diff --git a/src/builder/java/speiger/src/builder/PrimitiveCollectionsBuilder.java b/src/builder/java/speiger/src/builder/PrimitiveCollectionsBuilder.java index 8ab7a34..a750e89 100644 --- a/src/builder/java/speiger/src/builder/PrimitiveCollectionsBuilder.java +++ b/src/builder/java/speiger/src/builder/PrimitiveCollectionsBuilder.java @@ -1,270 +1,270 @@ -package speiger.src.builder; - -import java.io.BufferedWriter; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.StringJoiner; -import java.util.function.Consumer; -import java.util.stream.Stream; - -import speiger.src.builder.modules.AsyncModule; -import speiger.src.builder.modules.BaseModule; -import speiger.src.builder.modules.CollectionModule; -import speiger.src.builder.modules.FunctionModule; -import speiger.src.builder.modules.JavaModule; -import speiger.src.builder.modules.ListModule; -import speiger.src.builder.modules.MapModule; -import speiger.src.builder.modules.PairModule; -import speiger.src.builder.modules.PrioQueueModule; -import speiger.src.builder.modules.SetModule; -import speiger.src.builder.processor.TemplateProcess; -import speiger.src.builder.processor.TemplateProcessor; - -@SuppressWarnings("javadoc") -public class PrimitiveCollectionsBuilder extends TemplateProcessor -{ - private static final int SPECIAL = 0x1; //Detects if the Builder is generating tests - private static final int LOAD = 0x2; //If Configs should be loaded - private static final int ANTI_SAVE = SPECIAL | LOAD; //If save should be disabled since load/save shouldn't happen at the same time. - private static final int SAVE = 0x4; //if the configuration should be created - Set globalFlags = new HashSet<>(); - List simplePackages = new ArrayList<>(); - List biPackages = new ArrayList<>(); - List enumPackages = new ArrayList<>(); - Map requirements = new HashMap<>(); - SettingsManager manager = new SettingsManager(); - int flags; - - public PrimitiveCollectionsBuilder() - { - this(false); - } - - public PrimitiveCollectionsBuilder(boolean silencedSuccess) - { - super(silencedSuccess, Paths.get("src/builder/resources/speiger/assets/collections/templates/"), Paths.get("src/main/java/speiger/src/collections/"), Paths.get("src/builder/resources/speiger/assets/collections/")); - } - - public PrimitiveCollectionsBuilder(Path sourceFolder, Path outputFolder, Path dataFolder) - { - this(false, sourceFolder, outputFolder, dataFolder); - } - - public PrimitiveCollectionsBuilder(boolean silencedSuccess, Path sourceFolder, Path outputFolder, Path dataFolder) - { - super(silencedSuccess, sourceFolder, outputFolder, dataFolder); - } - - private PrimitiveCollectionsBuilder setFlags(int flags) { - this.flags = flags; - if((flags & ANTI_SAVE) != 0) { - this.flags &= ~SAVE; - } - return this; - } - - private static PrimitiveCollectionsBuilder createTests(boolean silent, int flags) { - return new PrimitiveCollectionsBuilder(silent, - Paths.get("src/builder/resources/speiger/assets/tests/templates/"), - Paths.get("src/test/java/speiger/src/tests/"), - Paths.get("src/builder/resources/speiger/assets/tests/")).setFlags(flags | SPECIAL); - } - - private static PrimitiveCollectionsBuilder createTesters(boolean silent, int flags) { - return new PrimitiveCollectionsBuilder(silent, - Paths.get("src/builder/resources/speiger/assets/testers/templates/"), - Paths.get("src/test/java/speiger/src/testers/"), - Paths.get("src/builder/resources/speiger/assets/testers/")).setFlags(flags | SPECIAL); - } - - @Override - protected boolean isFileValid(Path fileName) - { - return true; - } - - @Override - protected boolean relativePackages() - { - return true; - } - - @Override - protected boolean debugUnusedMappers() - { - return false; - } - - @Override - protected void afterFinish() - { - if((flags & SPECIAL) == 0 && getVersion() > 8) - { - Path basePath = Paths.get("src/main/java"); - try(BufferedWriter writer = Files.newBufferedWriter(basePath.resolve("module-info.java"))) - { - writer.write(getModuleInfo(basePath)); - } - catch(Exception e) - { - e.printStackTrace(); - } - } - } - - public List createModules() - { - List modules = new ArrayList<>(); - modules.add(JavaModule.INSTANCE); - modules.add(FunctionModule.INSTANCE); - modules.add(CollectionModule.INSTANCE); - modules.add(PrioQueueModule.INSTANCE); - modules.add(ListModule.INSTANCE); - modules.add(SetModule.INSTANCE); - modules.add(MapModule.INSTANCE); - modules.add(PairModule.INSTANCE); - modules.add(AsyncModule.INSTANCE); - return modules; - } - - - @Override - protected void init() - { - prepPackages(); - //Init Modules here - addModules(createModules()); - finishPackages(); - } - - public void addModules(List modules) - { - for(int i = 0,m=modules.size();i process) - { - List packages = getPackagesByRequirement(requirements.get(fileName)); - for(int i = 0,m=packages.size();i getPackagesByRequirement(RequiredType type) { - if(type == null) return simplePackages; - if(type == RequiredType.BI_CLASS) return biPackages; - if(type == RequiredType.ENUM) return enumPackages; - return Collections.emptyList(); - } - - private String getModuleInfo(Path basePath) { - StringJoiner joiner = new StringJoiner("\n", "", "\n"); - try(Stream stream = Files.walk(getOutputFolder())) - { - stream.filter(Files::isDirectory) - .filter(this::containsFiles) - .map(basePath::relativize) - .map(Path::toString) - .map(this::sanitize) - .forEach(T -> joiner.add("\texports "+T+";")); - } - catch(Exception e) - { - e.printStackTrace(); - throw new RuntimeException(e); - } - StringBuilder builder = new StringBuilder(); - builder.append("/** @author Speiger */\n"); - builder.append("module ").append(sanitize(basePath.relativize(getOutputFolder()).toString())).append(" {\n"); - builder.append(joiner.toString()).append("}"); - return builder.toString(); - } - - private String sanitize(String input) - { - return input.replace("\\", ".").replace("/", "."); - } - - private boolean containsFiles(Path path) - { - try(Stream stream = Files.walk(path, 1)) - { - return stream.filter(Files::isRegularFile).findFirst().isPresent(); - } - catch(Exception e) - { - e.printStackTrace(); - } - return false; - } - - private int getVersion() - { - String version = System.getProperty("java.version"); - if(version.startsWith("1.")) return Integer.parseInt(version.substring(2, 3)); - int dot = version.indexOf("."); - return Integer.parseInt(dot != -1 ? version.substring(0, dot) : version); - } - - public static void main(String...args) - { - try - { - Set flags = new HashSet<>(Arrays.asList(args)); - boolean silent = flags.contains("silent"); - boolean force = flags.contains("force"); - boolean tests = flags.contains("tests"); - boolean forceTests = flags.contains("force-tests"); - boolean load = flags.contains("load"); - boolean save = flags.contains("save"); - int flag = (load ? LOAD : 0) | (save ? SAVE : 0); - new PrimitiveCollectionsBuilder(silent).setFlags(flag).process(force); - if(tests) { - createTests(silent, flag).process(force || forceTests); - createTesters(silent, flag).process(force || forceTests); - } - } - catch(InterruptedException | IOException e) - { - e.printStackTrace(); - } - } -} +package speiger.src.builder; + +import java.io.BufferedWriter; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.StringJoiner; +import java.util.function.Consumer; +import java.util.stream.Stream; + +import speiger.src.builder.modules.AsyncModule; +import speiger.src.builder.modules.BaseModule; +import speiger.src.builder.modules.CollectionModule; +import speiger.src.builder.modules.FunctionModule; +import speiger.src.builder.modules.JavaModule; +import speiger.src.builder.modules.ListModule; +import speiger.src.builder.modules.MapModule; +import speiger.src.builder.modules.PairModule; +import speiger.src.builder.modules.PrioQueueModule; +import speiger.src.builder.modules.SetModule; +import speiger.src.builder.processor.TemplateProcess; +import speiger.src.builder.processor.TemplateProcessor; + +@SuppressWarnings("javadoc") +public class PrimitiveCollectionsBuilder extends TemplateProcessor +{ + private static final int SPECIAL = 0x1; //Detects if the Builder is generating tests + private static final int LOAD = 0x2; //If Configs should be loaded + private static final int ANTI_SAVE = SPECIAL | LOAD; //If save should be disabled since load/save shouldn't happen at the same time. + private static final int SAVE = 0x4; //if the configuration should be created + Set globalFlags = new HashSet<>(); + List simplePackages = new ArrayList<>(); + List biPackages = new ArrayList<>(); + List enumPackages = new ArrayList<>(); + Map requirements = new HashMap<>(); + SettingsManager manager = new SettingsManager(); + int flags; + + public PrimitiveCollectionsBuilder() + { + this(false); + } + + public PrimitiveCollectionsBuilder(boolean silencedSuccess) + { + super(silencedSuccess, Paths.get("src/builder/resources/speiger/assets/collections/templates/"), Paths.get("src/main/java/speiger/src/collections/"), Paths.get("src/builder/resources/speiger/assets/collections/")); + } + + public PrimitiveCollectionsBuilder(Path sourceFolder, Path outputFolder, Path dataFolder) + { + this(false, sourceFolder, outputFolder, dataFolder); + } + + public PrimitiveCollectionsBuilder(boolean silencedSuccess, Path sourceFolder, Path outputFolder, Path dataFolder) + { + super(silencedSuccess, sourceFolder, outputFolder, dataFolder); + } + + private PrimitiveCollectionsBuilder setFlags(int flags) { + this.flags = flags; + if((flags & ANTI_SAVE) != 0) { + this.flags &= ~SAVE; + } + return this; + } + + private static PrimitiveCollectionsBuilder createTests(boolean silent, int flags) { + return new PrimitiveCollectionsBuilder(silent, + Paths.get("src/builder/resources/speiger/assets/tests/templates/"), + Paths.get("src/test/java/speiger/src/tests/"), + Paths.get("src/builder/resources/speiger/assets/tests/")).setFlags(flags | SPECIAL); + } + + private static PrimitiveCollectionsBuilder createTesters(boolean silent, int flags) { + return new PrimitiveCollectionsBuilder(silent, + Paths.get("src/builder/resources/speiger/assets/testers/templates/"), + Paths.get("src/test/java/speiger/src/testers/"), + Paths.get("src/builder/resources/speiger/assets/testers/")).setFlags(flags | SPECIAL); + } + + @Override + protected boolean isFileValid(Path fileName) + { + return true; + } + + @Override + protected boolean relativePackages() + { + return true; + } + + @Override + protected boolean debugUnusedMappers() + { + return false; + } + + @Override + protected void afterFinish() + { + if((flags & SPECIAL) == 0 && getVersion() > 8) + { + Path basePath = Paths.get("src/main/java"); + try(BufferedWriter writer = Files.newBufferedWriter(basePath.resolve("module-info.java"))) + { + writer.write(getModuleInfo(basePath)); + } + catch(Exception e) + { + e.printStackTrace(); + } + } + } + + public List createModules() + { + List modules = new ArrayList<>(); + modules.add(JavaModule.INSTANCE); + modules.add(FunctionModule.INSTANCE); + modules.add(CollectionModule.INSTANCE); + modules.add(PrioQueueModule.INSTANCE); + modules.add(ListModule.INSTANCE); + modules.add(SetModule.INSTANCE); + modules.add(MapModule.INSTANCE); + modules.add(PairModule.INSTANCE); + modules.add(AsyncModule.INSTANCE); + return modules; + } + + + @Override + protected void init() + { + prepPackages(); + //Init Modules here + addModules(createModules()); + finishPackages(); + } + + public void addModules(List modules) + { + for(int i = 0,m=modules.size();i process) + { + List packages = getPackagesByRequirement(requirements.get(fileName)); + for(int i = 0,m=packages.size();i getPackagesByRequirement(RequiredType type) { + if(type == null) return simplePackages; + if(type == RequiredType.BI_CLASS) return biPackages; + if(type == RequiredType.ENUM) return enumPackages; + return Collections.emptyList(); + } + + private String getModuleInfo(Path basePath) { + StringJoiner joiner = new StringJoiner("\n", "", "\n"); + try(Stream stream = Files.walk(getOutputFolder())) + { + stream.filter(Files::isDirectory) + .filter(this::containsFiles) + .map(basePath::relativize) + .map(Path::toString) + .map(this::sanitize) + .forEach(T -> joiner.add("\texports "+T+";")); + } + catch(Exception e) + { + e.printStackTrace(); + throw new RuntimeException(e); + } + StringBuilder builder = new StringBuilder(); + builder.append("/** @author Speiger */\n"); + builder.append("module ").append(sanitize(basePath.relativize(getOutputFolder()).toString())).append(" {\n"); + builder.append(joiner.toString()).append("}"); + return builder.toString(); + } + + private String sanitize(String input) + { + return input.replace("\\", ".").replace("/", "."); + } + + private boolean containsFiles(Path path) + { + try(Stream stream = Files.walk(path, 1)) + { + return stream.filter(Files::isRegularFile).findFirst().isPresent(); + } + catch(Exception e) + { + e.printStackTrace(); + } + return false; + } + + private int getVersion() + { + String version = System.getProperty("java.version"); + if(version.startsWith("1.")) return Integer.parseInt(version.substring(2, 3)); + int dot = version.indexOf("."); + return Integer.parseInt(dot != -1 ? version.substring(0, dot) : version); + } + + public static void main(String...args) + { + try + { + Set flags = new HashSet<>(Arrays.asList(args)); + boolean silent = flags.contains("silent"); + boolean force = flags.contains("force"); + boolean tests = flags.contains("tests"); + boolean forceTests = flags.contains("force-tests"); + boolean load = flags.contains("load"); + boolean save = flags.contains("save"); + int flag = (load ? LOAD : 0) | (save ? SAVE : 0); + new PrimitiveCollectionsBuilder(silent).setFlags(flag).process(force); + if(tests) { + createTests(silent, flag).process(force || forceTests); + createTesters(silent, flag).process(force || forceTests); + } + } + catch(InterruptedException | IOException e) + { + e.printStackTrace(); + } + } +} diff --git a/src/builder/java/speiger/src/builder/modules/MapModule.java b/src/builder/java/speiger/src/builder/modules/MapModule.java index f697d2c..8ee2f0c 100644 --- a/src/builder/java/speiger/src/builder/modules/MapModule.java +++ b/src/builder/java/speiger/src/builder/modules/MapModule.java @@ -1,281 +1,281 @@ -package speiger.src.builder.modules; - -import java.util.Arrays; -import java.util.Set; -import java.util.TreeSet; - -import speiger.src.builder.ClassType; - -@SuppressWarnings("javadoc") -public class MapModule extends BaseModule -{ - public static final BaseModule INSTANCE = new MapModule(); - - @Override - public String getModuleName() { return "Map"; } - @Override - public boolean isBiModule() { return true; } - @Override - protected void loadVariables() {} - @Override - public boolean isModuleValid(ClassType keyType, ClassType valueType) { return keyType != ClassType.BOOLEAN; } - @Override - public boolean areDependenciesLoaded() { return isDependencyLoaded(SetModule.INSTANCE) && isDependencyLoaded(CollectionModule.INSTANCE, false); } - - @Override - public Set getModuleKeys(ClassType keyType, ClassType valueType) { - Set sets = new TreeSet<>(); - sets.addAll(Arrays.asList("Wrappers", "Implementations")); - sets.addAll(Arrays.asList("OrderedMap", "SortedMap")); - sets.addAll(Arrays.asList("ArrayMap", "ConcurrentMap", "ImmutableMap")); - sets.addAll(Arrays.asList("HashMap", "LinkedHashMap")); - sets.addAll(Arrays.asList("CustomHashMap", "LinkedCustomHashMap")); - sets.addAll(Arrays.asList("EnumMap", "LinkedEnumMap")); - sets.addAll(Arrays.asList("AVLTreeMap", "RBTreeMap")); - return sets; - } - - @Override - protected void loadFlags() - { - if(isModuleEnabled()) addFlag("MAP_MODULE"); - if(isModuleEnabled("Wrappers")) addFlag("MAPS_FEATURE"); - boolean implementations = isModuleEnabled("Implementations"); - boolean hashMap = implementations && isModuleEnabled("HashMap"); - boolean customHashMap = implementations && isModuleEnabled("CustomHashMap"); - boolean enumMap = implementations && isModuleEnabled("EnumMap"); - - if(isModuleEnabled("OrderedMap")) { - addFlag("ORDERED_MAP_FEATURE"); - if(isModuleEnabled("ArrayMap")) addFlag("ARRAY_MAP_FEATURE"); - if(hashMap && isModuleEnabled("LinkedHashMap")) addFlag("LINKED_MAP_FEATURE"); - if(customHashMap && isModuleEnabled("LinkedCustomHashMap")) addFlag("LINKED_CUSTOM_MAP_FEATURE"); - if(enumMap && isModuleEnabled("LinkedEnumMap")) addFlag("LINKED_ENUM_MAP_FEATURE"); - } - if(isModuleEnabled("SortedMap")) { - addFlag("SORTED_MAP_FEATURE"); - if(implementations && isModuleEnabled("AVLTreeMap")) addFlag("AVL_TREE_MAP_FEATURE"); - if(implementations && isModuleEnabled("RBTreeMap")) addFlag("RB_TREE_MAP_FEATURE"); - } - if(implementations && isModuleEnabled("ConcurrentMap")) addFlag("CONCURRENT_MAP_FEATURE"); - if(implementations && isModuleEnabled("ImmutableMap")) addFlag("IMMUTABLE_MAP_FEATURE"); - if(hashMap) addFlag("MAP_FEATURE"); - if(customHashMap) addFlag("CUSTOM_MAP_FEATURE"); - if(enumMap) addFlag("ENUM_MAP_FEATURE"); - } - - @Override - protected void loadBlockades() - { - if(!isModuleEnabled()) addBlockedFiles("Map", "AbstractMap"); - if(!isModuleEnabled("Wrappers")) addBlockedFiles("Maps"); - boolean implementations = !isModuleEnabled("Implementations"); - if(implementations || !isModuleEnabled("ImmutableMap")) addBlockedFiles("ImmutableOpenHashMap"); - if(implementations || !isModuleEnabled("ConcurrentMap")) addBlockedFiles("ConcurrentMap", "ConcurrentOpenHashMap"); - - boolean ordered = !isModuleEnabled("OrderedMap"); - if(ordered) addBlockedFiles("OrderedMap"); - boolean hashMap = implementations || !isModuleEnabled("HashMap"); - if(hashMap) addBlockedFiles("OpenHashMap"); - if(hashMap || ordered || !isModuleEnabled("LinkedHashMap")) addBlockedFiles("LinkedOpenHashMap"); - - boolean customHashMap = implementations || !isModuleEnabled("CustomHashMap"); - if(customHashMap) addBlockedFiles("OpenCustomHashMap"); - if(customHashMap || ordered || !isModuleEnabled("LinkedCustomHashMap")) addBlockedFiles("LinkedOpenCustomHashMap"); - - boolean enumMap = implementations || !isModuleEnabled("EnumMap"); - if(enumMap) addBlockedFiles("EnumMap"); - if(enumMap || ordered || !isModuleEnabled("LinkedEnumMap")) addBlockedFiles("LinkedEnumMap"); - - if(ordered || !isModuleEnabled("ArrayMap")) addBlockedFiles("ArrayMap"); - - boolean sorted = !isModuleEnabled("SortedMap"); - if(sorted) addBlockedFiles("SortedMap", "NavigableMap"); - if(implementations || sorted || !isModuleEnabled("AVLTreeMap")) addBlockedFiles("AVLTreeMap"); - if(implementations || sorted || !isModuleEnabled("RBTreeMap")) addBlockedFiles("RBTreeMap"); - - if(keyType == ClassType.BOOLEAN) - { - //Main Classes - addBlockedFiles("SortedMap", "NavigableMap", "RBTreeMap", "AVLTreeMap"); - addBlockedFiles("OrderedMap", "ArrayMap", "LinkedOpenHashMap", "LinkedOpenCustomHashMap"); - addBlockedFiles("ConcurrentMap", "ConcurrentOpenHashMap"); - addBlockedFiles("Map", "Maps", "AbstractMap", "ImmutableOpenHashMap", "OpenHashMap", "OpenCustomHashMap"); - - //Test Classes - addBlockedFiles("TestMap", "MapTests", "MapTestSuiteBuilder", "MapConstructorTests", "TestMapGenerator", "SimpleMapTestGenerator", "DerivedMapGenerators", "AbstractMapTester"); - addBlockedFiles("TestSortedMapGenerator", "OrderedMapTestSuiteBuilder", "NavigableMapTestSuiteBuilder", "SortedMapTestSuiteBuilder"); - addBlockedFiles("TestOrderedMapGenerator"); - addBlockedFilter(T -> T.endsWith("Tester") && (T.startsWith("Map") || T.startsWith("OrderedMap") || T.startsWith("SortedMap") || T.startsWith("NavigableMap"))); - } - } - - @Override - protected void loadRemappers() - { - //Main Classes - addBiRequirement("Map"); - addBiRequirement("SortedMap"); - addBiRequirement("OrderedMap"); - addBiRequirement("NavigableMap"); - addBiRequirement("ConcurrentMap"); - addBiRequirement("AbstractMap"); - addEnumRequirement("EnumMap"); - addEnumRequirement("LinkedEnumMap"); - addBiRequirement("ConcurrentOpenHashMap"); - addBiRequirement("ImmutableOpenHashMap"); - addBiRequirement("OpenHashMap"); - addBiRequirement("LinkedOpenHashMap"); - addBiRequirement("OpenCustomHashMap"); - addBiRequirement("LinkedOpenCustomHashMap"); - addBiRequirement("ArrayMap"); - addBiRequirement("RBTreeMap"); - addBiRequirement("AVLTreeMap"); - addBiRequirement("Maps"); - - addRemapper("AbstractMap", "Abstract%sMap"); - addRemapper("EnumMap", "Enum2%sMap"); - addRemapper("LinkedEnumMap", "LinkedEnum2%sMap"); - addRemapper("ImmutableOpenHashMap", "Immutable%sOpenHashMap"); - - //Test Classes - addBiRequirement("TestMapGenerator"); - addBiRequirement("TestSortedMapGenerator"); - addBiRequirement("TestOrderedMapGenerator"); - addBiRequirement("SimpleMapTestGenerator"); - addBiRequirement("DerivedMapGenerators"); - addBiRequirement("AbstractMapTester"); - addBiRequirement("MapTestSuiteBuilder"); - addBiRequirement("SortedMapTestSuiteBuilder"); - addBiRequirement("NavigableMapTestSuiteBuilder"); - addBiRequirement("OrderedMapTestSuiteBuilder"); - addBiRequirement("MapTests"); - addBiRequirement("MapConstructorTests"); - addBiRequirement("TestMap"); - addBiRequirement("MapAddToTester"); - addBiRequirement("MapSubFromTester"); - addBiRequirement("MapClearTester"); - addBiRequirement("MapComputeIfAbsentTester"); - addBiRequirement("MapComputeIfPresentTester"); - addBiRequirement("MapComputeTester"); - addBiRequirement("MapCopyTester"); - addBiRequirement("MapContainsTester"); - addBiRequirement("MapContainsKeyTester"); - addBiRequirement("MapContainsValueTester"); - addBiRequirement("MapCreatorTester"); - addBiRequirement("MapEntrySetTester"); - addBiRequirement("MapEqualsTester"); - addBiRequirement("MapForEachTester"); - addBiRequirement("MapGetOrDefaultTester"); - addBiRequirement("MapGetTester"); - addBiRequirement("MapHashCodeTester"); - addBiRequirement("MapIsEmptyTester"); - addBiRequirement("MapMergeTester"); - addBiRequirement("MapMergeBulkTester"); - addBiRequirement("MapPutAllArrayTester"); - addBiRequirement("MapPutAllTester"); - addBiRequirement("MapPutIfAbsentTester"); - addBiRequirement("MapPutTester"); - addBiRequirement("MapRemoveEntryTester"); - addBiRequirement("MapRemoveOrDefaultTester"); - addBiRequirement("MapRemoveTester"); - addBiRequirement("MapReplaceAllTester"); - addBiRequirement("MapReplaceEntryTester"); - addBiRequirement("MapReplaceTester"); - addBiRequirement("MapSizeTester"); - addBiRequirement("MapSupplyIfAbsentTester"); - addBiRequirement("MapToStringTester"); - addBiRequirement("NavigableMapNavigationTester"); - addBiRequirement("SortedMapNavigationTester"); - addBiRequirement("OrderedMapNavigationTester"); - addBiRequirement("OrderedMapMoveTester"); - addBiRequirement("MapConstructorTester"); - - addRemapper("TestMapGenerator", "Test%sMapGenerator"); - addRemapper("TestSortedMapGenerator", "Test%sSortedMapGenerator"); - addRemapper("TestOrderedMapGenerator", "Test%sOrderedMapGenerator"); - addRemapper("SimpleMapTestGenerator", "Simple%sMapTestGenerator"); - addRemapper("DerivedMapGenerators", "Derived%sMapGenerators"); - addRemapper("AbstractMapTester", "Abstract%sMapTester"); - addRemapper("TestMap", "Test%sMap"); - } - - @Override - protected void loadFunctions() - { - addFunctionValueMapper("BULK_MERGE", "mergeAll"); - addFunctionValueMappers("COMPUTE_IF_ABSENT", "compute%sIfAbsent"); - addFunctionValueMappers("COMPUTE_IF_PRESENT", "compute%sIfPresent"); - addFunctionValueMapper("COMPUTE", "compute"); - addFunctionMapper("DEQUEUE_LAST", "dequeueLast"); - addFunctionMapper("DEQUEUE", "dequeue"); - addSimpleMapper("ENTRY_SET", keyType.getFileType().toLowerCase()+"2"+valueType.getFileType()+"EntrySet"); - addFunctionMappers("FIRST_ENTRY_KEY", "first%sKey"); - addFunctionValueMappers("FIRST_ENTRY_VALUE", "first%sValue"); - if(keyType.isObject()) addFunctionValueMapper("GET_VALUE", valueType.isObject() ? "getObject" : "get"); - else addSimpleMapper("GET_VALUE", "get"); - addFunctionMappers("LAST_ENTRY_KEY", "last%sKey"); - addFunctionValueMappers("LAST_ENTRY_VALUE", "last%sValue"); - addFunctionValueMapper("MERGE", "merge"); - addFunctionMappers("POLL_FIRST_ENTRY_KEY", "pollFirst%sKey"); - addFunctionMappers("POLL_LAST_ENTRY_KEY", "pollLast%sKey"); - if(keyType.isObject()) addFunctionMapper("REMOVE_VALUE", "rem"); - else addSimpleMapper("REMOVE_VALUE", "remove"); - addFunctionMapper("REMOVE", "remove"); - addFunctionValueMappers("REPLACE_VALUES", valueType.isObject() ? "replaceObjects" : "replace%ss"); - addFunctionValueMappers("SUPPLY_IF_ABSENT", "supply%sIfAbsent"); - } - - @Override - protected void loadClasses() - { - //Implementation Classes - addAbstractBiMapper("IMMUTABLE_HASH_MAP", "Immutable%sOpenHashMap", "2"); - addBiClassMapper("LINKED_CUSTOM_HASH_MAP", "LinkedOpenCustomHashMap", "2"); - addBiClassMapper("LINKED_HASH_MAP", "LinkedOpenHashMap", "2"); - addBiClassMapper("CUSTOM_HASH_MAP", "OpenCustomHashMap", "2"); - addBiClassMapper("CONCURRENT_HASH_MAP", "ConcurrentOpenHashMap", "2"); - addBiClassMapper("AVL_TREE_MAP", "AVLTreeMap", "2"); - addBiClassMapper("RB_TREE_MAP", "RBTreeMap", "2"); - addFunctionValueMappers("LINKED_ENUM_MAP", valueType.isObject() ? "LinkedEnum2ObjectMap" : "LinkedEnum2%sMap"); - addFunctionValueMappers("ENUM_MAP", valueType.isObject() ? "Enum2ObjectMap" : "Enum2%sMap"); - addBiClassMapper("HASH_MAP", "OpenHashMap", "2"); - addBiClassMapper("ARRAY_MAP", "ArrayMap", "2"); - - //Abstract Classes - addAbstractBiMapper("ABSTRACT_MAP", "Abstract%sMap", "2"); - - //Helper Classes - addBiClassMapper("MAPS", "Maps", "2"); - - //Interfaces - addBiClassMapper("NAVIGABLE_MAP", "NavigableMap", "2"); - addBiClassMapper("ORDERED_MAP", "OrderedMap", "2"); - addBiClassMapper("SORTED_MAP", "SortedMap", "2"); - addBiClassMapper("CONCURRENT_MAP", "ConcurrentMap", "2"); - addBiClassMapper("MAP", "Map", "2"); - } - - @Override - protected void loadTestClasses() - { - //Implementation Classes - addAbstractBiMapper("SIMPLE_TEST_MAP", "Test%sMap", "2"); - addBiClassMapper("MAP_TESTS", "MapTests", "2"); - addAbstractBiMapper("NAVIGABLE_MAP_TEST_BUILDER", "%sNavigableMapTestSuiteBuilder", "2"); - addAbstractBiMapper("SORTED_MAP_TEST_BUILDER", "%sSortedMapTestSuiteBuilder", "2"); - addAbstractBiMapper("ORDERED_MAP_TEST_BUILDER", "%sOrderedMapTestSuiteBuilder", "2"); - addAbstractBiMapper("MAP_TEST_BUILDER", "%sMapTestSuiteBuilder", "2"); - - //Abstract Classes - addAbstractBiMapper("ABSTRACT_MAP_TESTER", "Abstract%sMapTester", "2"); - - //Helper Classes - addAbstractBiMapper("MAP_CONSTRUCTOR_TESTS", "%sMapConstructorTests", "2"); - addAbstractBiMapper("SIMPLE_MAP_TEST_GENERATOR", "Simple%sMapTestGenerator", "2"); - addAbstractBiMapper("DERIVED_MAP_GENERATORS", "Derived%sMapGenerators", "2"); - addAbstractBiMapper("TEST_ORDERED_MAP_GENERATOR", "Test%sOrderedMapGenerator", "2"); - addAbstractBiMapper("TEST_SORTED_MAP_GENERATOR", "Test%sSortedMapGenerator", "2"); - addAbstractBiMapper("TEST_MAP_GENERATOR", "Test%sMapGenerator", "2"); - } +package speiger.src.builder.modules; + +import java.util.Arrays; +import java.util.Set; +import java.util.TreeSet; + +import speiger.src.builder.ClassType; + +@SuppressWarnings("javadoc") +public class MapModule extends BaseModule +{ + public static final BaseModule INSTANCE = new MapModule(); + + @Override + public String getModuleName() { return "Map"; } + @Override + public boolean isBiModule() { return true; } + @Override + protected void loadVariables() {} + @Override + public boolean isModuleValid(ClassType keyType, ClassType valueType) { return keyType != ClassType.BOOLEAN; } + @Override + public boolean areDependenciesLoaded() { return isDependencyLoaded(SetModule.INSTANCE) && isDependencyLoaded(CollectionModule.INSTANCE, false); } + + @Override + public Set getModuleKeys(ClassType keyType, ClassType valueType) { + Set sets = new TreeSet<>(); + sets.addAll(Arrays.asList("Wrappers", "Implementations")); + sets.addAll(Arrays.asList("OrderedMap", "SortedMap")); + sets.addAll(Arrays.asList("ArrayMap", "ConcurrentMap", "ImmutableMap")); + sets.addAll(Arrays.asList("HashMap", "LinkedHashMap")); + sets.addAll(Arrays.asList("CustomHashMap", "LinkedCustomHashMap")); + sets.addAll(Arrays.asList("EnumMap", "LinkedEnumMap")); + sets.addAll(Arrays.asList("AVLTreeMap", "RBTreeMap")); + return sets; + } + + @Override + protected void loadFlags() + { + if(isModuleEnabled()) addFlag("MAP_MODULE"); + if(isModuleEnabled("Wrappers")) addFlag("MAPS_FEATURE"); + boolean implementations = isModuleEnabled("Implementations"); + boolean hashMap = implementations && isModuleEnabled("HashMap"); + boolean customHashMap = implementations && isModuleEnabled("CustomHashMap"); + boolean enumMap = implementations && isModuleEnabled("EnumMap"); + + if(isModuleEnabled("OrderedMap")) { + addFlag("ORDERED_MAP_FEATURE"); + if(isModuleEnabled("ArrayMap")) addFlag("ARRAY_MAP_FEATURE"); + if(hashMap && isModuleEnabled("LinkedHashMap")) addFlag("LINKED_MAP_FEATURE"); + if(customHashMap && isModuleEnabled("LinkedCustomHashMap")) addFlag("LINKED_CUSTOM_MAP_FEATURE"); + if(enumMap && isModuleEnabled("LinkedEnumMap")) addFlag("LINKED_ENUM_MAP_FEATURE"); + } + if(isModuleEnabled("SortedMap")) { + addFlag("SORTED_MAP_FEATURE"); + if(implementations && isModuleEnabled("AVLTreeMap")) addFlag("AVL_TREE_MAP_FEATURE"); + if(implementations && isModuleEnabled("RBTreeMap")) addFlag("RB_TREE_MAP_FEATURE"); + } + if(implementations && isModuleEnabled("ConcurrentMap")) addFlag("CONCURRENT_MAP_FEATURE"); + if(implementations && isModuleEnabled("ImmutableMap")) addFlag("IMMUTABLE_MAP_FEATURE"); + if(hashMap) addFlag("MAP_FEATURE"); + if(customHashMap) addFlag("CUSTOM_MAP_FEATURE"); + if(enumMap) addFlag("ENUM_MAP_FEATURE"); + } + + @Override + protected void loadBlockades() + { + if(!isModuleEnabled()) addBlockedFiles("Map", "AbstractMap"); + if(!isModuleEnabled("Wrappers")) addBlockedFiles("Maps"); + boolean implementations = !isModuleEnabled("Implementations"); + if(implementations || !isModuleEnabled("ImmutableMap")) addBlockedFiles("ImmutableOpenHashMap"); + if(implementations || !isModuleEnabled("ConcurrentMap")) addBlockedFiles("ConcurrentMap", "ConcurrentOpenHashMap"); + + boolean ordered = !isModuleEnabled("OrderedMap"); + if(ordered) addBlockedFiles("OrderedMap"); + boolean hashMap = implementations || !isModuleEnabled("HashMap"); + if(hashMap) addBlockedFiles("OpenHashMap"); + if(hashMap || ordered || !isModuleEnabled("LinkedHashMap")) addBlockedFiles("LinkedOpenHashMap"); + + boolean customHashMap = implementations || !isModuleEnabled("CustomHashMap"); + if(customHashMap) addBlockedFiles("OpenCustomHashMap"); + if(customHashMap || ordered || !isModuleEnabled("LinkedCustomHashMap")) addBlockedFiles("LinkedOpenCustomHashMap"); + + boolean enumMap = implementations || !isModuleEnabled("EnumMap"); + if(enumMap) addBlockedFiles("EnumMap"); + if(enumMap || ordered || !isModuleEnabled("LinkedEnumMap")) addBlockedFiles("LinkedEnumMap"); + + if(ordered || !isModuleEnabled("ArrayMap")) addBlockedFiles("ArrayMap"); + + boolean sorted = !isModuleEnabled("SortedMap"); + if(sorted) addBlockedFiles("SortedMap", "NavigableMap"); + if(implementations || sorted || !isModuleEnabled("AVLTreeMap")) addBlockedFiles("AVLTreeMap"); + if(implementations || sorted || !isModuleEnabled("RBTreeMap")) addBlockedFiles("RBTreeMap"); + + if(keyType == ClassType.BOOLEAN) + { + //Main Classes + addBlockedFiles("SortedMap", "NavigableMap", "RBTreeMap", "AVLTreeMap"); + addBlockedFiles("OrderedMap", "ArrayMap", "LinkedOpenHashMap", "LinkedOpenCustomHashMap"); + addBlockedFiles("ConcurrentMap", "ConcurrentOpenHashMap"); + addBlockedFiles("Map", "Maps", "AbstractMap", "ImmutableOpenHashMap", "OpenHashMap", "OpenCustomHashMap"); + + //Test Classes + addBlockedFiles("TestMap", "MapTests", "MapTestSuiteBuilder", "MapConstructorTests", "TestMapGenerator", "SimpleMapTestGenerator", "DerivedMapGenerators", "AbstractMapTester"); + addBlockedFiles("TestSortedMapGenerator", "OrderedMapTestSuiteBuilder", "NavigableMapTestSuiteBuilder", "SortedMapTestSuiteBuilder"); + addBlockedFiles("TestOrderedMapGenerator"); + addBlockedFilter(T -> T.endsWith("Tester") && (T.startsWith("Map") || T.startsWith("OrderedMap") || T.startsWith("SortedMap") || T.startsWith("NavigableMap"))); + } + } + + @Override + protected void loadRemappers() + { + //Main Classes + addBiRequirement("Map"); + addBiRequirement("SortedMap"); + addBiRequirement("OrderedMap"); + addBiRequirement("NavigableMap"); + addBiRequirement("ConcurrentMap"); + addBiRequirement("AbstractMap"); + addEnumRequirement("EnumMap"); + addEnumRequirement("LinkedEnumMap"); + addBiRequirement("ConcurrentOpenHashMap"); + addBiRequirement("ImmutableOpenHashMap"); + addBiRequirement("OpenHashMap"); + addBiRequirement("LinkedOpenHashMap"); + addBiRequirement("OpenCustomHashMap"); + addBiRequirement("LinkedOpenCustomHashMap"); + addBiRequirement("ArrayMap"); + addBiRequirement("RBTreeMap"); + addBiRequirement("AVLTreeMap"); + addBiRequirement("Maps"); + + addRemapper("AbstractMap", "Abstract%sMap"); + addRemapper("EnumMap", "Enum2%sMap"); + addRemapper("LinkedEnumMap", "LinkedEnum2%sMap"); + addRemapper("ImmutableOpenHashMap", "Immutable%sOpenHashMap"); + + //Test Classes + addBiRequirement("TestMapGenerator"); + addBiRequirement("TestSortedMapGenerator"); + addBiRequirement("TestOrderedMapGenerator"); + addBiRequirement("SimpleMapTestGenerator"); + addBiRequirement("DerivedMapGenerators"); + addBiRequirement("AbstractMapTester"); + addBiRequirement("MapTestSuiteBuilder"); + addBiRequirement("SortedMapTestSuiteBuilder"); + addBiRequirement("NavigableMapTestSuiteBuilder"); + addBiRequirement("OrderedMapTestSuiteBuilder"); + addBiRequirement("MapTests"); + addBiRequirement("MapConstructorTests"); + addBiRequirement("TestMap"); + addBiRequirement("MapAddToTester"); + addBiRequirement("MapSubFromTester"); + addBiRequirement("MapClearTester"); + addBiRequirement("MapComputeIfAbsentTester"); + addBiRequirement("MapComputeIfPresentTester"); + addBiRequirement("MapComputeTester"); + addBiRequirement("MapCopyTester"); + addBiRequirement("MapContainsTester"); + addBiRequirement("MapContainsKeyTester"); + addBiRequirement("MapContainsValueTester"); + addBiRequirement("MapCreatorTester"); + addBiRequirement("MapEntrySetTester"); + addBiRequirement("MapEqualsTester"); + addBiRequirement("MapForEachTester"); + addBiRequirement("MapGetOrDefaultTester"); + addBiRequirement("MapGetTester"); + addBiRequirement("MapHashCodeTester"); + addBiRequirement("MapIsEmptyTester"); + addBiRequirement("MapMergeTester"); + addBiRequirement("MapMergeBulkTester"); + addBiRequirement("MapPutAllArrayTester"); + addBiRequirement("MapPutAllTester"); + addBiRequirement("MapPutIfAbsentTester"); + addBiRequirement("MapPutTester"); + addBiRequirement("MapRemoveEntryTester"); + addBiRequirement("MapRemoveOrDefaultTester"); + addBiRequirement("MapRemoveTester"); + addBiRequirement("MapReplaceAllTester"); + addBiRequirement("MapReplaceEntryTester"); + addBiRequirement("MapReplaceTester"); + addBiRequirement("MapSizeTester"); + addBiRequirement("MapSupplyIfAbsentTester"); + addBiRequirement("MapToStringTester"); + addBiRequirement("NavigableMapNavigationTester"); + addBiRequirement("SortedMapNavigationTester"); + addBiRequirement("OrderedMapNavigationTester"); + addBiRequirement("OrderedMapMoveTester"); + addBiRequirement("MapConstructorTester"); + + addRemapper("TestMapGenerator", "Test%sMapGenerator"); + addRemapper("TestSortedMapGenerator", "Test%sSortedMapGenerator"); + addRemapper("TestOrderedMapGenerator", "Test%sOrderedMapGenerator"); + addRemapper("SimpleMapTestGenerator", "Simple%sMapTestGenerator"); + addRemapper("DerivedMapGenerators", "Derived%sMapGenerators"); + addRemapper("AbstractMapTester", "Abstract%sMapTester"); + addRemapper("TestMap", "Test%sMap"); + } + + @Override + protected void loadFunctions() + { + addFunctionValueMapper("BULK_MERGE", "mergeAll"); + addFunctionValueMappers("COMPUTE_IF_ABSENT", "compute%sIfAbsent"); + addFunctionValueMappers("COMPUTE_IF_PRESENT", "compute%sIfPresent"); + addFunctionValueMapper("COMPUTE", "compute"); + addFunctionMapper("DEQUEUE_LAST", "dequeueLast"); + addFunctionMapper("DEQUEUE", "dequeue"); + addSimpleMapper("ENTRY_SET", keyType.getFileType().toLowerCase()+"2"+valueType.getFileType()+"EntrySet"); + addFunctionMappers("FIRST_ENTRY_KEY", "first%sKey"); + addFunctionValueMappers("FIRST_ENTRY_VALUE", "first%sValue"); + if(keyType.isObject()) addFunctionValueMapper("GET_VALUE", valueType.isObject() ? "getObject" : "get"); + else addSimpleMapper("GET_VALUE", "get"); + addFunctionMappers("LAST_ENTRY_KEY", "last%sKey"); + addFunctionValueMappers("LAST_ENTRY_VALUE", "last%sValue"); + addFunctionValueMapper("MERGE", "merge"); + addFunctionMappers("POLL_FIRST_ENTRY_KEY", "pollFirst%sKey"); + addFunctionMappers("POLL_LAST_ENTRY_KEY", "pollLast%sKey"); + if(keyType.isObject()) addFunctionMapper("REMOVE_VALUE", "rem"); + else addSimpleMapper("REMOVE_VALUE", "remove"); + addFunctionMapper("REMOVE", "remove"); + addFunctionValueMappers("REPLACE_VALUES", valueType.isObject() ? "replaceObjects" : "replace%ss"); + addFunctionValueMappers("SUPPLY_IF_ABSENT", "supply%sIfAbsent"); + } + + @Override + protected void loadClasses() + { + //Implementation Classes + addAbstractBiMapper("IMMUTABLE_HASH_MAP", "Immutable%sOpenHashMap", "2"); + addBiClassMapper("LINKED_CUSTOM_HASH_MAP", "LinkedOpenCustomHashMap", "2"); + addBiClassMapper("LINKED_HASH_MAP", "LinkedOpenHashMap", "2"); + addBiClassMapper("CUSTOM_HASH_MAP", "OpenCustomHashMap", "2"); + addBiClassMapper("CONCURRENT_HASH_MAP", "ConcurrentOpenHashMap", "2"); + addBiClassMapper("AVL_TREE_MAP", "AVLTreeMap", "2"); + addBiClassMapper("RB_TREE_MAP", "RBTreeMap", "2"); + addFunctionValueMappers("LINKED_ENUM_MAP", valueType.isObject() ? "LinkedEnum2ObjectMap" : "LinkedEnum2%sMap"); + addFunctionValueMappers("ENUM_MAP", valueType.isObject() ? "Enum2ObjectMap" : "Enum2%sMap"); + addBiClassMapper("HASH_MAP", "OpenHashMap", "2"); + addBiClassMapper("ARRAY_MAP", "ArrayMap", "2"); + + //Abstract Classes + addAbstractBiMapper("ABSTRACT_MAP", "Abstract%sMap", "2"); + + //Helper Classes + addBiClassMapper("MAPS", "Maps", "2"); + + //Interfaces + addBiClassMapper("NAVIGABLE_MAP", "NavigableMap", "2"); + addBiClassMapper("ORDERED_MAP", "OrderedMap", "2"); + addBiClassMapper("SORTED_MAP", "SortedMap", "2"); + addBiClassMapper("CONCURRENT_MAP", "ConcurrentMap", "2"); + addBiClassMapper("MAP", "Map", "2"); + } + + @Override + protected void loadTestClasses() + { + //Implementation Classes + addAbstractBiMapper("SIMPLE_TEST_MAP", "Test%sMap", "2"); + addBiClassMapper("MAP_TESTS", "MapTests", "2"); + addAbstractBiMapper("NAVIGABLE_MAP_TEST_BUILDER", "%sNavigableMapTestSuiteBuilder", "2"); + addAbstractBiMapper("SORTED_MAP_TEST_BUILDER", "%sSortedMapTestSuiteBuilder", "2"); + addAbstractBiMapper("ORDERED_MAP_TEST_BUILDER", "%sOrderedMapTestSuiteBuilder", "2"); + addAbstractBiMapper("MAP_TEST_BUILDER", "%sMapTestSuiteBuilder", "2"); + + //Abstract Classes + addAbstractBiMapper("ABSTRACT_MAP_TESTER", "Abstract%sMapTester", "2"); + + //Helper Classes + addAbstractBiMapper("MAP_CONSTRUCTOR_TESTS", "%sMapConstructorTests", "2"); + addAbstractBiMapper("SIMPLE_MAP_TEST_GENERATOR", "Simple%sMapTestGenerator", "2"); + addAbstractBiMapper("DERIVED_MAP_GENERATORS", "Derived%sMapGenerators", "2"); + addAbstractBiMapper("TEST_ORDERED_MAP_GENERATOR", "Test%sOrderedMapGenerator", "2"); + addAbstractBiMapper("TEST_SORTED_MAP_GENERATOR", "Test%sSortedMapGenerator", "2"); + addAbstractBiMapper("TEST_MAP_GENERATOR", "Test%sMapGenerator", "2"); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/collections/templates/collections/AbstractCollection.template b/src/builder/resources/speiger/assets/collections/templates/collections/AbstractCollection.template index fedde02..78680e1 100644 --- a/src/builder/resources/speiger/assets/collections/templates/collections/AbstractCollection.template +++ b/src/builder/resources/speiger/assets/collections/templates/collections/AbstractCollection.template @@ -1,266 +1,266 @@ -package speiger.src.collections.PACKAGE.collections; - -import java.util.Collection; -import java.util.Objects; -import java.util.AbstractCollection; -#if TYPE_OBJECT -import java.util.function.Consumer; -#endif - -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.functions.CONSUMER; -import speiger.src.collections.PACKAGE.utils.ITERATORS; -#endif -import speiger.src.collections.PACKAGE.utils.ARRAYS; - -/** - * Abstract Type Specific Collection that reduces boxing/unboxing - * @Type(T) - */ -public abstract class ABSTRACT_COLLECTION KEY_GENERIC_TYPE extends AbstractCollection implements COLLECTION KEY_GENERIC_TYPE -{ - @Override - public abstract ITERATOR KEY_GENERIC_TYPE iterator(); - -#if !TYPE_OBJECT - /** {@inheritDoc} - *

This default implementation delegates to the corresponding type-specific function. - * @deprecated Please use the corresponding type-specific function instead. - */ - @Override - @Deprecated - public boolean add(CLASS_TYPE e) { return COLLECTION.super.add(e); } - -#endif - @Override - public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) { - boolean modified = false; - for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();modified |= add(iter.NEXT())); - return modified; - } - - @Override - public COLLECTION KEY_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); } - -#if !TYPE_OBJECT - /** {@inheritDoc} - *

This default implementation delegates to the corresponding type-specific function. - * @deprecated Please use the corresponding type-specific function instead. - */ - @Override - @Deprecated - public boolean contains(Object e) { return COLLECTION.super.contains(e); } - - /** - * A Type-Specific implementation of contains. This implementation iterates over the elements and returns true if the value match. - * @param e the element that should be searched for. - * @return true if the value was found. - */ - @Override - public boolean contains(KEY_TYPE e) { - for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { if(KEY_EQUALS(iter.NEXT(), e)) return true; } - return false; - } - - /** {@inheritDoc} - *

This default implementation delegates to the corresponding type-specific function. - * @deprecated Please use the corresponding type-specific function instead. - */ - @Override - @Deprecated - public boolean addAll(Collection c) - { - return c instanceof COLLECTION ? addAll((COLLECTION KEY_GENERIC_TYPE)c) : super.addAll(c); - } -#endif - - /** - * A Type-Specific implementation of containsAll. This implementation iterates over all elements and checks all elements are present in the other collection. - * @param c the collection that should be checked if it contains all elements. - * @return true if all elements were found in the collection - * @throws java.lang.NullPointerException if the collection is null - */ - @Override - public boolean containsAll(COLLECTION KEY_GENERIC_TYPE c) { - Objects.requireNonNull(c); - if(c.isEmpty()) return true; - for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();) - if(!contains(iter.NEXT())) - return false; - return true; - } - - @Override - public boolean containsAll(Collection c) { - Objects.requireNonNull(c); - return c instanceof COLLECTION ? containsAll((COLLECTION KEY_GENERIC_TYPE)c) : super.containsAll(c); - } - - /** - * This implementation iterates over the elements of the collection and checks if they are stored in this collection - * @param c the elements that should be checked for - * @return true if any element is in this collection - * @throws java.lang.NullPointerException if the collection is null - */ - @Override - @Primitive - public boolean containsAny(Collection c) { - Objects.requireNonNull(c); - if(c.isEmpty()) return false; - for(Object e : c) - if(contains(e)) - return true; - return false; - } - - /** - * This implementation iterates over the elements of the collection and checks if they are stored in this collection. - * @param c the elements that should be checked for - * @return true if any element is in this collection - * @throws java.lang.NullPointerException if the collection is null - */ - @Override - public boolean containsAny(COLLECTION KEY_GENERIC_TYPE c) { - Objects.requireNonNull(c); - if(c.isEmpty()) return false; - for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();) - if(contains(iter.NEXT())) - return true; - return false; - } - -#if !TYPE_OBJECT - /** {@inheritDoc} - *

This default implementation delegates to the corresponding type-specific function. - * @deprecated Please use the corresponding type-specific function instead. - */ - @Override - @Deprecated - public boolean remove(Object e) { return COLLECTION.super.remove(e); } - - /** - * A Type-Specific implementation of remove. This implementation iterates over the elements until it finds the element that is searched for or it runs out of elements. - * It stops after finding the first element - * @param e the element that is searched for - * @return true if the element was found and removed. - */ - @Override - public boolean REMOVE_KEY(KEY_TYPE e) { - for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { - if(KEY_EQUALS(iter.NEXT(), e)) { - iter.remove(); - return true; - } - } - return false; - } - -#endif - /** - * A Type-Specific implementation of removeAll. This Implementation iterates over all elements and removes them as they were found in the other collection. - * @param c the elements that should be deleted - * @return true if the collection was modified. - * @throws java.lang.NullPointerException if the collection is null - */ - @Override - public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) { - Objects.requireNonNull(c); - if(c.isEmpty()) return false; - boolean modified = false; - for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { - if(c.contains(iter.NEXT())) { - iter.remove(); - modified = true; - } - } - return modified; - } - - @Override - public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { - Objects.requireNonNull(c); - if(c.isEmpty()) return false; - Objects.requireNonNull(r); - boolean modified = false; - for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { - KEY_TYPE e = iter.NEXT(); - if(c.contains(e)) { - r.accept(e); - iter.remove(); - modified = true; - } - } - return modified; - } - - /** - * A Type-Specific implementation of retainAll. This Implementation iterates over all elements and removes them as they were not found in the other collection. - * @param c the elements that should be kept - * @return true if the collection was modified. - * @throws java.lang.NullPointerException if the collection is null - */ - @Override - public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) { - Objects.requireNonNull(c); - if(c.isEmpty()) { - boolean modified = !isEmpty(); - clear(); - return modified; - } - boolean modified = false; - for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { - if(!c.contains(iter.NEXT())) { - iter.remove(); - modified = true; - } - } - return modified; - } - - @Override - public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { - Objects.requireNonNull(c); - Objects.requireNonNull(r); - if(c.isEmpty()) { - boolean modified = !isEmpty(); - forEach(r); - clear(); - return modified; - } - boolean modified = false; - for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { - KEY_TYPE e = iter.NEXT(); - if(!c.contains(e)) { - r.accept(e); - iter.remove(); - modified = true; - } - } - return modified; - } - -#if !TYPE_OBJECT - /** - * A Type-Specific implementation of toArray that links to {@link #TO_ARRAY(KEY_TYPE[])} with a newly created array. - * @return an array containing all of the elements in this collection - */ - @Override - public KEY_TYPE[] TO_ARRAY() { - if(isEmpty()) return ARRAYS.EMPTY_ARRAY; - return TO_ARRAY(new KEY_TYPE[size()]); - } - - /** - * A Type-Specific implementation of toArray. This implementation iterates over all elements and unwraps them into primitive type. - * @param a array that the elements should be injected to. If null or to small a new array with the right size is created - * @return an array containing all of the elements in this collection - */ - @Override - public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) { - if(a == null || a.length < size()) a = new KEY_TYPE[size()]; - ITERATORS.unwrap(a, iterator()); - if (a.length > size()) a[size()] = EMPTY_KEY_VALUE; - return a; - } -#endif +package speiger.src.collections.PACKAGE.collections; + +import java.util.Collection; +import java.util.Objects; +import java.util.AbstractCollection; +#if TYPE_OBJECT +import java.util.function.Consumer; +#endif + +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.functions.CONSUMER; +import speiger.src.collections.PACKAGE.utils.ITERATORS; +import speiger.src.collections.PACKAGE.utils.ARRAYS; +#endif + +/** + * Abstract Type Specific Collection that reduces boxing/unboxing + * @Type(T) + */ +public abstract class ABSTRACT_COLLECTION KEY_GENERIC_TYPE extends AbstractCollection implements COLLECTION KEY_GENERIC_TYPE +{ + @Override + public abstract ITERATOR KEY_GENERIC_TYPE iterator(); + +#if !TYPE_OBJECT + /** {@inheritDoc} + *

This default implementation delegates to the corresponding type-specific function. + * @deprecated Please use the corresponding type-specific function instead. + */ + @Override + @Deprecated + public boolean add(CLASS_TYPE e) { return COLLECTION.super.add(e); } + +#endif + @Override + public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) { + boolean modified = false; + for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();modified |= add(iter.NEXT())); + return modified; + } + + @Override + public COLLECTION KEY_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); } + +#if !TYPE_OBJECT + /** {@inheritDoc} + *

This default implementation delegates to the corresponding type-specific function. + * @deprecated Please use the corresponding type-specific function instead. + */ + @Override + @Deprecated + public boolean contains(Object e) { return COLLECTION.super.contains(e); } + + /** + * A Type-Specific implementation of contains. This implementation iterates over the elements and returns true if the value match. + * @param e the element that should be searched for. + * @return true if the value was found. + */ + @Override + public boolean contains(KEY_TYPE e) { + for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { if(KEY_EQUALS(iter.NEXT(), e)) return true; } + return false; + } + + /** {@inheritDoc} + *

This default implementation delegates to the corresponding type-specific function. + * @deprecated Please use the corresponding type-specific function instead. + */ + @Override + @Deprecated + public boolean addAll(Collection c) + { + return c instanceof COLLECTION ? addAll((COLLECTION KEY_GENERIC_TYPE)c) : super.addAll(c); + } +#endif + + /** + * A Type-Specific implementation of containsAll. This implementation iterates over all elements and checks all elements are present in the other collection. + * @param c the collection that should be checked if it contains all elements. + * @return true if all elements were found in the collection + * @throws java.lang.NullPointerException if the collection is null + */ + @Override + public boolean containsAll(COLLECTION KEY_GENERIC_TYPE c) { + Objects.requireNonNull(c); + if(c.isEmpty()) return true; + for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();) + if(!contains(iter.NEXT())) + return false; + return true; + } + + @Override + public boolean containsAll(Collection c) { + Objects.requireNonNull(c); + return c instanceof COLLECTION ? containsAll((COLLECTION KEY_GENERIC_TYPE)c) : super.containsAll(c); + } + + /** + * This implementation iterates over the elements of the collection and checks if they are stored in this collection + * @param c the elements that should be checked for + * @return true if any element is in this collection + * @throws java.lang.NullPointerException if the collection is null + */ + @Override + @Primitive + public boolean containsAny(Collection c) { + Objects.requireNonNull(c); + if(c.isEmpty()) return false; + for(Object e : c) + if(contains(e)) + return true; + return false; + } + + /** + * This implementation iterates over the elements of the collection and checks if they are stored in this collection. + * @param c the elements that should be checked for + * @return true if any element is in this collection + * @throws java.lang.NullPointerException if the collection is null + */ + @Override + public boolean containsAny(COLLECTION KEY_GENERIC_TYPE c) { + Objects.requireNonNull(c); + if(c.isEmpty()) return false; + for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();) + if(contains(iter.NEXT())) + return true; + return false; + } + +#if !TYPE_OBJECT + /** {@inheritDoc} + *

This default implementation delegates to the corresponding type-specific function. + * @deprecated Please use the corresponding type-specific function instead. + */ + @Override + @Deprecated + public boolean remove(Object e) { return COLLECTION.super.remove(e); } + + /** + * A Type-Specific implementation of remove. This implementation iterates over the elements until it finds the element that is searched for or it runs out of elements. + * It stops after finding the first element + * @param e the element that is searched for + * @return true if the element was found and removed. + */ + @Override + public boolean REMOVE_KEY(KEY_TYPE e) { + for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { + if(KEY_EQUALS(iter.NEXT(), e)) { + iter.remove(); + return true; + } + } + return false; + } + +#endif + /** + * A Type-Specific implementation of removeAll. This Implementation iterates over all elements and removes them as they were found in the other collection. + * @param c the elements that should be deleted + * @return true if the collection was modified. + * @throws java.lang.NullPointerException if the collection is null + */ + @Override + public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) { + Objects.requireNonNull(c); + if(c.isEmpty()) return false; + boolean modified = false; + for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { + if(c.contains(iter.NEXT())) { + iter.remove(); + modified = true; + } + } + return modified; + } + + @Override + public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { + Objects.requireNonNull(c); + if(c.isEmpty()) return false; + Objects.requireNonNull(r); + boolean modified = false; + for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { + KEY_TYPE e = iter.NEXT(); + if(c.contains(e)) { + r.accept(e); + iter.remove(); + modified = true; + } + } + return modified; + } + + /** + * A Type-Specific implementation of retainAll. This Implementation iterates over all elements and removes them as they were not found in the other collection. + * @param c the elements that should be kept + * @return true if the collection was modified. + * @throws java.lang.NullPointerException if the collection is null + */ + @Override + public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) { + Objects.requireNonNull(c); + if(c.isEmpty()) { + boolean modified = !isEmpty(); + clear(); + return modified; + } + boolean modified = false; + for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { + if(!c.contains(iter.NEXT())) { + iter.remove(); + modified = true; + } + } + return modified; + } + + @Override + public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { + Objects.requireNonNull(c); + Objects.requireNonNull(r); + if(c.isEmpty()) { + boolean modified = !isEmpty(); + forEach(r); + clear(); + return modified; + } + boolean modified = false; + for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { + KEY_TYPE e = iter.NEXT(); + if(!c.contains(e)) { + r.accept(e); + iter.remove(); + modified = true; + } + } + return modified; + } + +#if !TYPE_OBJECT + /** + * A Type-Specific implementation of toArray that links to {@link #TO_ARRAY(KEY_TYPE[])} with a newly created array. + * @return an array containing all of the elements in this collection + */ + @Override + public KEY_TYPE[] TO_ARRAY() { + if(isEmpty()) return ARRAYS.EMPTY_ARRAY; + return TO_ARRAY(new KEY_TYPE[size()]); + } + + /** + * A Type-Specific implementation of toArray. This implementation iterates over all elements and unwraps them into primitive type. + * @param a array that the elements should be injected to. If null or to small a new array with the right size is created + * @return an array containing all of the elements in this collection + */ + @Override + public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) { + if(a == null || a.length < size()) a = new KEY_TYPE[size()]; + ITERATORS.unwrap(a, iterator()); + if (a.length > size()) a[size()] = EMPTY_KEY_VALUE; + return a; + } +#endif } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/collections/templates/collections/Collection.template b/src/builder/resources/speiger/assets/collections/templates/collections/Collection.template index e0a40ec..9abc694 100644 --- a/src/builder/resources/speiger/assets/collections/templates/collections/Collection.template +++ b/src/builder/resources/speiger/assets/collections/templates/collections/Collection.template @@ -1,322 +1,323 @@ -package speiger.src.collections.PACKAGE.collections; - -import java.util.Collection; -#if PRIMITIVES -import java.util.Objects; -import java.util.function.JAVA_PREDICATE; -import java.util.function.Predicate; -#if SPLIT_ITERATOR_FEATURE && STREAM_FEATURE -import java.util.stream.JAVA_STREAM; -import java.util.stream.StreamSupport; -#endif -#endif -#if TYPE_OBJECT -import java.util.function.Consumer; -import java.util.function.IntFunction; -#else -import speiger.src.collections.PACKAGE.functions.CONSUMER; -#endif -#if SPLIT_ITERATOR_FEATURE -import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS; -#endif -import speiger.src.collections.PACKAGE.utils.COLLECTIONS; -import speiger.src.collections.utils.ISizeProvider; -import speiger.src.collections.utils.SanityChecks; - -/** - * A Type-Specific {@link Collection} that reduces (un)boxing - * @Type(T) - */ -public interface COLLECTION KEY_GENERIC_TYPE extends Collection, ITERABLE KEY_GENERIC_TYPE, ISizeProvider -{ -#if !TYPE_OBJECT - /** - * A Type-Specific add function to reduce (un)boxing - * @param o the element that should be added - * @return true if the element was added to the collection - */ - public boolean add(KEY_TYPE o); - -#endif - /** - * A Type-Specific addAll function to reduce (un)boxing - * @param c the collection of elements that should be added - * @return true if elements were added into the collection - */ - public boolean addAll(COLLECTION KEY_GENERIC_TYPE c); - - /** - * A Type-Specific Array based addAll method to reduce the amount of Wrapping - * @param e the elements that should be added - * @return if the collection was modified - */ - public default boolean addAll(KEY_TYPE... e) { return addAll(e, 0, e.length); } - - /** - * A Type-Specific Array based addAll method to reduce the amount of Wrapping - * @param e the elements that should be added - * @param length how many elements of the array should be added - * @return if the collection was modified - */ - public default boolean addAll(KEY_TYPE[] e, int length) { return addAll(e, 0, length); } - - /** - * A Type-Specific Array based addAll method to reduce the amount of Wrapping - * @param e the elements that should be added - * @param offset where to start within the array - * @param length how many elements of the array should be added - * @return if the collection was modified - */ - public default boolean addAll(KEY_TYPE[] e, int offset, int length) { - if(length <= 0) return false; - SanityChecks.checkArrayCapacity(e.length, offset, length); - boolean added = false; - for(int i = 0;i c); - -#if !TYPE_OBJECT - /** - * A Type-Specific remove function that reduces (un)boxing. - * @param o the element that should be removed - * @return true if the element was removed - * @see Collection#remove(Object) - */ - public boolean REMOVE_KEY(KEY_TYPE o); - -#endif - /** - * A Type-Specific removeAll function that reduces (un)boxing. - * @param c the collection of elements that should be removed - * @return true if any element was removed - * @see Collection#removeAll(Collection) - */ - public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c); - - /** - * A Type-Specific removeAll function that reduces (un)boxing. - * It also notifies the remover of which exact element is going to be removed. - * @param c the collection of elements that should be removed - * @param r elements that got removed - * @return true if any element was removed - * @see Collection#removeAll(Collection) - */ - public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r); - - /** - * A Type-Specific retainAll function that reduces (un)boxing. - * @param c the collection of elements that should be kept - * @return true if any element was removed - * @see Collection#retainAll(Collection) - */ - public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c); - - /** - * A Type-Specific retainAll function that reduces (un)boxing. - * It also notifies the remover of which exact element is going to be removed. - * @param c the collection of elements that should be kept - * @param r elements that got removed - * @return true if any element was removed - * @see Collection#retainAll(Collection) - */ - public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r); - - /** - * A Helper function to reduce the usage of Streams and allows to collect all elements - * @param collection that the elements should be inserted to - * @param the collection type - * @return the input with the desired elements - */ - default E pour(E collection) { - collection.addAll(this); - return collection; - } - - /** - * A Function that does a shallow clone of the Collection itself. - * This function is more optimized then a copy constructor since the Collection does not have to be unsorted/resorted. - * It can be compared to Cloneable but with less exception risk - * @return a Shallow Copy of the collection - * @note Wrappers and view collections will not support this feature - */ - public COLLECTION KEY_GENERIC_TYPE copy(); - -#if TYPE_OBJECT - /** - * A Helper function that simplifies the process of creating a new Array. - * @param action the array creation function - * @return an array containing all of the elements in this collection - * @see Collection#toArray(Object[]) - */ - default E[] TO_ARRAY(IntFunction action) { - return TO_ARRAY(action.apply(size())); - } - -#else - /** - * A Type-Specific toArray function that delegates to {@link #TO_ARRAY(KEY_TYPE[])} with a newly created array. - * @return an array containing all of the elements in this collection - * @see Collection#toArray() - */ - public KEY_TYPE[] TO_ARRAY(); - - /** - * A Type-Specific toArray function that reduces (un)boxing. - * @param a array that the elements should be injected to. If null or to small a new array with the right size is created - * @return an array containing all of the elements in this collection - * @see Collection#toArray(Object[]) - */ - public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a); - -#if PRIMITIVES - /** {@inheritDoc} - *

This default implementation delegates to the corresponding type-specific function. - * @deprecated Please use the corresponding type-specific function instead. - */ - @Override - @Deprecated - public default boolean removeIf(Predicate filter) { - Objects.requireNonNull(filter); -#if TYPE_BYTE || TYPE_SHORT || TYPE_CHAR || TYPE_FLOAT - return remIf(v -> filter.test(KEY_TO_OBJ(SanityChecks.SANITY_CAST(v)))); -#else - return remIf(v -> filter.test(KEY_TO_OBJ(v))); -#endif - } - - /** - * A Type-Specific removeIf function to reduce (un)boxing. - *

Removes elements that were selected by the filter - * @see Collection#removeIf(Predicate) - * @param filter Filters the elements that should be removed - * @return true if the collection was modified - * @throws java.lang.NullPointerException if filter is null - */ - public default boolean remIf(JAVA_PREDICATE filter) { - Objects.requireNonNull(filter); - boolean removed = false; - final ITERATOR each = iterator(); - while (each.hasNext()) { - if (filter.test(each.NEXT())) { - each.remove(); - removed = true; - } - } - return removed; - } - -#endif - /** {@inheritDoc} - *

This default implementation delegates to the corresponding type-specific function. - * @deprecated Please use the corresponding type-specific function instead. - */ - @Override - @Deprecated - public default boolean add(CLASS_TYPE o) { return add(OBJ_TO_KEY(o)); } - - /** {@inheritDoc} - *

This default implementation delegates to the corresponding type-specific function. - * @deprecated Please use the corresponding type-specific function instead. - */ - @Override - @Deprecated - public default boolean contains(Object o) { return o != null && contains(CLASS_TO_KEY(o)); } - - /** {@inheritDoc} - *

This default implementation delegates to the corresponding type-specific function. - * @deprecated Please use the corresponding type-specific function instead. - */ - @Override - @Deprecated - public default boolean remove(Object o) { return o != null && REMOVE_KEY(CLASS_TO_KEY(o)); } - -#endif - /** - * Returns a Type-Specific Iterator to reduce (un)boxing - * @return a iterator of the collection - * @see Collection#iterator() - */ - @Override - public ITERATOR KEY_GENERIC_TYPE iterator(); - - /** - * Creates a Wrapped Collection that is Synchronized - * @return a new Collection that is synchronized - * @see COLLECTIONS#synchronize - */ - public default COLLECTION KEY_GENERIC_TYPE synchronize() { return COLLECTIONS.synchronize(this); } - - /** - * Creates a Wrapped Collection that is Synchronized - * @param mutex is the controller of the synchronization block - * @return a new Collection Wrapper that is synchronized - * @see COLLECTIONS#synchronize - */ - public default COLLECTION KEY_GENERIC_TYPE synchronize(Object mutex) { return COLLECTIONS.synchronize(this, mutex); } - - /** - * Creates a Wrapped Collection that is unmodifiable - * @return a new Collection Wrapper that is unmodifiable - * @see COLLECTIONS#unmodifiable - */ - public default COLLECTION KEY_GENERIC_TYPE unmodifiable() { return COLLECTIONS.unmodifiable(this); } - -#if SPLIT_ITERATOR_FEATURE -#if PRIMITIVES - /** - * Returns a Java-Type-Specific Stream to reduce boxing/unboxing. - * @return a Stream of the closest java type - */ - default JAVA_STREAM primitiveStream() { return StreamSupport.NEW_STREAM(SPLIT_ITERATORS.createJavaSplititerator(this, 0), false); } - - /** - * Returns a Java-Type-Specific Parallel Stream to reduce boxing/unboxing. - * @return a Stream of the closest java type - */ - default JAVA_STREAM parallelPrimitiveStream() { return StreamSupport.NEW_STREAM(SPLIT_ITERATORS.createJavaSplititerator(this, 0), true); } - -#endif -#if STREAM_FEATURE - /** - * A Type Specific Type Splititerator to reduce boxing/unboxing - * @return type specific splititerator - */ - @Override - default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createSplititerator(this, 0); } -#endif -#endif +package speiger.src.collections.PACKAGE.collections; + +import java.util.Collection; +#if PRIMITIVES +import java.util.Objects; +import java.util.function.JAVA_PREDICATE; +import java.util.function.Predicate; +#if SPLIT_ITERATOR_FEATURE && STREAM_FEATURE +import java.util.stream.JAVA_STREAM; +import java.util.stream.StreamSupport; +#endif +#endif +#if TYPE_OBJECT +import java.util.function.Consumer; +import java.util.function.IntFunction; +#else +import speiger.src.collections.PACKAGE.functions.CONSUMER; +#endif +#if SPLIT_ITERATOR_FEATURE +import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS; +#endif +import speiger.src.collections.PACKAGE.utils.COLLECTIONS; +import speiger.src.collections.utils.ISizeProvider; +import speiger.src.collections.utils.SanityChecks; + +/** + * A Type-Specific {@link Collection} that reduces (un)boxing + * @Type(T) + */ +public interface COLLECTION KEY_GENERIC_TYPE extends Collection, ITERABLE KEY_GENERIC_TYPE, ISizeProvider +{ +#if !TYPE_OBJECT + /** + * A Type-Specific add function to reduce (un)boxing + * @param o the element that should be added + * @return true if the element was added to the collection + */ + public boolean add(KEY_TYPE o); + +#endif + /** + * A Type-Specific addAll function to reduce (un)boxing + * @param c the collection of elements that should be added + * @return true if elements were added into the collection + */ + public boolean addAll(COLLECTION KEY_GENERIC_TYPE c); + + /** + * A Type-Specific Array based addAll method to reduce the amount of Wrapping + * @param e the elements that should be added + * @return if the collection was modified + */ + public default boolean addAll(KEY_TYPE... e) { return addAll(e, 0, e.length); } + + /** + * A Type-Specific Array based addAll method to reduce the amount of Wrapping + * @param e the elements that should be added + * @param length how many elements of the array should be added + * @return if the collection was modified + */ + public default boolean addAll(KEY_TYPE[] e, int length) { return addAll(e, 0, length); } + + /** + * A Type-Specific Array based addAll method to reduce the amount of Wrapping + * @param e the elements that should be added + * @param offset where to start within the array + * @param length how many elements of the array should be added + * @return if the collection was modified + */ + public default boolean addAll(KEY_TYPE[] e, int offset, int length) { + if(length <= 0) return false; + SanityChecks.checkArrayCapacity(e.length, offset, length); + boolean added = false; + for(int i = 0;i c); + +#if !TYPE_OBJECT + /** + * A Type-Specific remove function that reduces (un)boxing. + * @param o the element that should be removed + * @return true if the element was removed + * @see Collection#remove(Object) + */ + public boolean REMOVE_KEY(KEY_TYPE o); + +#endif + /** + * A Type-Specific removeAll function that reduces (un)boxing. + * @param c the collection of elements that should be removed + * @return true if any element was removed + * @see Collection#removeAll(Collection) + */ + public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c); + + /** + * A Type-Specific removeAll function that reduces (un)boxing. + * It also notifies the remover of which exact element is going to be removed. + * @param c the collection of elements that should be removed + * @param r elements that got removed + * @return true if any element was removed + * @see Collection#removeAll(Collection) + */ + public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r); + + /** + * A Type-Specific retainAll function that reduces (un)boxing. + * @param c the collection of elements that should be kept + * @return true if any element was removed + * @see Collection#retainAll(Collection) + */ + public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c); + + /** + * A Type-Specific retainAll function that reduces (un)boxing. + * It also notifies the remover of which exact element is going to be removed. + * @param c the collection of elements that should be kept + * @param r elements that got removed + * @return true if any element was removed + * @see Collection#retainAll(Collection) + */ + public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r); + + /** + * A Helper function to reduce the usage of Streams and allows to collect all elements + * @param collection that the elements should be inserted to + * @param the collection type + * @return the input with the desired elements + */ + default E pour(E collection) { + collection.addAll(this); + return collection; + } + + /** + * A Function that does a shallow clone of the Collection itself. + * This function is more optimized then a copy constructor since the Collection does not have to be unsorted/resorted. + * It can be compared to Cloneable but with less exception risk + * @return a Shallow Copy of the collection + * @note Wrappers and view collections will not support this feature + */ + public COLLECTION KEY_GENERIC_TYPE copy(); + +#if TYPE_OBJECT + /** + * A Helper function that simplifies the process of creating a new Array. + * @param action the array creation function + * @param the returning arrayType + * @return an array containing all of the elements in this collection + * @see Collection#toArray(Object[]) + */ + default E[] TO_ARRAY(IntFunction action) { + return TO_ARRAY(action.apply(size())); + } + +#else + /** + * A Type-Specific toArray function that delegates to {@link #TO_ARRAY(KEY_TYPE[])} with a newly created array. + * @return an array containing all of the elements in this collection + * @see Collection#toArray() + */ + public KEY_TYPE[] TO_ARRAY(); + + /** + * A Type-Specific toArray function that reduces (un)boxing. + * @param a array that the elements should be injected to. If null or to small a new array with the right size is created + * @return an array containing all of the elements in this collection + * @see Collection#toArray(Object[]) + */ + public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a); + +#if PRIMITIVES + /** {@inheritDoc} + *

This default implementation delegates to the corresponding type-specific function. + * @deprecated Please use the corresponding type-specific function instead. + */ + @Override + @Deprecated + public default boolean removeIf(Predicate filter) { + Objects.requireNonNull(filter); +#if TYPE_BYTE || TYPE_SHORT || TYPE_CHAR || TYPE_FLOAT + return remIf(v -> filter.test(KEY_TO_OBJ(SanityChecks.SANITY_CAST(v)))); +#else + return remIf(v -> filter.test(KEY_TO_OBJ(v))); +#endif + } + + /** + * A Type-Specific removeIf function to reduce (un)boxing. + *

Removes elements that were selected by the filter + * @see Collection#removeIf(Predicate) + * @param filter Filters the elements that should be removed + * @return true if the collection was modified + * @throws java.lang.NullPointerException if filter is null + */ + public default boolean remIf(JAVA_PREDICATE filter) { + Objects.requireNonNull(filter); + boolean removed = false; + final ITERATOR each = iterator(); + while (each.hasNext()) { + if (filter.test(each.NEXT())) { + each.remove(); + removed = true; + } + } + return removed; + } + +#endif + /** {@inheritDoc} + *

This default implementation delegates to the corresponding type-specific function. + * @deprecated Please use the corresponding type-specific function instead. + */ + @Override + @Deprecated + public default boolean add(CLASS_TYPE o) { return add(OBJ_TO_KEY(o)); } + + /** {@inheritDoc} + *

This default implementation delegates to the corresponding type-specific function. + * @deprecated Please use the corresponding type-specific function instead. + */ + @Override + @Deprecated + public default boolean contains(Object o) { return o != null && contains(CLASS_TO_KEY(o)); } + + /** {@inheritDoc} + *

This default implementation delegates to the corresponding type-specific function. + * @deprecated Please use the corresponding type-specific function instead. + */ + @Override + @Deprecated + public default boolean remove(Object o) { return o != null && REMOVE_KEY(CLASS_TO_KEY(o)); } + +#endif + /** + * Returns a Type-Specific Iterator to reduce (un)boxing + * @return a iterator of the collection + * @see Collection#iterator() + */ + @Override + public ITERATOR KEY_GENERIC_TYPE iterator(); + + /** + * Creates a Wrapped Collection that is Synchronized + * @return a new Collection that is synchronized + * @see COLLECTIONS#synchronize + */ + public default COLLECTION KEY_GENERIC_TYPE synchronize() { return COLLECTIONS.synchronize(this); } + + /** + * Creates a Wrapped Collection that is Synchronized + * @param mutex is the controller of the synchronization block + * @return a new Collection Wrapper that is synchronized + * @see COLLECTIONS#synchronize + */ + public default COLLECTION KEY_GENERIC_TYPE synchronize(Object mutex) { return COLLECTIONS.synchronize(this, mutex); } + + /** + * Creates a Wrapped Collection that is unmodifiable + * @return a new Collection Wrapper that is unmodifiable + * @see COLLECTIONS#unmodifiable + */ + public default COLLECTION KEY_GENERIC_TYPE unmodifiable() { return COLLECTIONS.unmodifiable(this); } + +#if SPLIT_ITERATOR_FEATURE +#if PRIMITIVES + /** + * Returns a Java-Type-Specific Stream to reduce boxing/unboxing. + * @return a Stream of the closest java type + */ + default JAVA_STREAM primitiveStream() { return StreamSupport.NEW_STREAM(SPLIT_ITERATORS.createJavaSplititerator(this, 0), false); } + + /** + * Returns a Java-Type-Specific Parallel Stream to reduce boxing/unboxing. + * @return a Stream of the closest java type + */ + default JAVA_STREAM parallelPrimitiveStream() { return StreamSupport.NEW_STREAM(SPLIT_ITERATORS.createJavaSplititerator(this, 0), true); } + +#endif +#if STREAM_FEATURE + /** + * A Type Specific Type Splititerator to reduce boxing/unboxing + * @return type specific splititerator + */ + @Override + default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createSplititerator(this, 0); } +#endif +#endif } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/collections/templates/collections/Iterable.template b/src/builder/resources/speiger/assets/collections/templates/collections/Iterable.template index e2e0f79..e5ccd70 100644 --- a/src/builder/resources/speiger/assets/collections/templates/collections/Iterable.template +++ b/src/builder/resources/speiger/assets/collections/templates/collections/Iterable.template @@ -1,457 +1,458 @@ -package speiger.src.collections.PACKAGE.collections; - -import java.util.Objects; -import java.util.function.Consumer; -#if JDK_FUNCTION -import java.util.function.PREDICATE; -#endif - -#if !TYPE_OBJECT - -import speiger.src.collections.PACKAGE.functions.CONSUMER; -import speiger.src.collections.PACKAGE.functions.COMPARATOR; -import speiger.src.collections.objects.collections.ObjectIterable; -#else -import java.util.function.BiFunction; -import java.util.function.IntFunction; -import java.util.Comparator; - -#endif -import speiger.src.collections.PACKAGE.functions.function.TO_OBJECT_FUNCTION; -import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER; -import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; -#if !JDK_FUNCTION -import speiger.src.collections.PACKAGE.functions.function.PREDICATE; -#endif -import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; -#if ARRAY_LIST_FEATURE || LINKED_LIST_FEATURE -import speiger.src.collections.PACKAGE.lists.LIST; -#if ARRAY_LIST_FEATURE -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -#else -import speiger.src.collections.PACKAGE.lists.LINKED_LIST; -#endif -#endif -#if SET_MODULE && !TYPE_BOOLEAN -#if LINKED_SET_FEATURE || LINKED_CUSTOM_SET_FEATURE || SET_FEATURE || CUSTOM_SET_FEATURE || RB_TREE_SET_FEATURE || AVL_TREE_SET_FEATURE || ARRAY_SET_FEATURE -import speiger.src.collections.PACKAGE.sets.SET; -#if LINKED_SET_FEATURE -import speiger.src.collections.PACKAGE.sets.LINKED_HASH_SET; -#else if LINKED_CUSTOM_SET_FEATURE -import speiger.src.collections.PACKAGE.sets.LINKED_CUSTOM_HASH_SET; -#else if SET_FEATURE -import speiger.src.collections.PACKAGE.sets.HASH_SET; -#else if CUSTOM_SET_FEATURE -import speiger.src.collections.PACKAGE.sets.CUSTOM_HASH_SET; -#else if RB_TREE_SET_FEATURE -import speiger.src.collections.PACKAGE.sets.RB_TREE_SET; -#else if AVL_TREE_SET_FEATURE -import speiger.src.collections.PACKAGE.sets.AVL_TREE_SET; -#else if ARRAY_SET_FEATURE -import speiger.src.collections.PACKAGE.sets.ARRAY_SET; -#endif -#endif -#endif -import speiger.src.collections.PACKAGE.utils.ARRAYS; -#if ASYNC_MODULE -import speiger.src.collections.PACKAGE.utils.ASYNC_BUILDER; -#endif -#if SPLIT_ITERATOR_FEATURE -import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS; -#endif -import speiger.src.collections.PACKAGE.utils.ITERABLES; -import speiger.src.collections.PACKAGE.utils.ITERATORS; -#if !LINKED_HASH_SET_FEATURE && LINKED_CUSTOM_HASH_SET_FEATURE -import speiger.src.collections.PACKAGE.utils.STRATEGY; -#endif -import speiger.src.collections.utils.ISizeProvider; - -/** - * A Type-Specific {@link Iterable} that reduces (un)boxing - * @Type(T) - */ -public interface ITERABLE KEY_GENERIC_TYPE extends Iterable -{ - /** - * Returns an iterator over elements of type {@code T}. - * - * @return an Iterator. - */ - @Override - ITERATOR KEY_GENERIC_TYPE iterator(); - -#if !TYPE_OBJECT - /** - * A Type Specific foreach function that reduces (un)boxing - * - * @implSpec - *

The default implementation behaves as if: - *

{@code
-	 *	iterator().forEachRemaining(action);
-	 * }
- * - * @param action The action to be performed for each element - * @throws NullPointerException if the specified action is null - * @see Iterable#forEach(Consumer) - */ - default void forEach(CONSUMER action) { - Objects.requireNonNull(action); - iterator().forEachRemaining(action); - } - - /** {@inheritDoc} - *

This default implementation delegates to the corresponding type-specific function. - * @deprecated Please use the corresponding type-specific function instead. - */ - @Deprecated - @Override - default void forEach(Consumer action) { - Objects.requireNonNull(action); - iterator().forEachRemaining(action); - } - -#endif - /** - * A Indexed forEach implementation that allows you to keep track of how many elements were already iterated over. - * @param action The action to be performed for each element - * @throws java.lang.NullPointerException if the specified action is null - */ - public default void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) { - Objects.requireNonNull(action); - int index = 0; - for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();action.accept(index++, iter.NEXT())); - } - - /** - * Helper function to reduce Lambda usage and allow for more method references, since these are faster/cleaner. - * @param input the object that should be included - * @param action The action to be performed for each element - * @param the generic type of the Object - * @throws java.lang.NullPointerException if the specified action is null - */ - default void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { - Objects.requireNonNull(action); - iterator().forEachRemaining(input, action); - } - -#if SPLIT_ITERATOR_FEATURE - /** - * A Type Specific Type Splititerator to reduce boxing/unboxing - * @return type specific splititerator - */ - @Override - default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createUnknownSplititerator(iterator(), 0); } - -#endif -#if ASYNC_MODULE - /** - * Creates a Async Builder for moving work of the thread. - * It is not designed to split the work to multithreaded work, so using this keep it singlethreaded, but it allows to be moved to another thread. - * @see ASYNC_BUILDER - * @return a AsyncBuilder - */ - default ASYNC_BUILDER KEY_GENERIC_TYPE asAsync() { - return new ASYNC_BUILDERBRACES(this); - } - -#endif - /** - * A Helper function to reduce the usage of Streams and allows to convert a Iterable to something else. - * @param mapper the mapping function - * @param The return type. - * @return a new Iterable that returns the desired result - */ - default ObjectIterable map(TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { - return ITERABLES.map(this, mapper); - } - - /** - * A Helper function to reduce the usage of Streams and allows to convert a Iterable to something else. - * @param mapper the flatMapping function - * @param The return type supplier. - * @param The return type. - * @return a new Iterable that returns the desired result - * @note does not support TO_ARRAY optimizations. - */ - default > ObjectIterable flatMap(TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { - return ITERABLES.flatMap(this, mapper); - } - - /** - * A Helper function to reduce the usage of Streams and allows to convert a Iterable to something else. - * @param mapper the flatMapping function - * @param The return type. - * @return a new Iterable that returns the desired result - * @note does not support TO_ARRAY optimizations. - */ - default ObjectIterable arrayflatMap(TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { - return ITERABLES.arrayFlatMap(this, mapper); - } - - /** - * A Helper function to reduce the usage of Streams and allows to filter out unwanted elements - * @param filter the elements that should be kept. - * @return a Iterable that filtered out all unwanted elements - * @note does not support TO_ARRAY optimizations. - */ - default ITERABLE KEY_GENERIC_TYPE filter(PREDICATE KEY_GENERIC_TYPE filter) { - return ITERABLES.filter(this, filter); - } - - /** - * A Helper function to reduce the usage of Streams and allows to filter out duplicated elements - * @return a Iterable that filtered out all duplicated elements - * @note does not support TO_ARRAY optimizations. - */ - default ITERABLE KEY_GENERIC_TYPE distinct() { - return ITERABLES.distinct(this); - } - - /** - * A Helper function to reduce the usage of Streams and allows to repeat elements a desired amount of times - * @param repeats how many times the elements should be repeated - * @return a Iterable that is repeating multiple times - */ - default ITERABLE KEY_GENERIC_TYPE repeat(int repeats) { - return ITERABLES.repeat(this, repeats); - } - - /** - * A Helper function to reduce the usage of Streams and allows to limit the amount of elements - * @param limit the amount of elements it should be limited to - * @return a Iterable that is limited in length - */ - default ITERABLE KEY_GENERIC_TYPE limit(long limit) { - return ITERABLES.limit(this, limit); - } - - /** - * A Helper function to reduce the usage of Streams and allows to sort the elements - * @param sorter that sorts the elements. - * @return a Iterable that is sorted - */ - default ITERABLE KEY_GENERIC_TYPE sorted(COMPARATOR KEY_GENERIC_TYPE sorter) { - return ITERABLES.sorted(this, sorter); - } - - /** - * A Helper function to reduce the usage of Streams and allows to preview elements before they are iterated through - * @param action the action that should be applied - * @return a Peeked Iterable - */ - default ITERABLE KEY_GENERIC_TYPE peek(CONSUMER KEY_GENERIC_TYPE action) { - return ITERABLES.peek(this, action); - } - - /** - * A Helper function to reduce the usage of Streams and allows to collect all elements - * @param collection that the elements should be inserted to - * @param the collection type - * @return the input with the desired elements - */ - default E pour(E collection) { - ITERATORS.pour(iterator(), collection); - return collection; - } - -#if ARRAY_LIST_FEATURE || LINKED_LIST_FEATURE - /** - * A Helper function that reduces the usage of streams and allows to collect all elements as a ArrayList - * @return a new ArrayList of all elements - */ - default LIST KEY_GENERIC_TYPE pourAsList() { -#if ARRAY_LIST_FEATURE - return pour(new ARRAY_LISTBRACES()); -#else - return pour(new LINKED_LISTBRACES()); -#endif - } - -#endif -#if !TYPE_BOOLEAN && SET_MODULE -#if LINKED_SET_FEATURE || LINKED_CUSTOM_SET_FEATURE || SET_FEATURE || CUSTOM_SET_FEATURE || RB_TREE_SET_FEATURE || AVL_TREE_SET_FEATURE || ARRAY_SET_FEATURE - /** - * A Helper function that reduces the usage of streams and allows to collect all elements as a LinkedHashSet - * @return a new LinkedHashSet of all elements - */ - default SET KEY_GENERIC_TYPE pourAsSet() { -#if LINKED_SET_FEATURE - return pour(new LINKED_HASH_SETBRACES()); -#else if LINKED_CUSTOM_SET_FEATURE - return pour(new LINKED_CUSTOM_HASH_SETBRACES(STRATEGY.normalStrategy())); -#else if SET_FEATURE - return pour(new HASH_SETBRACES()); -#else if CUSTOM_SET_FEATURE - return pour(new CUSTOM_HASH_SETBRACES(STRATEGY.normalStrategy())); -#else if RB_TREE_SET_FEATURE - return pour(new RB_Tree_SETBRACES()); -#else if AVL_TREE_SET_FEATURE - return pour(new AVL_Tree_SETBRACES()); -#else if ARRAY_SET_FEATURE - return pour(new ARRAY_SETBRACES()); -#endif - } - -#endif -#endif -#if TYPE_OBJECT - /** - * A Helper function that reduces the usage of streams and allows to collect all elements as a Array - * @param action is the creator function of said Array to ensure type is kept. - * @return a new Array of all elements - */ - default E[] TO_ARRAY(IntFunction action) { - ISizeProvider prov = ISizeProvider.of(this); - if(prov != null) { - int size = prov.size(); - if(size >= 0) { - E[] array = action.apply(size); - ITERATORS.unwrap(array, iterator()); - return array; - } - } - return ARRAYS.pour(iterator(), action); - } -#else - /** - * A Helper function that reduces the usage of streams and allows to collect all elements as a Array - * @return a new Array of all elements - */ - default KEY_TYPE[] TO_ARRAY() { - ISizeProvider prov = ISizeProvider.of(this); - if(prov != null) { - int size = prov.size(); - if(size >= 0) { - KEY_TYPE[] array = NEW_KEY_ARRAY(size); - ITERATORS.unwrap(array, iterator()); - return array; - } - } - return ARRAYS.pour(iterator()); - } - -#endif - /** - * Helper function to reduce stream usage that allows to filter for any matches. - * @param filter that should be applied - * @return true if any matches were found - */ - default boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { - if(filter.test(iter.NEXT())) return true; - } - return false; - } - - /** - * Helper function to reduce stream usage that allows to filter for no matches. - * @param filter that should be applied - * @return true if no matches were found - */ - default boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { - if(filter.test(iter.NEXT())) return false; - } - return true; - } - - /** - * Helper function to reduce stream usage that allows to filter for all matches. - * @param filter that should be applied - * @return true if all matches. - */ - default boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { - if(!filter.test(iter.NEXT())) return false; - } - return true; - } - - /** - * Helper function to reduce stream usage that allows to filter for the first match. - * @param filter that should be applied - * @return the found value or the null equivalent variant. - */ - default KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { - KEY_TYPE entry = iter.NEXT(); - if(filter.test(entry)) return entry; - } - return EMPTY_VALUE; - } - -#if !TYPE_OBJECT - /** - * Performs a reduction on the - * elements of this Iterable - * @param operator the operation that should be applied - * @param identity the start value - * @return the reduction result, returns identity if nothing was found - */ - default KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - KEY_TYPE state = identity; - for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { - state = operator.APPLY_VALUE(state, iter.NEXT()); - } - return state; - } - -#else - /** - * Performs a reduction on the - * elements of this Iterable - * @param operator the operation that should be applied - * @param identity the start value - * @Type(E) - * @return the reduction result, returns identity if nothing was found - */ - default KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) { - Objects.requireNonNull(operator); - KEY_SPECIAL_TYPE state = identity; - for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { - state = operator.APPLY_VALUE(state, iter.NEXT()); - } - return state; - } - -#endif - /** - * Performs a reduction on the - * elements of this Iterable - * @param operator the operation that should be applied - * @return the reduction result, returns null value if nothing was found - */ - default KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - KEY_TYPE state = EMPTY_VALUE; - boolean empty = true; - for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { - if(empty) { - empty = false; - state = iter.NEXT(); - continue; - } - state = operator.APPLY_VALUE(state, iter.NEXT()); - } - return state; - } - - /** - * Helper function to reduce stream usage that allows to count the valid elements. - * @param filter that should be applied - * @return the amount of Valid Elements - */ - default int count(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - int result = 0; - for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { - if(filter.test(iter.NEXT())) result++; - } - return result; - } +package speiger.src.collections.PACKAGE.collections; + +import java.util.Objects; +import java.util.function.Consumer; +#if JDK_FUNCTION +import java.util.function.PREDICATE; +#endif + +#if !TYPE_OBJECT + +import speiger.src.collections.PACKAGE.functions.CONSUMER; +import speiger.src.collections.PACKAGE.functions.COMPARATOR; +import speiger.src.collections.objects.collections.ObjectIterable; +#else +import java.util.function.BiFunction; +import java.util.function.IntFunction; +import java.util.Comparator; + +#endif +import speiger.src.collections.PACKAGE.functions.function.TO_OBJECT_FUNCTION; +import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER; +import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; +#if !JDK_FUNCTION +import speiger.src.collections.PACKAGE.functions.function.PREDICATE; +#endif +import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; +#if ARRAY_LIST_FEATURE || LINKED_LIST_FEATURE +import speiger.src.collections.PACKAGE.lists.LIST; +#if ARRAY_LIST_FEATURE +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +#else +import speiger.src.collections.PACKAGE.lists.LINKED_LIST; +#endif +#endif +#if SET_MODULE && !TYPE_BOOLEAN +#if LINKED_SET_FEATURE || LINKED_CUSTOM_SET_FEATURE || SET_FEATURE || CUSTOM_SET_FEATURE || RB_TREE_SET_FEATURE || AVL_TREE_SET_FEATURE || ARRAY_SET_FEATURE +import speiger.src.collections.PACKAGE.sets.SET; +#if LINKED_SET_FEATURE +import speiger.src.collections.PACKAGE.sets.LINKED_HASH_SET; +#else if LINKED_CUSTOM_SET_FEATURE +import speiger.src.collections.PACKAGE.sets.LINKED_CUSTOM_HASH_SET; +#else if SET_FEATURE +import speiger.src.collections.PACKAGE.sets.HASH_SET; +#else if CUSTOM_SET_FEATURE +import speiger.src.collections.PACKAGE.sets.CUSTOM_HASH_SET; +#else if RB_TREE_SET_FEATURE +import speiger.src.collections.PACKAGE.sets.RB_TREE_SET; +#else if AVL_TREE_SET_FEATURE +import speiger.src.collections.PACKAGE.sets.AVL_TREE_SET; +#else if ARRAY_SET_FEATURE +import speiger.src.collections.PACKAGE.sets.ARRAY_SET; +#endif +#endif +#endif +import speiger.src.collections.PACKAGE.utils.ARRAYS; +#if ASYNC_MODULE +import speiger.src.collections.PACKAGE.utils.ASYNC_BUILDER; +#endif +#if SPLIT_ITERATOR_FEATURE +import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS; +#endif +import speiger.src.collections.PACKAGE.utils.ITERABLES; +import speiger.src.collections.PACKAGE.utils.ITERATORS; +#if !LINKED_HASH_SET_FEATURE && LINKED_CUSTOM_HASH_SET_FEATURE +import speiger.src.collections.PACKAGE.utils.STRATEGY; +#endif +import speiger.src.collections.utils.ISizeProvider; + +/** + * A Type-Specific {@link Iterable} that reduces (un)boxing + * @Type(T) + */ +public interface ITERABLE KEY_GENERIC_TYPE extends Iterable +{ + /** + * Returns an iterator over elements of type {@code T}. + * + * @return an Iterator. + */ + @Override + ITERATOR KEY_GENERIC_TYPE iterator(); + +#if !TYPE_OBJECT + /** + * A Type Specific foreach function that reduces (un)boxing + * + * @implSpec + *

The default implementation behaves as if: + *

{@code
+	 *	iterator().forEachRemaining(action);
+	 * }
+ * + * @param action The action to be performed for each element + * @throws NullPointerException if the specified action is null + * @see Iterable#forEach(Consumer) + */ + default void forEach(CONSUMER action) { + Objects.requireNonNull(action); + iterator().forEachRemaining(action); + } + + /** {@inheritDoc} + *

This default implementation delegates to the corresponding type-specific function. + * @deprecated Please use the corresponding type-specific function instead. + */ + @Deprecated + @Override + default void forEach(Consumer action) { + Objects.requireNonNull(action); + iterator().forEachRemaining(action); + } + +#endif + /** + * A Indexed forEach implementation that allows you to keep track of how many elements were already iterated over. + * @param action The action to be performed for each element + * @throws java.lang.NullPointerException if the specified action is null + */ + public default void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) { + Objects.requireNonNull(action); + int index = 0; + for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();action.accept(index++, iter.NEXT())); + } + + /** + * Helper function to reduce Lambda usage and allow for more method references, since these are faster/cleaner. + * @param input the object that should be included + * @param action The action to be performed for each element + * @param the generic type of the Object + * @throws java.lang.NullPointerException if the specified action is null + */ + default void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { + Objects.requireNonNull(action); + iterator().forEachRemaining(input, action); + } + +#if SPLIT_ITERATOR_FEATURE + /** + * A Type Specific Type Splititerator to reduce boxing/unboxing + * @return type specific splititerator + */ + @Override + default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createUnknownSplititerator(iterator(), 0); } + +#endif +#if ASYNC_MODULE + /** + * Creates a Async Builder for moving work of the thread. + * It is not designed to split the work to multithreaded work, so using this keep it singlethreaded, but it allows to be moved to another thread. + * @see ASYNC_BUILDER + * @return a AsyncBuilder + */ + default ASYNC_BUILDER KEY_GENERIC_TYPE asAsync() { + return new ASYNC_BUILDERBRACES(this); + } + +#endif + /** + * A Helper function to reduce the usage of Streams and allows to convert a Iterable to something else. + * @param mapper the mapping function + * @param The return type. + * @return a new Iterable that returns the desired result + */ + default ObjectIterable map(TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { + return ITERABLES.map(this, mapper); + } + + /** + * A Helper function to reduce the usage of Streams and allows to convert a Iterable to something else. + * @param mapper the flatMapping function + * @param The return type supplier. + * @param The return type. + * @return a new Iterable that returns the desired result + * @note does not support TO_ARRAY optimizations. + */ + default > ObjectIterable flatMap(TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { + return ITERABLES.flatMap(this, mapper); + } + + /** + * A Helper function to reduce the usage of Streams and allows to convert a Iterable to something else. + * @param mapper the flatMapping function + * @param The return type. + * @return a new Iterable that returns the desired result + * @note does not support TO_ARRAY optimizations. + */ + default ObjectIterable arrayflatMap(TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { + return ITERABLES.arrayFlatMap(this, mapper); + } + + /** + * A Helper function to reduce the usage of Streams and allows to filter out unwanted elements + * @param filter the elements that should be kept. + * @return a Iterable that filtered out all unwanted elements + * @note does not support TO_ARRAY optimizations. + */ + default ITERABLE KEY_GENERIC_TYPE filter(PREDICATE KEY_GENERIC_TYPE filter) { + return ITERABLES.filter(this, filter); + } + + /** + * A Helper function to reduce the usage of Streams and allows to filter out duplicated elements + * @return a Iterable that filtered out all duplicated elements + * @note does not support TO_ARRAY optimizations. + */ + default ITERABLE KEY_GENERIC_TYPE distinct() { + return ITERABLES.distinct(this); + } + + /** + * A Helper function to reduce the usage of Streams and allows to repeat elements a desired amount of times + * @param repeats how many times the elements should be repeated + * @return a Iterable that is repeating multiple times + */ + default ITERABLE KEY_GENERIC_TYPE repeat(int repeats) { + return ITERABLES.repeat(this, repeats); + } + + /** + * A Helper function to reduce the usage of Streams and allows to limit the amount of elements + * @param limit the amount of elements it should be limited to + * @return a Iterable that is limited in length + */ + default ITERABLE KEY_GENERIC_TYPE limit(long limit) { + return ITERABLES.limit(this, limit); + } + + /** + * A Helper function to reduce the usage of Streams and allows to sort the elements + * @param sorter that sorts the elements. + * @return a Iterable that is sorted + */ + default ITERABLE KEY_GENERIC_TYPE sorted(COMPARATOR KEY_GENERIC_TYPE sorter) { + return ITERABLES.sorted(this, sorter); + } + + /** + * A Helper function to reduce the usage of Streams and allows to preview elements before they are iterated through + * @param action the action that should be applied + * @return a Peeked Iterable + */ + default ITERABLE KEY_GENERIC_TYPE peek(CONSUMER KEY_GENERIC_TYPE action) { + return ITERABLES.peek(this, action); + } + + /** + * A Helper function to reduce the usage of Streams and allows to collect all elements + * @param collection that the elements should be inserted to + * @param the collection type + * @return the input with the desired elements + */ + default E pour(E collection) { + ITERATORS.pour(iterator(), collection); + return collection; + } + +#if ARRAY_LIST_FEATURE || LINKED_LIST_FEATURE + /** + * A Helper function that reduces the usage of streams and allows to collect all elements as a ArrayList + * @return a new ArrayList of all elements + */ + default LIST KEY_GENERIC_TYPE pourAsList() { +#if ARRAY_LIST_FEATURE + return pour(new ARRAY_LISTBRACES()); +#else + return pour(new LINKED_LISTBRACES()); +#endif + } + +#endif +#if !TYPE_BOOLEAN && SET_MODULE +#if LINKED_SET_FEATURE || LINKED_CUSTOM_SET_FEATURE || SET_FEATURE || CUSTOM_SET_FEATURE || RB_TREE_SET_FEATURE || AVL_TREE_SET_FEATURE || ARRAY_SET_FEATURE + /** + * A Helper function that reduces the usage of streams and allows to collect all elements as a LinkedHashSet + * @return a new LinkedHashSet of all elements + */ + default SET KEY_GENERIC_TYPE pourAsSet() { +#if LINKED_SET_FEATURE + return pour(new LINKED_HASH_SETBRACES()); +#else if LINKED_CUSTOM_SET_FEATURE + return pour(new LINKED_CUSTOM_HASH_SETBRACES(STRATEGY.normalStrategy())); +#else if SET_FEATURE + return pour(new HASH_SETBRACES()); +#else if CUSTOM_SET_FEATURE + return pour(new CUSTOM_HASH_SETBRACES(STRATEGY.normalStrategy())); +#else if RB_TREE_SET_FEATURE + return pour(new RB_Tree_SETBRACES()); +#else if AVL_TREE_SET_FEATURE + return pour(new AVL_Tree_SETBRACES()); +#else if ARRAY_SET_FEATURE + return pour(new ARRAY_SETBRACES()); +#endif + } + +#endif +#endif +#if TYPE_OBJECT + /** + * A Helper function that reduces the usage of streams and allows to collect all elements as a Array + * @param action is the creator function of said Array to ensure type is kept. + * @param the returning arrayType + * @return a new Array of all elements + */ + default E[] TO_ARRAY(IntFunction action) { + ISizeProvider prov = ISizeProvider.of(this); + if(prov != null) { + int size = prov.size(); + if(size >= 0) { + E[] array = action.apply(size); + ITERATORS.unwrap(array, iterator()); + return array; + } + } + return ARRAYS.pour(iterator(), action); + } +#else + /** + * A Helper function that reduces the usage of streams and allows to collect all elements as a Array + * @return a new Array of all elements + */ + default KEY_TYPE[] TO_ARRAY() { + ISizeProvider prov = ISizeProvider.of(this); + if(prov != null) { + int size = prov.size(); + if(size >= 0) { + KEY_TYPE[] array = NEW_KEY_ARRAY(size); + ITERATORS.unwrap(array, iterator()); + return array; + } + } + return ARRAYS.pour(iterator()); + } + +#endif + /** + * Helper function to reduce stream usage that allows to filter for any matches. + * @param filter that should be applied + * @return true if any matches were found + */ + default boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { + if(filter.test(iter.NEXT())) return true; + } + return false; + } + + /** + * Helper function to reduce stream usage that allows to filter for no matches. + * @param filter that should be applied + * @return true if no matches were found + */ + default boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { + if(filter.test(iter.NEXT())) return false; + } + return true; + } + + /** + * Helper function to reduce stream usage that allows to filter for all matches. + * @param filter that should be applied + * @return true if all matches. + */ + default boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { + if(!filter.test(iter.NEXT())) return false; + } + return true; + } + + /** + * Helper function to reduce stream usage that allows to filter for the first match. + * @param filter that should be applied + * @return the found value or the null equivalent variant. + */ + default KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { + KEY_TYPE entry = iter.NEXT(); + if(filter.test(entry)) return entry; + } + return EMPTY_VALUE; + } + +#if !TYPE_OBJECT + /** + * Performs a reduction on the + * elements of this Iterable + * @param operator the operation that should be applied + * @param identity the start value + * @return the reduction result, returns identity if nothing was found + */ + default KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + KEY_TYPE state = identity; + for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { + state = operator.APPLY_VALUE(state, iter.NEXT()); + } + return state; + } + +#else + /** + * Performs a reduction on the + * elements of this Iterable + * @param operator the operation that should be applied + * @param identity the start value + * @Type(E) + * @return the reduction result, returns identity if nothing was found + */ + default KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) { + Objects.requireNonNull(operator); + KEY_SPECIAL_TYPE state = identity; + for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { + state = operator.APPLY_VALUE(state, iter.NEXT()); + } + return state; + } + +#endif + /** + * Performs a reduction on the + * elements of this Iterable + * @param operator the operation that should be applied + * @return the reduction result, returns null value if nothing was found + */ + default KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + KEY_TYPE state = EMPTY_VALUE; + boolean empty = true; + for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { + if(empty) { + empty = false; + state = iter.NEXT(); + continue; + } + state = operator.APPLY_VALUE(state, iter.NEXT()); + } + return state; + } + + /** + * Helper function to reduce stream usage that allows to count the valid elements. + * @param filter that should be applied + * @return the amount of Valid Elements + */ + default int count(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + int result = 0; + for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { + if(filter.test(iter.NEXT())) result++; + } + return result; + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/collections/templates/functions/Comparator.template b/src/builder/resources/speiger/assets/collections/templates/functions/Comparator.template index 870ec5f..d0e1ca6 100644 --- a/src/builder/resources/speiger/assets/collections/templates/functions/Comparator.template +++ b/src/builder/resources/speiger/assets/collections/templates/functions/Comparator.template @@ -1,70 +1,70 @@ -package speiger.src.collections.PACKAGE.functions; - -import java.util.Comparator; -import java.util.Objects; - -/** - * Type-Specific Class for Comparator to reduce (un)boxing - */ -public interface COMPARATOR extends Comparator -{ - /** - * Type-Specific compare function to reduce (un)boxing - * @param o1 the first object to be compared. - * @param o2 the second object to be compared. - * @return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. - * @see Comparator#compare(Object, Object) - */ - int compare(KEY_TYPE o1, KEY_TYPE o2); - - /** {@inheritDoc} - *

This default implementation delegates to the corresponding type-specific function. - * @deprecated Please use the corresponding type-specific function instead. - */ - @Override - @Deprecated - default int compare(CLASS_TYPE o1, CLASS_TYPE o2) { - return compare(OBJ_TO_KEY(o1), OBJ_TO_KEY(o2)); - } - - /** - * A Wrapper function to convert a Non-Type-Specific Comparator to a Type-Specific-Comparator - * @param c comparator to convert - * @return the wrapper of the comparator - * @throws NullPointerException if the comparator is null - */ - public static COMPARATOR of(Comparator c) { - Objects.requireNonNull(c); - return (K, V) -> c.compare(KEY_TO_OBJ(K), KEY_TO_OBJ(V)); - } - - @Override - public default COMPARATOR reversed() { - return new Reversed(this); - } - - /** - * A Type Specific Reversed Comparator to reduce boxing/unboxing - */ - static class Reversed implements COMPARATOR - { - COMPARATOR original; - - /** - * default constructor - * @param original that is going to be reversed - */ - public Reversed(COMPARATOR original) { - this.original = original; - } - - public int compare(KEY_TYPE o1, KEY_TYPE o2) { - return original.compare(o2, o1); - } - - @Override - public COMPARATOR reversed() { - return original; - } - } +package speiger.src.collections.PACKAGE.functions; + +import java.util.Comparator; +import java.util.Objects; + +/** + * Type-Specific Class for Comparator to reduce (un)boxing + */ +public interface COMPARATOR extends Comparator +{ + /** + * Type-Specific compare function to reduce (un)boxing + * @param o1 the first object to be compared. + * @param o2 the second object to be compared. + * @return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. + * @see Comparator#compare(Object, Object) + */ + int compare(KEY_TYPE o1, KEY_TYPE o2); + + /** {@inheritDoc} + *

This default implementation delegates to the corresponding type-specific function. + * @deprecated Please use the corresponding type-specific function instead. + */ + @Override + @Deprecated + default int compare(CLASS_TYPE o1, CLASS_TYPE o2) { + return compare(OBJ_TO_KEY(o1), OBJ_TO_KEY(o2)); + } + + /** + * A Wrapper function to convert a Non-Type-Specific Comparator to a Type-Specific-Comparator + * @param c comparator to convert + * @return the wrapper of the comparator + * @throws NullPointerException if the comparator is null + */ + public static COMPARATOR of(Comparator c) { + Objects.requireNonNull(c); + return (K, V) -> c.compare(KEY_TO_OBJ(K), KEY_TO_OBJ(V)); + } + + @Override + public default COMPARATOR reversed() { + return new Reversed(this); + } + + /** + * A Type Specific Reversed Comparator to reduce boxing/unboxing + */ + static class Reversed implements COMPARATOR + { + COMPARATOR original; + + /** + * default constructor + * @param original that is going to be reversed + */ + public Reversed(COMPARATOR original) { + this.original = original; + } + + public int compare(KEY_TYPE o1, KEY_TYPE o2) { + return original.compare(o2, o1); + } + + @Override + public COMPARATOR reversed() { + return original; + } + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/collections/templates/functions/Supplier.template b/src/builder/resources/speiger/assets/collections/templates/functions/Supplier.template index 22158d6..3f80da7 100644 --- a/src/builder/resources/speiger/assets/collections/templates/functions/Supplier.template +++ b/src/builder/resources/speiger/assets/collections/templates/functions/Supplier.template @@ -1,19 +1,19 @@ -package speiger.src.collections.PACKAGE.functions; - -/** - * Type-Specific Supplier interface that reduces (un)boxing and allows to merge other consumer types into this interface - * @Type(T) - */ -#if TYPE_OBJECT -public interface SUPPLIER KEY_GENERIC_TYPE extends java.util.function.Supplier -#else if JDK_TYPE && !TYPE_BOOLEAN -public interface SUPPLIER KEY_GENERIC_TYPE extends JAVA_SUPPLIER -#else -public interface SUPPLIER KEY_GENERIC_TYPE -#endif -{ - /** - * @return the supplied value - */ - public KEY_TYPE SUPPLY_GET(); +package speiger.src.collections.PACKAGE.functions; + +/** + * Type-Specific Supplier interface that reduces (un)boxing and allows to merge other consumer types into this interface + * @Type(T) + */ +#if TYPE_OBJECT +public interface SUPPLIER KEY_GENERIC_TYPE extends java.util.function.Supplier +#else if JDK_TYPE && !TYPE_BOOLEAN +public interface SUPPLIER KEY_GENERIC_TYPE extends JAVA_SUPPLIER +#else +public interface SUPPLIER KEY_GENERIC_TYPE +#endif +{ + /** + * @return the supplied value + */ + public KEY_TYPE SUPPLY_GET(); } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/collections/templates/functions/Task.template b/src/builder/resources/speiger/assets/collections/templates/functions/Task.template index 2d90612..cbb19de 100644 --- a/src/builder/resources/speiger/assets/collections/templates/functions/Task.template +++ b/src/builder/resources/speiger/assets/collections/templates/functions/Task.template @@ -1,92 +1,92 @@ -package speiger.src.collections.PACKAGE.functions; - -import java.util.concurrent.RunnableFuture; -#if !TYPE_OBJECT -import java.util.concurrent.CancellationException; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -#endif - -/** - * - * A Type Specific Task interface that allows you to keep track of the task that is currently running.
- * It extends Runnable future and supports said functions but also provides quality of life functions like:
- * - * - isSuccesfull: which allows to detect if the task was completed properly and not interrupted or crashed. - * - pause/resume: which allows to pause/resume the task at any moment, making it easier to create thread-safe actions. - * @Type(T) - */ -public interface TASK KEY_GENERIC_TYPE extends RunnableFuture { - /** - * Helper function to detect if the task is currently paused. - * @return true if paused - */ - public boolean isPaused(); - - /** - * Pauses the task, which lets the thread finish without completing the task. - * Tasks are written in the way where they can pause without any issues. - * This won't be instant, as this function is applied asynchronous and doesn't check if the thread paused. - * So make sure it had the time to pause. - */ - public void pause(); - - /** - * Pauses the task, which lets the thread finish without completing the task. - * Tasks are written in the way where they can pause without any issues. - * This won't be instant, as this function is applied asynchronous. - * It will await the pausing of the task. - */ - public void awaitPausing(); - - /** - * Continues the task if it wasn't already completed. - * This is done by resubmitting the task to the executor provided. - */ - public void resume(); - - /** - * Quality of life function that allows to detect if no cancellation/exception was applied to this task and it completed on its own. - * @return true if it was properly completed - */ - public boolean isSuccessful(); - -#if !TYPE_OBJECT - /** - * A Type Specific get method that allows to reduce (un)boxing of primtives. - * - * Waits if necessary for the computation to complete, and then - * retrieves its result. - * - * @return the computed result as primitive - * @throws CancellationException if the computation was cancelled - * @throws ExecutionException if the computation threw an exception - * @throws InterruptedException if the current thread was interrupted - * while waiting - */ - public KEY_TYPE GET_KEY() throws InterruptedException, ExecutionException; - - /** - * Waits if necessary for at most the given time for the computation - * to complete, and then retrieves its result, if available. - * - * @param timeout the maximum time to wait - * @param unit the time unit of the timeout argument - * @return the computed result as primitive - * @throws CancellationException if the computation was cancelled - * @throws ExecutionException if the computation threw an exception - * @throws InterruptedException if the current thread was interrupted while waiting - * @throws TimeoutException if the wait timed out - */ - public KEY_TYPE GET_KEY(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; - - @Override - @Deprecated - public default CLASS_TYPE get() throws InterruptedException, ExecutionException { return KEY_TO_OBJ(GET_KEY()); } - - @Override - @Deprecated - public default CLASS_TYPE get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return KEY_TO_OBJ(GET_KEY(timeout, unit)); } -#endif +package speiger.src.collections.PACKAGE.functions; + +import java.util.concurrent.RunnableFuture; +#if !TYPE_OBJECT +import java.util.concurrent.CancellationException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +#endif + +/** + * + * A Type Specific Task interface that allows you to keep track of the task that is currently running.
+ * It extends Runnable future and supports said functions but also provides quality of life functions like:
+ * + * - isSuccesfull: which allows to detect if the task was completed properly and not interrupted or crashed. + * - pause/resume: which allows to pause/resume the task at any moment, making it easier to create thread-safe actions. + * @Type(T) + */ +public interface TASK KEY_GENERIC_TYPE extends RunnableFuture { + /** + * Helper function to detect if the task is currently paused. + * @return true if paused + */ + public boolean isPaused(); + + /** + * Pauses the task, which lets the thread finish without completing the task. + * Tasks are written in the way where they can pause without any issues. + * This won't be instant, as this function is applied asynchronous and doesn't check if the thread paused. + * So make sure it had the time to pause. + */ + public void pause(); + + /** + * Pauses the task, which lets the thread finish without completing the task. + * Tasks are written in the way where they can pause without any issues. + * This won't be instant, as this function is applied asynchronous. + * It will await the pausing of the task. + */ + public void awaitPausing(); + + /** + * Continues the task if it wasn't already completed. + * This is done by resubmitting the task to the executor provided. + */ + public void resume(); + + /** + * Quality of life function that allows to detect if no cancellation/exception was applied to this task and it completed on its own. + * @return true if it was properly completed + */ + public boolean isSuccessful(); + +#if !TYPE_OBJECT + /** + * A Type Specific get method that allows to reduce (un)boxing of primtives. + * + * Waits if necessary for the computation to complete, and then + * retrieves its result. + * + * @return the computed result as primitive + * @throws CancellationException if the computation was cancelled + * @throws ExecutionException if the computation threw an exception + * @throws InterruptedException if the current thread was interrupted + * while waiting + */ + public KEY_TYPE GET_KEY() throws InterruptedException, ExecutionException; + + /** + * Waits if necessary for at most the given time for the computation + * to complete, and then retrieves its result, if available. + * + * @param timeout the maximum time to wait + * @param unit the time unit of the timeout argument + * @return the computed result as primitive + * @throws CancellationException if the computation was cancelled + * @throws ExecutionException if the computation threw an exception + * @throws InterruptedException if the current thread was interrupted while waiting + * @throws TimeoutException if the wait timed out + */ + public KEY_TYPE GET_KEY(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; + + @Override + @Deprecated + public default CLASS_TYPE get() throws InterruptedException, ExecutionException { return KEY_TO_OBJ(GET_KEY()); } + + @Override + @Deprecated + public default CLASS_TYPE get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return KEY_TO_OBJ(GET_KEY(timeout, unit)); } +#endif } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/collections/templates/functions/function/Function.template b/src/builder/resources/speiger/assets/collections/templates/functions/function/Function.template index 7e5c8e6..26443e2 100644 --- a/src/builder/resources/speiger/assets/collections/templates/functions/function/Function.template +++ b/src/builder/resources/speiger/assets/collections/templates/functions/function/Function.template @@ -1,134 +1,134 @@ -package speiger.src.collections.PACKAGE.functions.function; - -#if VALUE_BOOLEAN || SAME_TYPE -import java.util.Objects; -#endif - -/** - * A Type Specific Function interface that reduces boxing/unboxing and fills the gaps of interfaces that are missing. - * @Type(T) - * @ValueType(V) - */ -@FunctionalInterface -#if JDK_FUNCTION -public interface FUNCTION KEY_VALUE_GENERIC_TYPE extends JAVA_FUNCTION KEY_VALUE_GENERIC_TYPE -#else -public interface FUNCTION KEY_VALUE_GENERIC_TYPE -#endif -{ - /** - * Type Specific get function to reduce boxing/unboxing - * @param k the value that should be processed - * @return the result of the function - */ - public VALUE_TYPE APPLY(KEY_TYPE k); - -#if SAME_TYPE - /** - * Creates a Default function that returns the input provided. - * @Type(T) - * @return a input returning function - */ - public static GENERIC_KEY_BRACES FUNCTION KEY_SAME_GENERIC_TYPE identity() { - return T -> T; - } - - /** - * Returns a composed function that first applies the {@code before} - * function to its input, and then applies this function to the result. - * If evaluation of either function throws an exception, it is relayed to - * the caller of the composed function. - * - * @Type(I) - * @param before the function that should be used first - * @return a composed function with a different starting function. - */ - public default GENERIC_SPECIAL_VALUE_BRACES FUNCTION SV_GENERIC_TYPE compose(FUNCTION SK_GENERIC_TYPE before) { - Objects.requireNonNull(before); - return T -> APPLY(before.APPLY(T)); - } - - /** - * Returns a composed function that first applies this function to - * its input, and then applies the {@code after} function to the result. - * If evaluation of either function throws an exception, it is relayed to - * the caller of the composed function. - * - * @Type(I) - * @param after the function that should be used last - * @return a composed function with a different starting function. - */ - public default GENERIC_SPECIAL_VALUE_BRACES FUNCTION KS_GENERIC_TYPE andThen(FUNCTION VS_GENERIC_TYPE after) { - Objects.requireNonNull(after); - return T -> after.APPLY(APPLY(T)); - } - -#endif -#if VALUE_BOOLEAN - /** - * Creates a Always true function that may be useful if you don't need to process information or just want a default. - * @Type(T) - * @return a default returning function - */ - public static GENERIC_KEY_BRACES FUNCTION KEY_GENERIC_TYPE alwaysTrue() { - return T -> true; - } - - /** - * Creates a Always false function that may be useful if you don't need to process information or just want a default. - * @Type(T) - * @return a default returning function - */ - public static GENERIC_KEY_BRACES FUNCTION KEY_GENERIC_TYPE alwaysFalse() { - return T -> false; - } - - /** - * A Type specific and-function helper function that reduces boxing/unboxing - * @param other the other function that should be merged with. - * @return a function that compares values in a and comparason - */ - public default FUNCTION KEY_VALUE_GENERIC_TYPE andType(FUNCTION KEY_VALUE_GENERIC_TYPE other) { - Objects.requireNonNull(other); - return T -> APPLY(T) && other.APPLY(T); - } - -#if JDK_FUNCTION - @Override - @Deprecated - public default FUNCTION KEY_VALUE_GENERIC_TYPE and(JAVA_FUNCTION KEY_VALUE_SUPER_GENERIC_TYPE other) { - Objects.requireNonNull(other); - return T -> APPLY(T) && other.APPLY(T); - } - - @Override -#else - /** - * A type specific inverter function - * @return the same function but inverts the result - */ -#endif - public default FUNCTION KEY_VALUE_GENERIC_TYPE negate() { - return T -> !APPLY(T); - } - - /** - * A Type specific or-function helper function that reduces boxing/unboxing - * @param other the other function that should be merged with. - * @return a function that compares values in a or comparason - */ - public default FUNCTION KEY_VALUE_GENERIC_TYPE orType(FUNCTION KEY_VALUE_GENERIC_TYPE other) { - Objects.requireNonNull(other); - return T -> APPLY(T) || other.APPLY(T); - } - -#if JDK_FUNCTION - @Override - @Deprecated - public default FUNCTION KEY_VALUE_GENERIC_TYPE or(JAVA_FUNCTION KEY_VALUE_SUPER_GENERIC_TYPE other) { - Objects.requireNonNull(other); - return T -> APPLY(T) || other.APPLY(T); - } -#endif -#endif +package speiger.src.collections.PACKAGE.functions.function; + +#if VALUE_BOOLEAN || SAME_TYPE +import java.util.Objects; +#endif + +/** + * A Type Specific Function interface that reduces boxing/unboxing and fills the gaps of interfaces that are missing. + * @Type(T) + * @ValueType(V) + */ +@FunctionalInterface +#if JDK_FUNCTION +public interface FUNCTION KEY_VALUE_GENERIC_TYPE extends JAVA_FUNCTION KEY_VALUE_GENERIC_TYPE +#else +public interface FUNCTION KEY_VALUE_GENERIC_TYPE +#endif +{ + /** + * Type Specific get function to reduce boxing/unboxing + * @param k the value that should be processed + * @return the result of the function + */ + public VALUE_TYPE APPLY(KEY_TYPE k); + +#if SAME_TYPE + /** + * Creates a Default function that returns the input provided. + * @Type(T) + * @return a input returning function + */ + public static GENERIC_KEY_BRACES FUNCTION KEY_SAME_GENERIC_TYPE identity() { + return T -> T; + } + + /** + * Returns a composed function that first applies the {@code before} + * function to its input, and then applies this function to the result. + * If evaluation of either function throws an exception, it is relayed to + * the caller of the composed function. + * + * @Type(I) + * @param before the function that should be used first + * @return a composed function with a different starting function. + */ + public default GENERIC_SPECIAL_VALUE_BRACES FUNCTION SV_GENERIC_TYPE compose(FUNCTION SK_GENERIC_TYPE before) { + Objects.requireNonNull(before); + return T -> APPLY(before.APPLY(T)); + } + + /** + * Returns a composed function that first applies this function to + * its input, and then applies the {@code after} function to the result. + * If evaluation of either function throws an exception, it is relayed to + * the caller of the composed function. + * + * @Type(I) + * @param after the function that should be used last + * @return a composed function with a different starting function. + */ + public default GENERIC_SPECIAL_VALUE_BRACES FUNCTION KS_GENERIC_TYPE andThen(FUNCTION VS_GENERIC_TYPE after) { + Objects.requireNonNull(after); + return T -> after.APPLY(APPLY(T)); + } + +#endif +#if VALUE_BOOLEAN + /** + * Creates a Always true function that may be useful if you don't need to process information or just want a default. + * @Type(T) + * @return a default returning function + */ + public static GENERIC_KEY_BRACES FUNCTION KEY_GENERIC_TYPE alwaysTrue() { + return T -> true; + } + + /** + * Creates a Always false function that may be useful if you don't need to process information or just want a default. + * @Type(T) + * @return a default returning function + */ + public static GENERIC_KEY_BRACES FUNCTION KEY_GENERIC_TYPE alwaysFalse() { + return T -> false; + } + + /** + * A Type specific and-function helper function that reduces boxing/unboxing + * @param other the other function that should be merged with. + * @return a function that compares values in a and comparason + */ + public default FUNCTION KEY_VALUE_GENERIC_TYPE andType(FUNCTION KEY_VALUE_GENERIC_TYPE other) { + Objects.requireNonNull(other); + return T -> APPLY(T) && other.APPLY(T); + } + +#if JDK_FUNCTION + @Override + @Deprecated + public default FUNCTION KEY_VALUE_GENERIC_TYPE and(JAVA_FUNCTION KEY_VALUE_SUPER_GENERIC_TYPE other) { + Objects.requireNonNull(other); + return T -> APPLY(T) && other.APPLY(T); + } + + @Override +#else + /** + * A type specific inverter function + * @return the same function but inverts the result + */ +#endif + public default FUNCTION KEY_VALUE_GENERIC_TYPE negate() { + return T -> !APPLY(T); + } + + /** + * A Type specific or-function helper function that reduces boxing/unboxing + * @param other the other function that should be merged with. + * @return a function that compares values in a or comparason + */ + public default FUNCTION KEY_VALUE_GENERIC_TYPE orType(FUNCTION KEY_VALUE_GENERIC_TYPE other) { + Objects.requireNonNull(other); + return T -> APPLY(T) || other.APPLY(T); + } + +#if JDK_FUNCTION + @Override + @Deprecated + public default FUNCTION KEY_VALUE_GENERIC_TYPE or(JAVA_FUNCTION KEY_VALUE_SUPER_GENERIC_TYPE other) { + Objects.requireNonNull(other); + return T -> APPLY(T) || other.APPLY(T); + } +#endif +#endif } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/collections/templates/lists/ArrayList.template b/src/builder/resources/speiger/assets/collections/templates/lists/ArrayList.template index 59e982b..afb705d 100644 --- a/src/builder/resources/speiger/assets/collections/templates/lists/ArrayList.template +++ b/src/builder/resources/speiger/assets/collections/templates/lists/ArrayList.template @@ -1,1198 +1,1200 @@ -package speiger.src.collections.PACKAGE.lists; - -import java.util.Arrays; -#if TYPE_OBJECT -import java.util.Comparator; -#endif -import java.util.Collection; -import java.util.Iterator; -import java.util.Objects; -#if TYPE_OBJECT -#if IARRAY_FEATURE || TYPE_OBJECT -import java.util.function.Consumer; -#endif - -import java.util.function.BiFunction; -#endif -#if !TYPE_OBJECT && JDK_FUNCTION -import java.util.function.PREDICATE; -#endif -import java.util.function.Predicate; -import java.util.function.UnaryOperator; -#if PRIMITIVES -#if !JDK_FUNCTION -import java.util.function.JAVA_PREDICATE; -#endif -import java.util.function.JAVA_UNARY_OPERATOR; -import java.nio.JAVA_BUFFER; -#endif - -import speiger.src.collections.PACKAGE.collections.COLLECTION; -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.collections.STACK; -#endif -import speiger.src.collections.PACKAGE.collections.ITERATOR; -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.functions.COMPARATOR; -import speiger.src.collections.PACKAGE.functions.CONSUMER; -#endif -import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; -#if !JDK_FUNCTION -import speiger.src.collections.PACKAGE.functions.function.PREDICATE; -#endif -import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; -import speiger.src.collections.PACKAGE.utils.ARRAYS; -import speiger.src.collections.objects.utils.ObjectArrays; -import speiger.src.collections.PACKAGE.utils.ITERATORS; -#if TYPE_OBJECT -import speiger.src.collections.utils.Stack; -#endif -#if PRIMITIVES && SPLIT_ITERATOR_FEATURE && STREAM_FEATURE -import java.util.stream.JAVA_STREAM; -import java.util.stream.StreamSupport; -#endif -#if IARRAY_FEATURE -import speiger.src.collections.PACKAGE.utils.IARRAY; -#endif -#if SPLIT_ITERATOR_FEATURE -import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR; -import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS; -#endif -#if !IARRAY_FEATURE -import speiger.src.collections.utils.IArray; -#endif -import speiger.src.collections.utils.SanityChecks; - -/** - * A Type-Specific Array-based implementation of list that is written to reduce (un)boxing - * -#if IARRAY_FEATURE - *

This implementation is optimized to improve how data is processed with interfaces like {@link IARRAY}, {@link STACK} -#else - *

This implementation is optimized to improve how data is processed with interfaces like {@link IArray}, {@link STACK} -#endif - * and with optimized functions that use type-specific implementations for primitives and optimized logic for bulkactions. - * - * @Type(T) - */ -#if IARRAY_FEATURE -public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE implements IARRAY KEY_GENERIC_TYPE, STACK KEY_GENERIC_TYPE -#else -public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE implements IArray, STACK KEY_GENERIC_TYPE -#endif -{ - static final int DEFAULT_ARRAY_SIZE = 10; - - /** The backing array */ - protected transient KEY_TYPE[] data; - /** The current size of the elements stored in the backing array */ - protected int size = 0; - - /** - * Creates a new ArrayList with a Empty array. - */ - public ARRAY_LIST() { - data = EMPTY_KEY_ARRAY; - } - - /** - * Creates a new ArrayList with the specific requested size - * @param size the minimum initial size of the Backing array - */ - public ARRAY_LIST(int size) { - if(size < 0) throw new IllegalStateException("Size has to be 0 or greater"); - data = NEW_KEY_ARRAY(size); - } - - /** - * Creates a new ArrayList a copy with the contents of the Collection. - * @param c the elements that should be added into the list - */ - @Primitive - public ARRAY_LIST(Collection c) { - this(c.size()); - size = ITERATORS.unwrap(data, c.iterator()); - } - - /** - * Creates a new ArrayList a copy with the contents of the Collection. - * @param c the elements that should be added into the list - */ - public ARRAY_LIST(COLLECTION KEY_GENERIC_TYPE c) { - this(c.size()); - size = ITERATORS.unwrap(data, c.iterator()); - } - - /** - * Creates a new ArrayList a copy with the contents of the List. - * @param l the elements that should be added into the list - */ - public ARRAY_LIST(LIST KEY_GENERIC_TYPE l) { - this(l.size()); - size = l.size(); - l.getElements(0, data, 0, size); - } - - /** - * Creates a new ArrayList with a Copy of the array - * @param a the array that should be copied - */ - public ARRAY_LIST(KEY_TYPE... a) { - this(a, 0, a.length); - } - - /** - * Creates a new ArrayList with a Copy of the array with a custom length - * @param a the array that should be copied - * @param length the desired length that should be copied - */ - public ARRAY_LIST(KEY_TYPE[] a, int length) { - this(a, 0, length); - } - - /** - * Creates a new ArrayList with a Copy of the array with in the custom range. - * @param a the array that should be copied - * @param offset the starting offset of where the array should be copied from - * @param length the desired length that should be copied - * @throws IllegalStateException if offset is smaller then 0 - * @throws IllegalStateException if the offset + length exceeds the array length - */ - public ARRAY_LIST(KEY_TYPE[] a, int offset, int length) { - this(length); - SanityChecks.checkArrayCapacity(a.length, offset, length); - System.arraycopy(a, offset, data, 0, length); - size = length; - } - - /** - * Creates a wrapped arraylist that uses the array as backing array - * @param a elements that should be wrapped - * @Type(T) - * @return a Wrapped list using the input array - */ - public static GENERIC_KEY_BRACES ARRAY_LIST KEY_GENERIC_TYPE wrap(KEY_TYPE... a) { - return wrap(a, a.length); - } - - /** - * Creates a wrapped arraylist that uses the array as backing array and a custom fill size - * @param a elements that should be wrapped - * @param length the size of the elements within the array - * @Type(T) - * @return a Wrapped list using the input array - */ - public static GENERIC_KEY_BRACES ARRAY_LIST KEY_GENERIC_TYPE wrap(KEY_TYPE[] a, int length) { - SanityChecks.checkArrayCapacity(a.length, 0, length); - ARRAY_LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); - list.data = a; - list.size = length; - return list; - } - -#if TYPE_OBJECT - /** - * Creates a new ArrayList with a EmptyObject array of the Type requested - * @param c the type of the array - * @Type(T) - * @return a typed List - */ - public static GENERIC_KEY_BRACES ARRAY_LIST KEY_GENERIC_TYPE of(Class c) { - ARRAY_LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); - list.data = (KEY_TYPE[])ObjectArrays.newArray(c, 0); - return list; - } - - /** - * Creates a new ArrayList with a EmptyObject array of the Type requested - * @param c the type of the array - * @param size the initial size of the backing array - * @Type(T) - * @return a typed List - */ - public static GENERIC_KEY_BRACES ARRAY_LIST KEY_GENERIC_TYPE of(Class c, int size) { - ARRAY_LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); - list.data = (KEY_TYPE[])ObjectArrays.newArray(c, size); - return list; - } - -#endif - /** - * Appends the specified element to the end of this list. - * - * @param e element to be appended to this list - * @return true (as specified by {@link Collection#add}) - */ - @Override - public boolean add(KEY_TYPE e) { - grow(size + 1); - data[size++] = e; - return true; - } - - /** - * Appends the specified element to the end of this Stack. - * @param e element to be appended to this Stack - */ - @Override - public void push(KEY_TYPE e) { - add(e); - } - - /** - * Appends the specified element to the index of the list - * @param index the index where to append the element to - * @param e the element to append to the list - * @throws IndexOutOfBoundsException if index is outside of the lists range - */ - @Override - public void add(int index, KEY_TYPE e) { - checkAddRange(index); - grow(size + 1); - if(index != size) System.arraycopy(data, index, data, index+1, size - index); - data[index] = e; - size++; - } - - /** - * Appends the specified elements to the index of the list. - * This function may delegate to more appropriate function if necessary - * @param index the index where to append the elements to - * @param c the elements to append to the list - * @throws IndexOutOfBoundsException if index is outside of the lists range - * @throws NullPointerException if collection contains a null element - */ - @Override - @Primitive - public boolean addAll(int index, Collection c) { - if(c instanceof COLLECTION) return addAll(index, (COLLECTION KEY_GENERIC_TYPE)c); - int add = c.size(); - if(add <= 0) return false; -#if !TYPE_OBJECT - if(c.contains(null)) throw new NullPointerException(); -#endif - grow(size + add); - if(index != size) System.arraycopy(data, index, data, index+add, size - index); - size+=add; - Iterator iter = c.iterator(); - while(add-- != 0) data[index++] = OBJ_TO_KEY(iter.next()); - return true; - } - - /** - * Appends the specified elements to the index of the list. - * This function may delegate to more appropriate function if necessary - * @param index the index where to append the elements to - * @param c the elements to append to the list - * @throws IndexOutOfBoundsException if index is outside of the lists range - */ - @Override - public boolean addAll(int index, COLLECTION KEY_GENERIC_TYPE c) { - if(c instanceof LIST) return addAll(index, (LIST KEY_GENERIC_TYPE)c); - int add = c.size(); - if(add <= 0) return false; - grow(size + add); - if(index != size) System.arraycopy(data, index, data, index+add, size - index); - size+=add; - ITERATOR KEY_GENERIC_TYPE iter = c.iterator(); - while(add-- != 0) data[index++] = iter.NEXT(); - return true; - } - - /** - * Appends the specified elements to the index of the list. - * @param index the index where to append the elements to - * @param c the elements to append to the list - * @throws IndexOutOfBoundsException if index is outside of the lists range - */ - @Override - public boolean addAll(int index, LIST KEY_GENERIC_TYPE c) { - int add = c.size(); - if(add <= 0) return false; - checkAddRange(index); - grow(size + add); - if(index != size) System.arraycopy(data, index, data, index+add, size - index); - size+=add; - c.getElements(0, data, index, c.size()); - return true; - } - - @Override - public boolean addAll(KEY_TYPE[] e, int offset, int length) { - if(length <= 0) return false; - SanityChecks.checkArrayCapacity(e.length, offset, length); - grow(size + length); - System.arraycopy(e, offset, data, size, length); - size+=length; - return true; - } - - /** - * Appends the specified array elements to the index of the list. - * @param from the index where to append the elements to - * @param a the elements to append to the list - * @param offset where to start ino the array - * @param length the amount of elements to insert - * @throws IndexOutOfBoundsException if index is outside of the lists range - */ - @Override - public void addElements(int from, KEY_TYPE[] a, int offset, int length) { - if(length <= 0) return; - checkAddRange(from); - SanityChecks.checkArrayCapacity(a.length, offset, length); - grow(size + length); - if(from != size) System.arraycopy(data, from, data, from+length, size - from); - size+=length; - System.arraycopy(a, offset, data, from, length); - } - - /** - * A function to fast fetch elements from the list - * @param from index where the list should be fetching elements from - * @param a the array where the values should be inserted to - * @param offset the startIndex of where the array should be written to - * @param length the number of elements the values should be fetched from - * @return the inputArray - * @throws NullPointerException if the array is null - * @throws IndexOutOfBoundsException if from is outside of the lists range - * @throws IllegalStateException if offset or length are smaller then 0 or exceed the array length - */ - @Override - public KEY_TYPE[] getElements(int from, KEY_TYPE[] a, int offset, int length) { - SanityChecks.checkArrayCapacity(size, from, length); - SanityChecks.checkArrayCapacity(a.length, offset, length); - System.arraycopy(data, from, a, offset, length); - return a; - } - - /** - * a function to fast remove elements from the list. - * @param from the start index of where the elements should be removed from (inclusive) - * @param to the end index of where the elements should be removed to (exclusive) - */ - @Override - public void removeElements(int from, int to) { - checkRange(from); - checkAddRange(to); - int length = to - from; - if(length <= 0) return; - if(to != size) System.arraycopy(data, to, data, from, size - to); - size -= length; -#if TYPE_OBJECT - for(int i = 0;i K[] extractElements(int from, int to, Class type) { - checkRange(from); - checkAddRange(to); - int length = to - from; - if(length <= 0) return ARRAYS.newArray(type, 0); - K[] a = ARRAYS.newArray(type, length); - System.arraycopy(data, from, a, 0, length); - if(to != size) System.arraycopy(data, to, data, from, size - to); - size -= length; - for(int i = 0;i=0;i--) - if(data[i] == null) return i; - return -1; - } -#else - if(o == null) return -1; -#endif - for(int i = size - 1;i>=0;i--) { - if(EQUALS_KEY_TYPE(data[i], o)) return i; - } - return -1; - } - -#if TYPE_OBJECT - /** - * Sorts the elements specified by the Natural order either by using the Comparator or the elements - * @param c the sorter of the elements, can be null - * @see java.util.List#sort(Comparator) - */ - @Override - public void sort(Comparator c) { - if(c != null) ARRAYS.stableSort(data, size, c); - else ARRAYS.stableSort(data, size); - } - - /** - * Sorts the elements specified by the Natural order either by using the Comparator or the elements using a unstable sort - * @param c the sorter of the elements, can be null - * @see java.util.List#sort(Comparator) - */ - @Override - public void unstableSort(Comparator c) { - if(c != null) ARRAYS.unstableSort(data, size, c); - else ARRAYS.unstableSort(data, size); - } - -#else - /** - * A Type Specific implementation of the Collection#contains function. - * @param e the element that is searched for. - * @return if the element was found - */ - @Override - public boolean contains(KEY_TYPE e) { - return indexOf(e) != -1; - } - - /** - * A Type-Specific function to find the index of a given element - * @param e the element that is searched for - * @return the index of the element if found. (if not found then -1) - */ - @Override - public int indexOf(KEY_TYPE e) { - for(int i = 0;i=0;i--) { - if(KEY_EQUALS(data[i], e)) return i; - } - return -1; - } - - /** - * Sorts the elements specified by the Natural order either by using the Comparator or the elements - * @param c the sorter of the elements, can be null - * @see java.util.List#sort(java.util.Comparator) - * @see ARRAYS#stableSort(KEY_TYPE[], COMPARATOR) - */ - @Override - public void sort(COMPARATOR c) { - if(c != null) ARRAYS.stableSort(data, size, c); - else ARRAYS.stableSort(data, size); - } - - /** - * Sorts the elements specified by the Natural order either by using the Comparator or the elements using a unstable sort - * @param c the sorter of the elements, can be null - * @see java.util.List#sort(java.util.Comparator) - * @see ARRAYS#unstableSort(KEY_TYPE[], COMPARATOR) - */ - @Override - public void unstableSort(COMPARATOR c) { - if(c != null) ARRAYS.unstableSort(data, size, c); - else ARRAYS.unstableSort(data, size); - } - -#endif - /** - * A Type-Specific get function to reduce (un)boxing - * @param index the index of the element to fetch - * @return the value of the requested index - * @throws IndexOutOfBoundsException if the index is out of range - */ - @Override - public KEY_TYPE GET_KEY(int index) { - checkRange(index); - return data[index]; - } - - /** - * Provides the Selected Object from the stack. - * Top to bottom - * @param index of the element that should be provided - * @return the element that was requested - * @throws ArrayIndexOutOfBoundsException if the index is out of bounds - * @see speiger.src.collections.utils.Stack#peek(int) - */ - @Override - public KEY_TYPE peek(int index) { - checkRange((size() - 1) - index); - return data[(size() - 1) - index]; - } - -#if IARRAY_FEATURE - /** - * Provides the Underlying Array in the Implementation - * @return underlying Array - * @throws ClassCastException if the return type does not match the underlying array. (Only for Object Implementations) - */ - @Override - public KEY_TYPE[] elements() { - return data; - } - -#if TYPE_OBJECT - /** - * @return if the array is castable - */ - @Override - public boolean isCastable() { - return data.getClass() != Object[].class; - } - -#endif -#endif - /** - * A Type Specific foreach function that reduces (un)boxing - * - * @implSpec - *

The default implementation behaves as if: - *

{@code
-	 * 	for(int i = 0;i
-	 *
-	 * @param action The action to be performed for each element
-	 * @throws NullPointerException if the specified action is null
-	 * @see Iterable#forEach(java.util.function.Consumer)
-	 */
-	@Override
-	public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
-		Objects.requireNonNull(action);
-		for(int i = 0;i void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) {
-		Objects.requireNonNull(action);
-		for(int i = 0;i KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) {
-		Objects.requireNonNull(operator);
-		KEY_SPECIAL_TYPE state = identity;
-		for(int i = 0;i o) {
-#if PRIMITIVES
-		Objects.requireNonNull(o);
-#if TYPE_BYTE || TYPE_SHORT || TYPE_CHAR || TYPE_FLOAT
-		REPLACE(T -> OBJ_TO_KEY(o.apply(KEY_TO_OBJ(SanityChecks.SANITY_CAST(T)))));
-#else
-		REPLACE(T -> OBJ_TO_KEY(o.apply(KEY_TO_OBJ(T))));
-#endif
-#else
-		Objects.requireNonNull(o);
-		for(int i = 0;i c) {
-		if(c.isEmpty()) return false;
-		boolean modified = false;
-		int j = 0;
-		for(int i = 0;i c) {
-		if(c.isEmpty()) {
-			boolean modifed = size > 0;
-			clear();
-			return modifed;
-		}
-		boolean modified = false;
-		int j = 0;
-		for(int i = 0;i filter) {
-		Objects.requireNonNull(filter);
-		boolean modified = false;
-		int j = 0;
-		for(int i = 0;i 0;
-			clear();
-			return modifed;
-		}
-		boolean modified = false;
-		int j = 0;
-		for(int i = 0;i 0;
-			forEach(r);
-			clear();
-			return modifed;
-		}
-		int j = 0;
-		for(int i = 0;i E[] toArray(E[] a) {
-		if(a == null) a = (E[])new Object[size];
-		else if(a.length < size) a = (E[])ObjectArrays.newArray(a.getClass().getComponentType(), size);
-#if TYPE_OBJECT
-        System.arraycopy(data, 0, a, 0, size);
-#else
-		for(int i = 0;i size) a[size] = null;
-		return a;
-	}
-	
-#if !TYPE_OBJECT
-	@Override
-	public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) {
-		if(a.length < size) a = new KEY_TYPE[size];
-		System.arraycopy(data, 0, a, 0, size);
-		if (a.length > size) a[size] = EMPTY_KEY_VALUE;
-		return a;
-	}
-	
-#endif
-	/**
-	 * A function to return the size of the list
-	 * @return the size of elements in the list
-	 */
-	@Override
-	public int size() {
-		return size;
-	}
-	
-	/**
-	 * A function to ensure the elements are within the requested size.
-	 * If smaller then the stored elements they get removed as needed.
-	 * If bigger it is ensured that enough room is provided depending on the implementation
-	 * @param size the requested amount of elements/room for elements
-	 */
-	@Override
-	public void size(int size) {
-		if(size > data.length)
-			data = Arrays.copyOf(data, size);
-		else if(size < size() && size >= 0)
-			Arrays.fill(data, size, size(), EMPTY_KEY_VALUE);
-		this.size = size;
-	}
-	
-	/**
-	 * A function to clear all elements in the list.
-	 */
-	@Override
-	public void clear() {
-#if TYPE_OBJECT
-		for(int i = 0;i size() || size() == data.length) return false;
-		int value = Math.max(size, size());
-		data = value == 0 ? EMPTY_KEY_ARRAY : Arrays.copyOf(data, value);
-		return true;
-	}
-	
-	/**
-	 * Trims the collection down to the requested size and clears all elements while doing so
-	 * @param size the amount of elements that should be allowed
-	 * @note this will enforce minimum size of the collection itself
-	 */
-	@Override
-	public void clearAndTrim(int size) {
-		if(data.length <= size) {
-			clear();
-			return;
-		}
-		data = size == 0 ? EMPTY_KEY_ARRAY : NEW_KEY_ARRAY(size);
-		this.size = size;
-	}
-	
-	/**
-	 * Increases the capacity of this implementation instance, if necessary,
-	 * to ensure that it can hold at least the number of elements specified by
-	 * the minimum capacity argument.
-	 *
-	 * @param size the desired minimum capacity
-	 */
-	@Override
-	public void ensureCapacity(int size) {
-		grow(size);
-	}
-	
-	@Override
-	public ARRAY_LIST KEY_GENERIC_TYPE copy() {
-		ARRAY_LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES();
-		list.data = Arrays.copyOf(data, data.length);
-		list.size = size;
-		return list;
-	}
-	
-	protected void grow(int capacity) {
-		if(capacity <= data.length) return;
-		data = Arrays.copyOf(data, data == ARRAYS.EMPTY_ARRAY ? Math.max(DEFAULT_ARRAY_SIZE, capacity) : (int)Math.max(Math.min((long)data.length + (data.length >> 1), SanityChecks.MAX_ARRAY_SIZE), capacity));		
-	}
-	
-	protected void checkRange(int index) {
-		if (index < 0 || index >= size)
-			throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
-	}
-	
-	protected void checkAddRange(int index) {
-		if (index < 0 || index > size)
-			throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
-	}
-	
-#if SPLIT_ITERATOR_FEATURE
-#if PRIMITIVES && STREAM_FEATURE
-	/**
-	 * Returns a Java-Type-Specific Stream to reduce boxing/unboxing.
-	 * @return a Stream of the closest java type
-	 * @note characteristics are ordered, sized, subsized
-	 */
-	@Override
-	public JAVA_STREAM primitiveStream() { return StreamSupport.NEW_STREAM(SPLIT_ITERATORS.createArrayJavaSplititerator(data, size, 16464), false); }
-	
-#endif
-	/**
-	 * A Type Specific Type Splititerator to reduce boxing/unboxing
-	 * @return type specific splititerator
-	 * @note characteristics are ordered, sized, subsized
-	 */
-	@Override
-	public SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createArraySplititerator(data, size, 16464); }
-#endif
+package speiger.src.collections.PACKAGE.lists;
+
+import java.util.Arrays;
+#if TYPE_OBJECT
+import java.util.Comparator;
+#endif
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.Objects;
+#if TYPE_OBJECT
+#if IARRAY_FEATURE || TYPE_OBJECT
+import java.util.function.Consumer;
+#endif
+
+import java.util.function.BiFunction;
+#endif
+#if !TYPE_OBJECT && JDK_FUNCTION
+import java.util.function.PREDICATE;
+#endif
+import java.util.function.Predicate;
+import java.util.function.UnaryOperator;
+#if PRIMITIVES
+#if !JDK_FUNCTION
+import java.util.function.JAVA_PREDICATE;
+#endif
+import java.util.function.JAVA_UNARY_OPERATOR;
+import java.nio.JAVA_BUFFER;
+#endif
+
+import speiger.src.collections.PACKAGE.collections.COLLECTION;
+#if !TYPE_OBJECT
+import speiger.src.collections.PACKAGE.collections.STACK;
+#endif
+import speiger.src.collections.PACKAGE.collections.ITERATOR;
+#if !TYPE_OBJECT
+import speiger.src.collections.PACKAGE.functions.COMPARATOR;
+import speiger.src.collections.PACKAGE.functions.CONSUMER;
+#endif
+import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
+#if !JDK_FUNCTION
+import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
+#endif
+import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
+#if !TYPE_OBJECT
+import speiger.src.collections.PACKAGE.utils.ARRAYS;
+#endif
+import speiger.src.collections.objects.utils.ObjectArrays;
+import speiger.src.collections.PACKAGE.utils.ITERATORS;
+#if TYPE_OBJECT
+import speiger.src.collections.utils.Stack;
+#endif
+#if PRIMITIVES && SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
+import java.util.stream.JAVA_STREAM;
+import java.util.stream.StreamSupport;
+#endif
+#if IARRAY_FEATURE
+import speiger.src.collections.PACKAGE.utils.IARRAY;
+#endif
+#if SPLIT_ITERATOR_FEATURE
+import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR;
+import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
+#endif
+#if !IARRAY_FEATURE
+import speiger.src.collections.utils.IArray;
+#endif
+import speiger.src.collections.utils.SanityChecks;
+
+/**
+ * A Type-Specific Array-based implementation of list that is written to reduce (un)boxing
+ * 
+#if IARRAY_FEATURE
+ * 

This implementation is optimized to improve how data is processed with interfaces like {@link IARRAY}, {@link STACK} +#else + *

This implementation is optimized to improve how data is processed with interfaces like {@link IArray}, {@link STACK} +#endif + * and with optimized functions that use type-specific implementations for primitives and optimized logic for bulkactions. + * + * @Type(T) + */ +#if IARRAY_FEATURE +public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE implements IARRAY KEY_GENERIC_TYPE, STACK KEY_GENERIC_TYPE +#else +public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE implements IArray, STACK KEY_GENERIC_TYPE +#endif +{ + static final int DEFAULT_ARRAY_SIZE = 10; + + /** The backing array */ + protected transient KEY_TYPE[] data; + /** The current size of the elements stored in the backing array */ + protected int size = 0; + + /** + * Creates a new ArrayList with a Empty array. + */ + public ARRAY_LIST() { + data = EMPTY_KEY_ARRAY; + } + + /** + * Creates a new ArrayList with the specific requested size + * @param size the minimum initial size of the Backing array + */ + public ARRAY_LIST(int size) { + if(size < 0) throw new IllegalStateException("Size has to be 0 or greater"); + data = NEW_KEY_ARRAY(size); + } + + /** + * Creates a new ArrayList a copy with the contents of the Collection. + * @param c the elements that should be added into the list + */ + @Primitive + public ARRAY_LIST(Collection c) { + this(c.size()); + size = ITERATORS.unwrap(data, c.iterator()); + } + + /** + * Creates a new ArrayList a copy with the contents of the Collection. + * @param c the elements that should be added into the list + */ + public ARRAY_LIST(COLLECTION KEY_GENERIC_TYPE c) { + this(c.size()); + size = ITERATORS.unwrap(data, c.iterator()); + } + + /** + * Creates a new ArrayList a copy with the contents of the List. + * @param l the elements that should be added into the list + */ + public ARRAY_LIST(LIST KEY_GENERIC_TYPE l) { + this(l.size()); + size = l.size(); + l.getElements(0, data, 0, size); + } + + /** + * Creates a new ArrayList with a Copy of the array + * @param a the array that should be copied + */ + public ARRAY_LIST(KEY_TYPE... a) { + this(a, 0, a.length); + } + + /** + * Creates a new ArrayList with a Copy of the array with a custom length + * @param a the array that should be copied + * @param length the desired length that should be copied + */ + public ARRAY_LIST(KEY_TYPE[] a, int length) { + this(a, 0, length); + } + + /** + * Creates a new ArrayList with a Copy of the array with in the custom range. + * @param a the array that should be copied + * @param offset the starting offset of where the array should be copied from + * @param length the desired length that should be copied + * @throws IllegalStateException if offset is smaller then 0 + * @throws IllegalStateException if the offset + length exceeds the array length + */ + public ARRAY_LIST(KEY_TYPE[] a, int offset, int length) { + this(length); + SanityChecks.checkArrayCapacity(a.length, offset, length); + System.arraycopy(a, offset, data, 0, length); + size = length; + } + + /** + * Creates a wrapped arraylist that uses the array as backing array + * @param a elements that should be wrapped + * @Type(T) + * @return a Wrapped list using the input array + */ + public static GENERIC_KEY_BRACES ARRAY_LIST KEY_GENERIC_TYPE wrap(KEY_TYPE... a) { + return wrap(a, a.length); + } + + /** + * Creates a wrapped arraylist that uses the array as backing array and a custom fill size + * @param a elements that should be wrapped + * @param length the size of the elements within the array + * @Type(T) + * @return a Wrapped list using the input array + */ + public static GENERIC_KEY_BRACES ARRAY_LIST KEY_GENERIC_TYPE wrap(KEY_TYPE[] a, int length) { + SanityChecks.checkArrayCapacity(a.length, 0, length); + ARRAY_LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); + list.data = a; + list.size = length; + return list; + } + +#if TYPE_OBJECT + /** + * Creates a new ArrayList with a EmptyObject array of the Type requested + * @param c the type of the array + * @Type(T) + * @return a typed List + */ + public static GENERIC_KEY_BRACES ARRAY_LIST KEY_GENERIC_TYPE of(Class c) { + ARRAY_LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); + list.data = (KEY_TYPE[])ObjectArrays.newArray(c, 0); + return list; + } + + /** + * Creates a new ArrayList with a EmptyObject array of the Type requested + * @param c the type of the array + * @param size the initial size of the backing array + * @Type(T) + * @return a typed List + */ + public static GENERIC_KEY_BRACES ARRAY_LIST KEY_GENERIC_TYPE of(Class c, int size) { + ARRAY_LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); + list.data = (KEY_TYPE[])ObjectArrays.newArray(c, size); + return list; + } + +#endif + /** + * Appends the specified element to the end of this list. + * + * @param e element to be appended to this list + * @return true (as specified by {@link Collection#add}) + */ + @Override + public boolean add(KEY_TYPE e) { + grow(size + 1); + data[size++] = e; + return true; + } + + /** + * Appends the specified element to the end of this Stack. + * @param e element to be appended to this Stack + */ + @Override + public void push(KEY_TYPE e) { + add(e); + } + + /** + * Appends the specified element to the index of the list + * @param index the index where to append the element to + * @param e the element to append to the list + * @throws IndexOutOfBoundsException if index is outside of the lists range + */ + @Override + public void add(int index, KEY_TYPE e) { + checkAddRange(index); + grow(size + 1); + if(index != size) System.arraycopy(data, index, data, index+1, size - index); + data[index] = e; + size++; + } + + /** + * Appends the specified elements to the index of the list. + * This function may delegate to more appropriate function if necessary + * @param index the index where to append the elements to + * @param c the elements to append to the list + * @throws IndexOutOfBoundsException if index is outside of the lists range + * @throws NullPointerException if collection contains a null element + */ + @Override + @Primitive + public boolean addAll(int index, Collection c) { + if(c instanceof COLLECTION) return addAll(index, (COLLECTION KEY_GENERIC_TYPE)c); + int add = c.size(); + if(add <= 0) return false; +#if !TYPE_OBJECT + if(c.contains(null)) throw new NullPointerException(); +#endif + grow(size + add); + if(index != size) System.arraycopy(data, index, data, index+add, size - index); + size+=add; + Iterator iter = c.iterator(); + while(add-- != 0) data[index++] = OBJ_TO_KEY(iter.next()); + return true; + } + + /** + * Appends the specified elements to the index of the list. + * This function may delegate to more appropriate function if necessary + * @param index the index where to append the elements to + * @param c the elements to append to the list + * @throws IndexOutOfBoundsException if index is outside of the lists range + */ + @Override + public boolean addAll(int index, COLLECTION KEY_GENERIC_TYPE c) { + if(c instanceof LIST) return addAll(index, (LIST KEY_GENERIC_TYPE)c); + int add = c.size(); + if(add <= 0) return false; + grow(size + add); + if(index != size) System.arraycopy(data, index, data, index+add, size - index); + size+=add; + ITERATOR KEY_GENERIC_TYPE iter = c.iterator(); + while(add-- != 0) data[index++] = iter.NEXT(); + return true; + } + + /** + * Appends the specified elements to the index of the list. + * @param index the index where to append the elements to + * @param c the elements to append to the list + * @throws IndexOutOfBoundsException if index is outside of the lists range + */ + @Override + public boolean addAll(int index, LIST KEY_GENERIC_TYPE c) { + int add = c.size(); + if(add <= 0) return false; + checkAddRange(index); + grow(size + add); + if(index != size) System.arraycopy(data, index, data, index+add, size - index); + size+=add; + c.getElements(0, data, index, c.size()); + return true; + } + + @Override + public boolean addAll(KEY_TYPE[] e, int offset, int length) { + if(length <= 0) return false; + SanityChecks.checkArrayCapacity(e.length, offset, length); + grow(size + length); + System.arraycopy(e, offset, data, size, length); + size+=length; + return true; + } + + /** + * Appends the specified array elements to the index of the list. + * @param from the index where to append the elements to + * @param a the elements to append to the list + * @param offset where to start ino the array + * @param length the amount of elements to insert + * @throws IndexOutOfBoundsException if index is outside of the lists range + */ + @Override + public void addElements(int from, KEY_TYPE[] a, int offset, int length) { + if(length <= 0) return; + checkAddRange(from); + SanityChecks.checkArrayCapacity(a.length, offset, length); + grow(size + length); + if(from != size) System.arraycopy(data, from, data, from+length, size - from); + size+=length; + System.arraycopy(a, offset, data, from, length); + } + + /** + * A function to fast fetch elements from the list + * @param from index where the list should be fetching elements from + * @param a the array where the values should be inserted to + * @param offset the startIndex of where the array should be written to + * @param length the number of elements the values should be fetched from + * @return the inputArray + * @throws NullPointerException if the array is null + * @throws IndexOutOfBoundsException if from is outside of the lists range + * @throws IllegalStateException if offset or length are smaller then 0 or exceed the array length + */ + @Override + public KEY_TYPE[] getElements(int from, KEY_TYPE[] a, int offset, int length) { + SanityChecks.checkArrayCapacity(size, from, length); + SanityChecks.checkArrayCapacity(a.length, offset, length); + System.arraycopy(data, from, a, offset, length); + return a; + } + + /** + * a function to fast remove elements from the list. + * @param from the start index of where the elements should be removed from (inclusive) + * @param to the end index of where the elements should be removed to (exclusive) + */ + @Override + public void removeElements(int from, int to) { + checkRange(from); + checkAddRange(to); + int length = to - from; + if(length <= 0) return; + if(to != size) System.arraycopy(data, to, data, from, size - to); + size -= length; +#if TYPE_OBJECT + for(int i = 0;i K[] extractElements(int from, int to, Class type) { + checkRange(from); + checkAddRange(to); + int length = to - from; + if(length <= 0) return ARRAYS.newArray(type, 0); + K[] a = ARRAYS.newArray(type, length); + System.arraycopy(data, from, a, 0, length); + if(to != size) System.arraycopy(data, to, data, from, size - to); + size -= length; + for(int i = 0;i=0;i--) + if(data[i] == null) return i; + return -1; + } +#else + if(o == null) return -1; +#endif + for(int i = size - 1;i>=0;i--) { + if(EQUALS_KEY_TYPE(data[i], o)) return i; + } + return -1; + } + +#if TYPE_OBJECT + /** + * Sorts the elements specified by the Natural order either by using the Comparator or the elements + * @param c the sorter of the elements, can be null + * @see java.util.List#sort(Comparator) + */ + @Override + public void sort(Comparator c) { + if(c != null) ARRAYS.stableSort(data, size, c); + else ARRAYS.stableSort(data, size); + } + + /** + * Sorts the elements specified by the Natural order either by using the Comparator or the elements using a unstable sort + * @param c the sorter of the elements, can be null + * @see java.util.List#sort(Comparator) + */ + @Override + public void unstableSort(Comparator c) { + if(c != null) ARRAYS.unstableSort(data, size, c); + else ARRAYS.unstableSort(data, size); + } + +#else + /** + * A Type Specific implementation of the Collection#contains function. + * @param e the element that is searched for. + * @return if the element was found + */ + @Override + public boolean contains(KEY_TYPE e) { + return indexOf(e) != -1; + } + + /** + * A Type-Specific function to find the index of a given element + * @param e the element that is searched for + * @return the index of the element if found. (if not found then -1) + */ + @Override + public int indexOf(KEY_TYPE e) { + for(int i = 0;i=0;i--) { + if(KEY_EQUALS(data[i], e)) return i; + } + return -1; + } + + /** + * Sorts the elements specified by the Natural order either by using the Comparator or the elements + * @param c the sorter of the elements, can be null + * @see java.util.List#sort(java.util.Comparator) + * @see ARRAYS#stableSort(KEY_TYPE[], COMPARATOR) + */ + @Override + public void sort(COMPARATOR c) { + if(c != null) ARRAYS.stableSort(data, size, c); + else ARRAYS.stableSort(data, size); + } + + /** + * Sorts the elements specified by the Natural order either by using the Comparator or the elements using a unstable sort + * @param c the sorter of the elements, can be null + * @see java.util.List#sort(java.util.Comparator) + * @see ARRAYS#unstableSort(KEY_TYPE[], COMPARATOR) + */ + @Override + public void unstableSort(COMPARATOR c) { + if(c != null) ARRAYS.unstableSort(data, size, c); + else ARRAYS.unstableSort(data, size); + } + +#endif + /** + * A Type-Specific get function to reduce (un)boxing + * @param index the index of the element to fetch + * @return the value of the requested index + * @throws IndexOutOfBoundsException if the index is out of range + */ + @Override + public KEY_TYPE GET_KEY(int index) { + checkRange(index); + return data[index]; + } + + /** + * Provides the Selected Object from the stack. + * Top to bottom + * @param index of the element that should be provided + * @return the element that was requested + * @throws ArrayIndexOutOfBoundsException if the index is out of bounds + * @see speiger.src.collections.utils.Stack#peek(int) + */ + @Override + public KEY_TYPE peek(int index) { + checkRange((size() - 1) - index); + return data[(size() - 1) - index]; + } + +#if IARRAY_FEATURE + /** + * Provides the Underlying Array in the Implementation + * @return underlying Array + * @throws ClassCastException if the return type does not match the underlying array. (Only for Object Implementations) + */ + @Override + public KEY_TYPE[] elements() { + return data; + } + +#if TYPE_OBJECT + /** + * @return if the array is castable + */ + @Override + public boolean isCastable() { + return data.getClass() != Object[].class; + } + +#endif +#endif + /** + * A Type Specific foreach function that reduces (un)boxing + * + * @implSpec + *

The default implementation behaves as if: + *

{@code
+	 * 	for(int i = 0;i
+	 *
+	 * @param action The action to be performed for each element
+	 * @throws NullPointerException if the specified action is null
+	 * @see Iterable#forEach(java.util.function.Consumer)
+	 */
+	@Override
+	public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
+		Objects.requireNonNull(action);
+		for(int i = 0;i void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) {
+		Objects.requireNonNull(action);
+		for(int i = 0;i KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) {
+		Objects.requireNonNull(operator);
+		KEY_SPECIAL_TYPE state = identity;
+		for(int i = 0;i o) {
+#if PRIMITIVES
+		Objects.requireNonNull(o);
+#if TYPE_BYTE || TYPE_SHORT || TYPE_CHAR || TYPE_FLOAT
+		REPLACE(T -> OBJ_TO_KEY(o.apply(KEY_TO_OBJ(SanityChecks.SANITY_CAST(T)))));
+#else
+		REPLACE(T -> OBJ_TO_KEY(o.apply(KEY_TO_OBJ(T))));
+#endif
+#else
+		Objects.requireNonNull(o);
+		for(int i = 0;i c) {
+		if(c.isEmpty()) return false;
+		boolean modified = false;
+		int j = 0;
+		for(int i = 0;i c) {
+		if(c.isEmpty()) {
+			boolean modifed = size > 0;
+			clear();
+			return modifed;
+		}
+		boolean modified = false;
+		int j = 0;
+		for(int i = 0;i filter) {
+		Objects.requireNonNull(filter);
+		boolean modified = false;
+		int j = 0;
+		for(int i = 0;i 0;
+			clear();
+			return modifed;
+		}
+		boolean modified = false;
+		int j = 0;
+		for(int i = 0;i 0;
+			forEach(r);
+			clear();
+			return modifed;
+		}
+		int j = 0;
+		for(int i = 0;i E[] toArray(E[] a) {
+		if(a == null) a = (E[])new Object[size];
+		else if(a.length < size) a = (E[])ObjectArrays.newArray(a.getClass().getComponentType(), size);
+#if TYPE_OBJECT
+        System.arraycopy(data, 0, a, 0, size);
+#else
+		for(int i = 0;i size) a[size] = null;
+		return a;
+	}
+	
+#if !TYPE_OBJECT
+	@Override
+	public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) {
+		if(a.length < size) a = new KEY_TYPE[size];
+		System.arraycopy(data, 0, a, 0, size);
+		if (a.length > size) a[size] = EMPTY_KEY_VALUE;
+		return a;
+	}
+	
+#endif
+	/**
+	 * A function to return the size of the list
+	 * @return the size of elements in the list
+	 */
+	@Override
+	public int size() {
+		return size;
+	}
+	
+	/**
+	 * A function to ensure the elements are within the requested size.
+	 * If smaller then the stored elements they get removed as needed.
+	 * If bigger it is ensured that enough room is provided depending on the implementation
+	 * @param size the requested amount of elements/room for elements
+	 */
+	@Override
+	public void size(int size) {
+		if(size > data.length)
+			data = Arrays.copyOf(data, size);
+		else if(size < size() && size >= 0)
+			Arrays.fill(data, size, size(), EMPTY_KEY_VALUE);
+		this.size = size;
+	}
+	
+	/**
+	 * A function to clear all elements in the list.
+	 */
+	@Override
+	public void clear() {
+#if TYPE_OBJECT
+		for(int i = 0;i size() || size() == data.length) return false;
+		int value = Math.max(size, size());
+		data = value == 0 ? EMPTY_KEY_ARRAY : Arrays.copyOf(data, value);
+		return true;
+	}
+	
+	/**
+	 * Trims the collection down to the requested size and clears all elements while doing so
+	 * @param size the amount of elements that should be allowed
+	 * @note this will enforce minimum size of the collection itself
+	 */
+	@Override
+	public void clearAndTrim(int size) {
+		if(data.length <= size) {
+			clear();
+			return;
+		}
+		data = size == 0 ? EMPTY_KEY_ARRAY : NEW_KEY_ARRAY(size);
+		this.size = size;
+	}
+	
+	/**
+	 * Increases the capacity of this implementation instance, if necessary,
+	 * to ensure that it can hold at least the number of elements specified by
+	 * the minimum capacity argument.
+	 *
+	 * @param size the desired minimum capacity
+	 */
+	@Override
+	public void ensureCapacity(int size) {
+		grow(size);
+	}
+	
+	@Override
+	public ARRAY_LIST KEY_GENERIC_TYPE copy() {
+		ARRAY_LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES();
+		list.data = Arrays.copyOf(data, data.length);
+		list.size = size;
+		return list;
+	}
+	
+	protected void grow(int capacity) {
+		if(capacity <= data.length) return;
+		data = Arrays.copyOf(data, data == ARRAYS.EMPTY_ARRAY ? Math.max(DEFAULT_ARRAY_SIZE, capacity) : (int)Math.max(Math.min((long)data.length + (data.length >> 1), SanityChecks.MAX_ARRAY_SIZE), capacity));		
+	}
+	
+	protected void checkRange(int index) {
+		if (index < 0 || index >= size)
+			throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
+	}
+	
+	protected void checkAddRange(int index) {
+		if (index < 0 || index > size)
+			throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
+	}
+	
+#if SPLIT_ITERATOR_FEATURE
+#if PRIMITIVES && STREAM_FEATURE
+	/**
+	 * Returns a Java-Type-Specific Stream to reduce boxing/unboxing.
+	 * @return a Stream of the closest java type
+	 * @note characteristics are ordered, sized, subsized
+	 */
+	@Override
+	public JAVA_STREAM primitiveStream() { return StreamSupport.NEW_STREAM(SPLIT_ITERATORS.createArrayJavaSplititerator(data, size, 16464), false); }
+	
+#endif
+	/**
+	 * A Type Specific Type Splititerator to reduce boxing/unboxing
+	 * @return type specific splititerator
+	 * @note characteristics are ordered, sized, subsized
+	 */
+	@Override
+	public SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createArraySplititerator(data, size, 16464); }
+#endif
 }
\ No newline at end of file
diff --git a/src/builder/resources/speiger/assets/collections/templates/lists/CopyOnWriteList.template b/src/builder/resources/speiger/assets/collections/templates/lists/CopyOnWriteList.template
index 9210c14..98026b3 100644
--- a/src/builder/resources/speiger/assets/collections/templates/lists/CopyOnWriteList.template
+++ b/src/builder/resources/speiger/assets/collections/templates/lists/CopyOnWriteList.template
@@ -1,2189 +1,2191 @@
-package speiger.src.collections.PACKAGE.lists;
-
-import java.util.Arrays;
-#if TYPE_OBJECT
-import java.util.Comparator;
-#endif
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.NoSuchElementException;
-import java.util.Objects;
-import java.util.concurrent.locks.ReentrantLock;
-import java.util.function.Consumer;
-import java.util.function.Supplier;
-#if TYPE_OBJECT
-import java.util.function.BiFunction;
-#endif
-#if !TYPE_OBJECT && JDK_FUNCTION
-import java.util.function.PREDICATE;
-#endif
-import java.util.function.Predicate;
-import java.util.function.UnaryOperator;
-#if PRIMITIVES
-#if !JDK_FUNCTION
-import java.util.function.JAVA_PREDICATE;
-#endif
-import java.util.function.JAVA_UNARY_OPERATOR;
-import java.nio.JAVA_BUFFER;
-#endif
-
-import speiger.src.collections.PACKAGE.collections.COLLECTION;
-#if !TYPE_OBJECT
-import speiger.src.collections.PACKAGE.collections.STACK;
-#endif
-import speiger.src.collections.PACKAGE.collections.ITERATOR;
-#if !TYPE_OBJECT
-import speiger.src.collections.PACKAGE.functions.COMPARATOR;
-import speiger.src.collections.PACKAGE.functions.CONSUMER;
-#endif
-import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
-#if !JDK_FUNCTION
-import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
-#endif
-import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
-import speiger.src.collections.PACKAGE.utils.ARRAYS;
-import speiger.src.collections.objects.utils.ObjectArrays;
-import speiger.src.collections.PACKAGE.utils.ITERATORS;
-#if TYPE_OBJECT
-import speiger.src.collections.utils.Stack;
-#endif
-#if PRIMITIVES && STREAM_FEATURE && SPLIT_ITERATOR_FEATURE
-import java.util.stream.JAVA_STREAM;
-import java.util.stream.StreamSupport;
-#endif
-#if SPLIT_ITERATOR_FEATURE
-import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR;
-import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
-#endif
-import speiger.src.collections.utils.ITrimmable;
-import speiger.src.collections.utils.SanityChecks;
-
-#if TYPE_OBJECT
-/**
- * A Type-Specific Array-based implementation of list that is written to reduce (un)boxing
- * 
- * 

This implementation is optimized to improve how data is processed with interfaces like {@link ITrimmable}, {@link Stack} - * and with optimized functions that use type-specific implementations for primitives and optimized logic for bulkactions. - * - * @Type(T) - */ -public class COPY_ON_WRITE_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE implements ITrimmable, Stack -#else -/** - * A Type-Specific Array-based implementation of list that is written to reduce (un)boxing - * - *

This implementation is optimized to improve how data is processed with interfaces like {@link ITrimmable}, {@link STACK} - * and with optimized functions that use type-specific implementations for primitives and optimized logic for bulkactions. - */ -public class COPY_ON_WRITE_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE implements ITrimmable, STACK -#endif -{ - /** Access lock */ - transient ReentrantLock lock = new ReentrantLock(); - /** The backing array */ - protected transient KEY_TYPE[] data; - - /** - * Creates a new ArrayList with a Empty array. - */ - public COPY_ON_WRITE_LIST() { - data = EMPTY_KEY_ARRAY; - } - - /** - * Creates a new ArrayList a copy with the contents of the Collection. - * @param c the elements that should be added into the list - */ - @Deprecated - public COPY_ON_WRITE_LIST(Collection c) { - data = NEW_KEY_ARRAY(c.size()); - ITERATORS.unwrap(data, c.iterator()); - } - - /** - * Creates a new ArrayList a copy with the contents of the Collection. - * @param c the elements that should be added into the list - */ - public COPY_ON_WRITE_LIST(COLLECTION KEY_GENERIC_TYPE c) { - data = NEW_KEY_ARRAY(c.size()); - ITERATORS.unwrap(data, c.iterator()); - } - - /** - * Creates a new ArrayList a copy with the contents of the List. - * @param l the elements that should be added into the list - */ - public COPY_ON_WRITE_LIST(LIST KEY_GENERIC_TYPE l) { - data = NEW_KEY_ARRAY(l.size()); - l.getElements(0, data, 0, data.length); - } - - /** - * Creates a new ArrayList with a Copy of the array - * @param a the array that should be copied - */ - public COPY_ON_WRITE_LIST(KEY_TYPE... a) { - this(a, 0, a.length); - } - - /** - * Creates a new ArrayList with a Copy of the array with a custom length - * @param a the array that should be copied - * @param length the desired length that should be copied - */ - public COPY_ON_WRITE_LIST(KEY_TYPE[] a, int length) { - this(a, 0, length); - } - - /** - * Creates a new ArrayList with a Copy of the array with in the custom range. - * @param a the array that should be copied - * @param offset the starting offset of where the array should be copied from - * @param length the desired length that should be copied - * @throws IllegalStateException if offset is smaller then 0 - * @throws IllegalStateException if the offset + length exceeds the array length - */ - public COPY_ON_WRITE_LIST(KEY_TYPE[] a, int offset, int length) { - data = NEW_KEY_ARRAY(length); - SanityChecks.checkArrayCapacity(a.length, offset, length); - System.arraycopy(a, offset, data, 0, length); - } - -#if TYPE_OBJECT - /** - * Creates a new ArrayList with a EmptyObject array of the Type requested - * @param c the type of the array - * @Type(T) - * @return a typed List - */ - public static GENERIC_KEY_BRACES COPY_ON_WRITE_LIST KEY_GENERIC_TYPE of(Class c) { - COPY_ON_WRITE_LIST KEY_GENERIC_TYPE list = new COPY_ON_WRITE_LISTBRACES(); - list.data = (KEY_TYPE[])ObjectArrays.newArray(c, 0); - return list; - } - -#endif - - private void setArray(KEY_TYPE[] data) { - this.data = data; - } - - private KEY_TYPE[] getArray() { - return data; - } - - /** - * Appends the specified element to the end of this list. - * - * @param e element to be appended to this list - * @return true (as specified by {@link Collection#add}) - */ - @Override - public boolean add(KEY_TYPE e) { - ReentrantLock lock = this.lock; - lock.lock(); - try { - KEY_TYPE[] newElements = Arrays.copyOf(data, data.length+1); - newElements[newElements.length-1] = e; - data = newElements; - } - finally { - lock.unlock(); - } - return true; - } - - /** - * Appends the specified element to the end of this Stack. - * @param e element to be appended to this Stack - */ - @Override - public void push(KEY_TYPE e) { - add(e); - } - - /** - * Appends the specified element to the index of the list - * @param index the index where to append the element to - * @param e the element to append to the list - * @throws IndexOutOfBoundsException if index is outside of the lists range - */ - @Override - public void add(int index, KEY_TYPE e) { - ReentrantLock lock = this.lock; - lock.lock(); - try { - KEY_TYPE[] data = this.data; - int size = data.length; - if(index < 0 || index > size) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); - KEY_TYPE[] newElements; - - if(index == size) { - newElements = Arrays.copyOf(data, size+1); - } - else { - newElements = NEW_KEY_ARRAY(size+1); - System.arraycopy(data, 0, newElements, 0, index); - System.arraycopy(data, index, newElements, index + 1, size - index); - } - newElements[index] = e; - this.data = newElements; - } - finally { - lock.unlock(); - } - } - - /** - * Appends the specified elements to the index of the list. - * This function may delegate to more appropriate function if necessary - * @param index the index where to append the elements to - * @param c the elements to append to the list - * @throws IndexOutOfBoundsException if index is outside of the lists range - * @throws NullPointerException if collection contains a null element - */ - @Override - @Deprecated - public boolean addAll(int index, Collection c) { - if(c instanceof COLLECTION) return addAll(index, (COLLECTION KEY_GENERIC_TYPE)c); - int add = c.size(); - if(add <= 0) return false; -#if !TYPE_OBJECT - if(c.contains(null)) throw new NullPointerException(); -#endif - ReentrantLock lock = this.lock; - lock.lock(); - try { - KEY_TYPE[] data = this.data; - int size = data.length; - if(index < 0 || index > size) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); - KEY_TYPE[] newElements; - if(index == size) { - newElements = Arrays.copyOf(data, size+add); - } - else { - newElements = NEW_KEY_ARRAY(size+add); - System.arraycopy(data, 0, newElements, 0, index); - System.arraycopy(data, index, newElements, index + add, size - index); - } - Iterator iter = c.iterator(); - while(add-- != 0) newElements[index++] = OBJ_TO_KEY(iter.next()); - this.data = newElements; - } - finally { - lock.unlock(); - } - return true; - } - - /** - * Appends the specified elements to the index of the list. - * This function may delegate to more appropriate function if necessary - * @param index the index where to append the elements to - * @param c the elements to append to the list - * @throws IndexOutOfBoundsException if index is outside of the lists range - */ - @Override - public boolean addAll(int index, COLLECTION KEY_GENERIC_TYPE c) { - if(c instanceof LIST) return addAll(index, (LIST KEY_GENERIC_TYPE)c); - int add = c.size(); - if(add <= 0) return false; - ReentrantLock lock = this.lock; - lock.lock(); - try { - KEY_TYPE[] data = this.data; - int size = data.length; - if(index < 0 || index > size) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); - KEY_TYPE[] newElements; - if(index == size) { - newElements = Arrays.copyOf(data, size+add); - } - else { - newElements = NEW_KEY_ARRAY(size+add); - System.arraycopy(data, 0, newElements, 0, index); - System.arraycopy(data, index, newElements, index + add, size - index); - } - ITERATOR KEY_GENERIC_TYPE iter = c.iterator(); - while(add-- != 0) newElements[index++] = iter.NEXT(); - this.data = newElements; - } - finally { - lock.unlock(); - } - return true; - } - - /** - * Appends the specified elements to the index of the list. - * @param index the index where to append the elements to - * @param c the elements to append to the list - * @throws IndexOutOfBoundsException if index is outside of the lists range - */ - @Override - public boolean addAll(int index, LIST KEY_GENERIC_TYPE c) { - int add = c.size(); - if(add <= 0) return false; - ReentrantLock lock = this.lock; - lock.lock(); - try { - KEY_TYPE[] data = this.data; - int size = data.length; - if(index < 0 || index > size) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); - KEY_TYPE[] newElements; - if(index == size) { - newElements = Arrays.copyOf(data, size+add); - } - else { - newElements = NEW_KEY_ARRAY(size+add); - System.arraycopy(data, 0, newElements, 0, index); - System.arraycopy(data, index, newElements, index + add, size - index); - } - c.getElements(0, newElements, index, c.size()); - this.data = newElements; - } - finally { - lock.unlock(); - } - return true; - } - - @Override - public boolean addAll(KEY_TYPE[] e, int offset, int length) { - if(length <= 0) return false; - SanityChecks.checkArrayCapacity(e.length, offset, length); - ReentrantLock lock = this.lock; - lock.lock(); - try { - int size = data.length; - KEY_TYPE[] newElements = Arrays.copyOf(data, size+length); - System.arraycopy(e, offset, newElements, size, length); - data = newElements; - } - finally { - lock.unlock(); - } - return true; - } - - /** - * Appends the specified array elements to the index of the list. - * @param from the index where to append the elements to - * @param a the elements to append to the list - * @param offset where to start ino the array - * @param length the amount of elements to insert - * @throws IndexOutOfBoundsException if index is outside of the lists range - */ - @Override - public void addElements(int from, KEY_TYPE[] a, int offset, int length) { - if(length <= 0) return; - ReentrantLock lock = this.lock; - lock.lock(); - try { - KEY_TYPE[] data = this.data; - int size = data.length; - if(from < 0 || from > size) throw new IndexOutOfBoundsException("Index: " + from + ", Size: " + size); - SanityChecks.checkArrayCapacity(a.length, offset, length); - KEY_TYPE[] newElements; - if(from == size) { - newElements = Arrays.copyOf(data, size+length); - } - else { - newElements = NEW_KEY_ARRAY(size+length); - System.arraycopy(data, 0, newElements, 0, from); - System.arraycopy(data, from, newElements, from + length, size - from); - } - System.arraycopy(a, offset, newElements, from, length); - this.data = newElements; - } - finally { - lock.unlock(); - } - } - - /** - * A function to fast fetch elements from the list - * @param from index where the list should be fetching elements from - * @param a the array where the values should be inserted to - * @param offset the startIndex of where the array should be written to - * @param length the number of elements the values should be fetched from - * @return the inputArray - * @throws NullPointerException if the array is null - * @throws IndexOutOfBoundsException if from is outside of the lists range - * @throws IllegalStateException if offset or length are smaller then 0 or exceed the array length - */ - @Override - public KEY_TYPE[] getElements(int from, KEY_TYPE[] a, int offset, int length) { - KEY_TYPE[] data = this.data; - SanityChecks.checkArrayCapacity(data.length, from, length); - SanityChecks.checkArrayCapacity(a.length, offset, length); - System.arraycopy(data, from, a, offset, length); - return a; - } - - /** - * a function to fast remove elements from the list. - * @param from the start index of where the elements should be removed from (inclusive) - * @param to the end index of where the elements should be removed to (exclusive) - */ - @Override - public void removeElements(int from, int to) { - checkRange(from); - checkAddRange(to); - int length = to - from; - if(length <= 0) return; - ReentrantLock lock = this.lock; - lock.lock(); - try { - KEY_TYPE[] data = this.data; - if(to == data.length) this.data = Arrays.copyOf(data, data.length - length); - else { - int size = data.length-length; - KEY_TYPE[] newElements = NEW_KEY_ARRAY(size); - System.arraycopy(data, 0, newElements, 0, from); - System.arraycopy(data, to, newElements, from, data.length - to); - this.data = newElements; - } - } - finally { - lock.unlock(); - } - } - -#if TYPE_OBJECT - /** - * A function to fast extract elements out of the list, this removes the elements that were fetched. - * @param from the start index of where the elements should be fetched from (inclusive) - * @param to the end index of where the elements should be fetched to (exclusive) - * @param type the type of the OutputArray - * @return a array of the elements that were fetched - */ - @Override - public K[] extractElements(int from, int to, Class type) { - checkRange(from); - checkAddRange(to); - int length = to - from; - if(length <= 0) return ARRAYS.newArray(type, 0); - K[] a = ARRAYS.newArray(type, length); - ReentrantLock lock = this.lock; - lock.lock(); - try { - KEY_TYPE[] data = this.data; - System.arraycopy(data, from, a, 0, length); - if(to == data.length) this.data = Arrays.copyOf(data, data.length - length); - else { - int size = data.length; - KEY_TYPE[] newElements = NEW_KEY_ARRAY(size-length); - if(from != 0) System.arraycopy(data, 0, newElements, 0, from); - System.arraycopy(data, to, newElements, from, size - to); - this.data = newElements; - } - return a; - } - finally { - lock.unlock(); - } - } - -#else - /** - * A function to fast extract elements out of the list, this removes the elements that were fetched. - * @param from the start index of where the elements should be fetched from (inclusive) - * @param to the end index of where the elements should be fetched to (exclusive) - * @return a array of the elements that were fetched - */ - @Override - public KEY_TYPE[] extractElements(int from, int to) { - checkRange(from); - checkAddRange(to); - int length = to - from; - if(length <= 0) return EMPTY_KEY_ARRAY; - ReentrantLock lock = this.lock; - lock.lock(); - try { - KEY_TYPE[] data = this.data; - KEY_TYPE[] a = NEW_KEY_ARRAY(length); - System.arraycopy(data, from, a, 0, length); - if(to == data.length) this.data = Arrays.copyOf(data, data.length - length); - else { - int size = data.length; - KEY_TYPE[] newElements = NEW_KEY_ARRAY(size-length); - if(from != 0) System.arraycopy(data, 0, newElements, 0, from); - System.arraycopy(data, to, newElements, from, size - to); - this.data = newElements; - } - return a; - } - finally { - lock.unlock(); - } - } - -#endif -#if PRIMITIVES - @Override - public void fillBuffer(JAVA_BUFFER buffer) { - buffer.put(data, 0, data.length); - } - -#endif - /** - * A function to find if the Element is present in this list. - * @param o the element that is searched for - * @return if the element was found. - */ - @Override - @Deprecated - public boolean contains(Object o) { - return indexOf(o) != -1; - } - - /** - * A function to find the index of a given element - * @param o the element that is searched for - * @return the index of the element if found. (if not found then -1) - */ - @Override - @Deprecated - public int indexOf(Object o) { - KEY_TYPE[] data = this.data; -#if TYPE_OBJECT - if(o == null) { - for(int i = 0,m=data.length;i=0;i--) - if(data[i] == null) return i; - return -1; - } -#else - if(o == null) return -1; -#endif - for(int i = data.length - 1;i>=0;i--) { - if(Objects.equals(o, KEY_TO_OBJ(data[i]))) return i; - } - return -1; - } - -#if TYPE_OBJECT - /** - * Sorts the elements specified by the Natural order either by using the Comparator or the elements - * @param c the sorter of the elements, can be null - * @see java.util.List#sort(Comparator) - */ - @Override - public void sort(Comparator c) { - ReentrantLock lock = this.lock; - lock.lock(); - try { - KEY_TYPE[] newData = Arrays.copyOf(data, data.length); - if(c != null) ARRAYS.stableSort(newData, newData.length, c); - else ARRAYS.stableSort(newData, newData.length); - data = newData; - } - finally { - lock.unlock(); - } - } - - /** - * Sorts the elements specified by the Natural order either by using the Comparator or the elements using a unstable sort - * @param c the sorter of the elements, can be null - * @see java.util.List#sort(Comparator) - */ - @Override - public void unstableSort(Comparator c) { - ReentrantLock lock = this.lock; - lock.lock(); - try { - KEY_TYPE[] newData = Arrays.copyOf(data, data.length); - if(c != null) ARRAYS.unstableSort(newData, newData.length, c); - else ARRAYS.unstableSort(newData, newData.length); - data = newData; - } - finally { - lock.unlock(); - } - } - -#else - /** - * A Type Specific implementation of the Collection#contains function. - * @param e the element that is searched for. - * @return if the element was found - */ - @Override - public boolean contains(KEY_TYPE e) { - return indexOf(e) != -1; - } - - /** - * A Type-Specific function to find the index of a given element - * @param e the element that is searched for - * @return the index of the element if found. (if not found then -1) - */ - @Override - public int indexOf(KEY_TYPE e) { - KEY_TYPE[] data = this.data; - for(int i = 0,m=data.length;i=0;i--) { - if(KEY_EQUALS(data[i], e)) return i; - } - return -1; - } - - /** - * Sorts the elements specified by the Natural order either by using the Comparator or the elements - * @param c the sorter of the elements, can be null - * @see java.util.List#sort(java.util.Comparator) - * @see ARRAYS#stableSort(KEY_TYPE[], COMPARATOR) - */ - @Override - public void sort(COMPARATOR c) { - ReentrantLock lock = this.lock; - lock.lock(); - try { - KEY_TYPE[] newData = Arrays.copyOf(data, data.length); - if(c != null) ARRAYS.stableSort(newData, newData.length, c); - else ARRAYS.stableSort(newData, newData.length); - data = newData; - } - finally { - lock.unlock(); - } - } - - /** - * Sorts the elements specified by the Natural order either by using the Comparator or the elements using a unstable sort - * @param c the sorter of the elements, can be null - * @see java.util.List#sort(java.util.Comparator) - * @see ARRAYS#unstableSort(KEY_TYPE[], COMPARATOR) - */ - @Override - public void unstableSort(COMPARATOR c) { - ReentrantLock lock = this.lock; - lock.lock(); - try { - KEY_TYPE[] newData = Arrays.copyOf(data, data.length); - if(c != null) ARRAYS.unstableSort(newData, newData.length, c); - else ARRAYS.unstableSort(newData, newData.length); - data = newData; - } - finally { - lock.unlock(); - } - } - -#endif - /** - * A Type-Specific get function to reduce (un)boxing - * @param index the index of the element to fetch - * @return the value of the requested index - * @throws IndexOutOfBoundsException if the index is out of range - */ - @Override - public KEY_TYPE GET_KEY(int index) { - checkRange(index); - return data[index]; - } - - /** - * Provides the Selected Object from the stack. - * Top to bottom - * @param index of the element that should be provided - * @return the element that was requested - * @throws ArrayIndexOutOfBoundsException if the index is out of bounds - * @see speiger.src.collections.utils.Stack#peek(int) - */ - @Override - public KEY_TYPE peek(int index) { - checkRange((size() - 1) - index); - return data[(size() - 1) - index]; - } - - @Override - public LIST_ITERATOR KEY_GENERIC_TYPE listIterator(int index) { - if(index < 0 || index > size()) throw new IndexOutOfBoundsException(); - return new COWIteratorBRACES(data, index); - } - - @Override - public LIST KEY_GENERIC_TYPE subList(int fromIndex, int toIndex) { - SanityChecks.checkArrayCapacity(data.length, fromIndex, toIndex-fromIndex); - return new COWSubListBRACES(this, lock, this::setArray, this::getArray, 0, fromIndex, toIndex); - } - - /** - * A Type Specific foreach function that reduces (un)boxing - * - * @implSpec - *

The default implementation behaves as if: - *

{@code
-	 * 	for(int i = 0,m=data.length;i
-	 *
-	 * @param action The action to be performed for each element
-	 * @throws NullPointerException if the specified action is null
-	 * @see Iterable#forEach(java.util.function.Consumer)
-	 */
-	@Override
-	public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
-		Objects.requireNonNull(action);
-		KEY_TYPE[] data = this.data;
-		for(int i = 0,m=data.length;i void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) {
-		Objects.requireNonNull(action);
-		KEY_TYPE[] data = this.data;
-		for(int i = 0,m=data.length;i KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) {
-		Objects.requireNonNull(operator);
-		KEY_TYPE[] data = this.data;
-		KEY_SPECIAL_TYPE state = identity;
-		for(int i = 0,m=data.length;i o) {
-#if PRIMITIVES
-		Objects.requireNonNull(o);
-#if TYPE_BYTE || TYPE_SHORT || TYPE_CHAR || TYPE_FLOAT
-		REPLACE(T -> OBJ_TO_KEY(o.apply(KEY_TO_OBJ(SanityChecks.SANITY_CAST(T)))));
-#else
-		REPLACE(T -> OBJ_TO_KEY(o.apply(KEY_TO_OBJ(T))));
-#endif
-#else
-		Objects.requireNonNull(o);
-		ReentrantLock lock = this.lock;
-		lock.lock();
-		try {
-			KEY_TYPE[] newData = Arrays.copyOf(data, data.length);
-			for(int i = 0,m=newData.length;i c) {
-		if(c.isEmpty()) return false;
-		ReentrantLock lock = this.lock;
-		lock.lock();
-		try {
-			KEY_TYPE[] data = this.data;
-			KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length);
-			int j = 0;
-			for(int i= 0,m=data.length;i c) {
-		ReentrantLock lock = this.lock;
-		lock.lock();
-		try {
-			KEY_TYPE[] data = this.data;
-			if(c.isEmpty()) {
-				if(data.length > 0) {
-					this.data = EMPTY_KEY_ARRAY;
-					return true;
-				}
-				return false;
-			}
-			KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length);
-			int j = 0;
-			for(int i= 0,m=data.length;i filter) {
-		Objects.requireNonNull(filter);
-		ReentrantLock lock = this.lock;
-		lock.lock();
-		try {
-			KEY_TYPE[] data = this.data;
-			KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length);
-			int j = 0;
-			for(int i= 0,m=data.length;i 0) {
-					this.data = EMPTY_KEY_ARRAY;
-					return true;
-				}
-				return false;
-			}
-			KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length);
-			int j = 0;
-			for(int i= 0,m=data.length;i 0) {
-					forEach(r);
-					this.data = EMPTY_KEY_ARRAY;
-					return true;
-				}
-				return false;
-			}
-			KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length);
-			int j = 0;
-			for(int i= 0,m=data.length;i E[] toArray(E[] a) {
-		KEY_TYPE[] data = this.data;
-		int size = data.length;
-		if(a == null) a = (E[])new Object[size];
-		else if(a.length < size) a = (E[])ObjectArrays.newArray(a.getClass().getComponentType(), size);
-#if TYPE_OBJECT
-        System.arraycopy(data, 0, a, 0, size);
-#else
-		for(int i = 0;i size) a[size] = null;
-		return a;
-	}
-	
-#if !TYPE_OBJECT
-	@Override
-	public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) {
-		KEY_TYPE[] data = this.data;
-		int size = data.length;
-		if(a.length < size) a = new KEY_TYPE[size];
-		System.arraycopy(data, 0, a, 0, size);
-		if (a.length > size) a[size] = EMPTY_KEY_VALUE;
-		return a;
-	}
-	
-#endif
-	
-	/**
-	 * A function to return the size of the list
-	 * @return the size of elements in the list
-	 */
-	@Override
-	public int size() {
-		return data.length;
-	}
-	
-	/**
-	 * A function to ensure the elements are within the requested size.
-	 * If smaller then the stored elements they get removed as needed.
-	 * If bigger it is ensured that enough room is provided depending on the implementation
-	 * @param size the requested amount of elements/room for elements
-	 */
-	@Override
-	public void size(int size) {
-		if(size == data.length || size < 0) return;
-		ReentrantLock lock = this.lock;
-		lock.lock();
-		try {
-			data = Arrays.copyOf(data, size);
-		}
-		finally {
-			lock.unlock();
-		}
-	}
-	
-	/**
-	 * A function to clear all elements in the list.
-	 */
-	@Override
-	public void clear() {
-		ReentrantLock lock = this.lock;
-		lock.lock();
-		try {
-			data = EMPTY_KEY_ARRAY;
-		}
-		finally {
-			lock.unlock();
-		}
-	}
-	
-	/**
-	 * Trims the original collection down to the size of the current elements or the requested size depending which is bigger
-	 * @param size the requested trim size.
-	 */
-	@Override
-	public boolean trim(int size) {
-		return false;
-	}
-	
-	/**
-	 * Trims the collection down to the requested size and clears all elements while doing so
-	 * @param size the amount of elements that should be allowed
-	 * @note this will enforce minimum size of the collection itself
-	 */
-	@Override
-	public void clearAndTrim(int size) {
-		ReentrantLock lock = this.lock;
-		lock.lock();
-		try {
-			data = EMPTY_KEY_ARRAY;
-		}
-		finally {
-			lock.unlock();
-		}
-	}
-	
-	@Override
-	public COPY_ON_WRITE_LIST KEY_GENERIC_TYPE copy() {
-		COPY_ON_WRITE_LIST KEY_GENERIC_TYPE list = new COPY_ON_WRITE_LISTBRACES();
-		list.data = Arrays.copyOf(data, data.length);
-		return list;
-	}
-	
-	protected void checkRange(int index) {
-		if (index < 0 || index >= data.length)
-			throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + data.length);
-	}
-	
-	protected void checkAddRange(int index) {
-		if (index < 0 || index > data.length)
-			throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + data.length);
-	}
-
-#if SPLIT_ITERATOR_FEATURE
-#if PRIMITIVES && STREAM_FEATURE
-	/**
-	 * Returns a Java-Type-Specific Stream to reduce boxing/unboxing.
-	 * @return a Stream of the closest java type
-	 * @note characteristics are ordered, sized, subsized
-	 */
-	@Override
-	public JAVA_STREAM primitiveStream() { return StreamSupport.NEW_STREAM(SPLIT_ITERATORS.createArrayJavaSplititerator(data, data.length, 16464), false); }
-	
-#endif
-	/**
-	 * A Type Specific Type Splititerator to reduce boxing/unboxing
-	 * @return type specific splititerator
-	 * @note characteristics are ordered, sized, subsized
-	 */
-	@Override
-	public SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createArraySplititerator(data, data.length, 16464); }
-	
-#endif
-	static final class COWIterator KEY_GENERIC_TYPE implements LIST_ITERATOR KEY_GENERIC_TYPE
-	{
-		KEY_TYPE[] data;
-		int index;
-		
-		public COWIterator(KEY_TYPE[] data, int index) {
-			this.data = data;
-			this.index = index;
-		}
-		
-		@Override
-		public boolean hasNext() {
-			return index < data.length;
-		}
-		
-		@Override
-		public KEY_TYPE NEXT() {
-			if(!hasNext()) throw new NoSuchElementException();
-			return data[index++];
-		}
-		
-		@Override
-		public boolean hasPrevious() {
-			return index > 0;
-		}
-		
-		@Override
-		public KEY_TYPE PREVIOUS() {
-			if(!hasPrevious()) throw new NoSuchElementException();
-			return data[--index];
-		}
-		
-		@Override
-		public int nextIndex() {
-			return index;
-		}
-		
-		@Override
-		public int previousIndex() {
-			return index-1;
-		}
-		
-		@Override
-		public void remove() { throw new UnsupportedOperationException(); }
-		@Override
-		public void set(KEY_TYPE e) { throw new UnsupportedOperationException(); }
-		@Override
-		public void add(KEY_TYPE e) { throw new UnsupportedOperationException(); }
-		
-		@Override
-		public int skip(int amount) {
-			if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
-			int steps = Math.min(amount, data.length - index);
-			index += steps;
-			return steps;
-		}
-		
-		@Override
-		public int back(int amount) {
-			if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
-			int steps = Math.min(amount, index);
-			index -= steps;
-			return steps;
-		}
-	}
-	
-	private static class COWSubList KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
-	{
-		final ABSTRACT_LIST KEY_GENERIC_TYPE list;
-		final ReentrantLock lock;
-		final Consumer setter;
-		final Supplier getter;
-		final int parentOffset;
-		final int offset;
-		int size;
-		
-		public COWSubList(ABSTRACT_LIST KEY_GENERIC_TYPE list, ReentrantLock lock, Consumer setter, Supplier getter, int offset, int from, int to) {
-			this.list = list;
-			this.lock = lock;
-			this.setter = setter;
-			this.getter = getter;
-			this.parentOffset = from;
-			this.offset = offset + from;
-			this.size = to - from;
-		}
-		
-		@Override
-		public void add(int index, KEY_TYPE element) {
-			lock.lock();
-			try {
-				checkAddSubRange(index);
-				list.add(parentOffset+index, element);
-				size++;				
-			}
-			finally {
-				lock.unlock();
-			}
-		}
-		
-		@Override
-		public boolean addAll(int index, Collection c) {
-			int add = c.size();
-			if(add <= 0) return false;
-			lock.lock();
-			try {
-				checkAddSubRange(index);
-				list.addAll(parentOffset+index, c);
-				this.size += add;
-			}
-			finally {
-				lock.unlock();
-			}
-			return true;
-		}
-		
-		@Override
-		public boolean addAll(int index, COLLECTION KEY_GENERIC_TYPE c) {
-			int add = c.size();
-			if(add <= 0) return false;
-			lock.lock();
-			try {
-				checkAddSubRange(index);
-				list.addAll(parentOffset+index, c);
-				this.size += add;
-			}
-			finally {
-				lock.unlock();
-			}
-			return true;
-		}
-
-		@Override
-		public boolean addAll(int index, LIST KEY_GENERIC_TYPE c) {
-			int add = c.size();
-			if(add <= 0) return false;
-			lock.lock();
-			try {
-				checkAddSubRange(index);
-				list.addAll(parentOffset+index, c);
-				this.size += add;
-			}
-			finally {
-				lock.unlock();
-			}
-			return true;
-		}
-		
-		@Override
-		public void addElements(int from, KEY_TYPE[] a, int offset, int length) {
-			if(length <= 0) return;
-			lock.lock();
-			try {
-				checkAddSubRange(from);
-				list.addElements(parentOffset+from, a, offset, length);
-				this.size += length;
-			}
-			finally {
-				lock.unlock();
-			}
-		}
-		
-		@Override
-		public KEY_TYPE[] getElements(int from, KEY_TYPE[] a, int offset, int length) {
-			SanityChecks.checkArrayCapacity(size, from, length);
-			SanityChecks.checkArrayCapacity(a.length, offset, length);
-			return list.getElements(from+parentOffset, a, offset, length);
-		}
-		
-		@Override
-		public void removeElements(int from, int to) {
-			if(to-from <= 0) return;
-			lock.lock();
-			try {
-				checkSubRange(from);
-				checkAddSubRange(to);
-				list.removeElements(from+parentOffset, to+parentOffset);
-				size -= to - from;
-			}
-			finally {
-				lock.unlock();
-			}
-		}
-		
-#if TYPE_OBJECT
-		@Override
-		public  K[] extractElements(int from, int to, Class type) {
-			lock.lock();
-			try {
-				checkSubRange(from);
-				checkAddSubRange(to);
-				K[] result = list.extractElements(from+parentOffset, to+parentOffset, type);
-				size -= result.length;
-				return result;
-			}
-			finally {
-				lock.unlock();
-			}
-		}
-
-#else
-		@Override
-		public KEY_TYPE[] extractElements(int from, int to) {
-			lock.lock();
-			try {
-				checkSubRange(from);
-				checkAddSubRange(to);
-				KEY_TYPE[] result = list.extractElements(from+parentOffset, to+parentOffset);
-				size -= result.length;
-				return result;
-			}
-			finally {
-				lock.unlock();
-			}
-		}
-		
-#endif
-		@Override
-		public KEY_TYPE GET_KEY(int index) {
-			checkSubRange(index);
-			return list.GET_KEY(parentOffset+index);
-		}
-
-		@Override
-		public KEY_TYPE set(int index, KEY_TYPE element) {
-			lock.lock();
-			try {
-				checkSubRange(index);
-				return list.set(parentOffset+index, element);
-			}
-			finally {
-				lock.unlock();
-			}
-		}
-		
-		@Override
-		public KEY_TYPE swapRemove(int index) {
-			if(index < 0 || index >= size) throw new IndexOutOfBoundsException();
-			ReentrantLock lock = this.lock;
-			lock.lock();
-			try {
-				KEY_TYPE[] data = getter.get();
-				KEY_TYPE result = data[offset+index];
-				KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length-1);
-				int end = offset+size-1;
-				System.arraycopy(data, 0, newElements, 0, end);
-				if(end != newElements.length) System.arraycopy(data, end+1, newElements, end, data.length-end-1);
-				if(index+offset != end) newElements[index+offset] = data[end];
-				setter.accept(newElements);
-				size--;
-				return result;
-			}
-			finally {
-				lock.unlock();
-			}
-		}
-		
-		@Override
-		public KEY_TYPE REMOVE(int index) {
-			lock.lock();
-			try {
-				checkSubRange(index);
-				KEY_TYPE result = list.REMOVE(index+parentOffset);
-				size--;
-				return result;
-			}
-			finally {
-				lock.unlock();
-			}
-		}
-		
-#if !TYPE_OBJECT
-		@Override
-		public boolean REMOVE_KEY(KEY_TYPE type) {
-			int index = indexOf(type);
-			if(index == -1) return false;
-			REMOVE(index);
-			return true;
-		}
-		
-#else
-		@Override
-		public boolean remove(Object type) {
-			int index = indexOf(type);
-			if(index == -1) return false;
-			REMOVE(index);
-			return true;
-		}
-		
-#endif
-		
-#if TYPE_OBJECT
-		@Override
-		public void sort(Comparator c) {
-			ReentrantLock lock = this.lock;
-			lock.lock();
-			try {
-				KEY_TYPE[] data = getter.get();
-				KEY_TYPE[] newData = Arrays.copyOf(data, data.length);
-				if(c != null) ARRAYS.stableSort(newData, offset, offset+size, c);
-				else ARRAYS.stableSort(newData, offset, offset+size);
-				setter.accept(newData);
-			}
-			finally {
-				lock.unlock();
-			}
-		}
-		
-		@Override
-		public void unstableSort(Comparator c) {
-			ReentrantLock lock = this.lock;
-			lock.lock();
-			try {
-				KEY_TYPE[] data = getter.get();
-				KEY_TYPE[] newData = Arrays.copyOf(data, data.length);
-				if(c != null) ARRAYS.unstableSort(newData, offset, offset+size, c);
-				else ARRAYS.unstableSort(newData, offset, offset+size);
-				setter.accept(newData);
-			}
-			finally {
-				lock.unlock();
-			}
-		}
-		
-#else
-		@Override
-		public void sort(COMPARATOR c) {
-			ReentrantLock lock = this.lock;
-			lock.lock();
-			try {
-				KEY_TYPE[] data = getter.get();
-				KEY_TYPE[] newData = Arrays.copyOf(data, data.length);
-				if(c != null) ARRAYS.stableSort(newData, offset, offset+size, c);
-				else ARRAYS.stableSort(newData, offset, offset+size);
-				setter.accept(newData);
-			}
-			finally {
-				lock.unlock();
-			}
-		}
-		
-		@Override
-		public void unstableSort(COMPARATOR c) {
-			ReentrantLock lock = this.lock;
-			lock.lock();
-			try {
-				KEY_TYPE[] data = getter.get();
-				KEY_TYPE[] newData = Arrays.copyOf(data, data.length);
-				if(c != null) ARRAYS.unstableSort(newData, offset, offset+size, c);
-				else ARRAYS.unstableSort(newData, offset, offset+size);
-				setter.accept(newData);
-			}
-			finally {
-				lock.unlock();
-			}	
-		}
-		
-#endif
-		
-		@Override
-		@Deprecated
-		public boolean removeAll(Collection c) {
-			if(c.isEmpty()) return false;
-			ReentrantLock lock = this.lock;
-			lock.lock();
-			try {
-				KEY_TYPE[] data = getter.get();
-				KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length);
-				int j = 0;
-				for(int i= 0,m=data.length;i= offset+size) newElements[j++] = data[i];
-					else if(!c.contains(KEY_TO_OBJ(data[i]))) newElements[j++] = data[i];
-				}
-				if(data.length != j) {
-					setter.accept(Arrays.copyOf(newElements, j));
-					size -= data.length - j;
-					return true;
-				}
-				return false;
-			}
-			finally {
-				lock.unlock();
-			}
-		}
-		
-		@Override
-		@Deprecated
-		public boolean retainAll(Collection c) {
-			ReentrantLock lock = this.lock;
-			lock.lock();
-			try {
-				KEY_TYPE[] data = getter.get();
-				if(c.isEmpty()) {
-					if(size > 0) {
-						clear();
-						return true;
-					}
-					return false;
-				}
-				KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length);
-				int j = 0;
-				for(int i= 0,m=data.length;i= offset+size) newElements[j++] = data[i];
-					else if(c.contains(KEY_TO_OBJ(data[i]))) newElements[j++] = data[i];
-				}
-				if(data.length != j) {
-					setter.accept(Arrays.copyOf(newElements, j));
-					size -= data.length - j;
-					return true;
-				}
-				return false;
-			}
-			finally {
-				lock.unlock();
-			}
-		}
-		
-		@Override
-		@Deprecated
-		public boolean removeIf(Predicate filter) {
-			Objects.requireNonNull(filter);
-			ReentrantLock lock = this.lock;
-			lock.lock();
-			try {
-				KEY_TYPE[] data = getter.get();
-				KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length);
-				int j = 0;
-				for(int i= 0,m=data.length;i= offset+size) newElements[j++] = data[i];
-					else if(!filter.test(KEY_TO_OBJ(data[i]))) newElements[j++] = data[i];
-				}
-				if(data.length != j) {
-					setter.accept(Arrays.copyOf(newElements, j));
-					size -= data.length - j;
-					return true;
-				}
-				return false;
-			}
-			finally {
-				lock.unlock();
-			}
-		}
-		
-		@Override
-		public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) {
-			if(c.isEmpty()) return false;
-			ReentrantLock lock = this.lock;
-			lock.lock();
-			try {
-				KEY_TYPE[] data = getter.get();
-				KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length);
-				int j = 0;
-				for(int i= 0,m=data.length;i= offset+size) newElements[j++] = data[i];
-					else if(!c.contains(data[i])) newElements[j++] = data[i];
-				}
-				if(data.length != j) {
-					setter.accept(Arrays.copyOf(newElements, j));
-					size -= data.length - j;
-					return true;
-				}
-				return false;
-			}
-			finally {
-				lock.unlock();
-			}
-		}
-		
-		@Override
-		public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) {
-			if(c.isEmpty()) return false;
-			ReentrantLock lock = this.lock;
-			lock.lock();
-			try {
-				KEY_TYPE[] data = getter.get();
-				KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length);
-				int j = 0;
-				for(int i= 0,m=data.length;i= offset+size) newElements[j++] = data[i];
-					else if(!c.contains(data[i])) newElements[j++] = data[i];
-					else r.accept(data[i]);
-				}
-				if(data.length != j) {
-					setter.accept(Arrays.copyOf(newElements, j));
-					size -= data.length - j;
-					return true;
-				}
-				return false;
-			}
-			finally {
-				lock.unlock();
-			}
-		}
-		
-		@Override
-		public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) {
-			ReentrantLock lock = this.lock;
-			lock.lock();
-			try {
-				KEY_TYPE[] data = getter.get();
-				if(c.isEmpty()) {
-					if(size > 0) {
-						clear();
-						return true;
-					}
-					return false;
-				}
-				KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length);
-				int j = 0;
-				for(int i= 0,m=data.length;i= offset+size) newElements[j++] = data[i];
-					else if(c.contains(data[i])) newElements[j++] = data[i];
-				}
-				if(data.length != j) {
-					setter.accept(Arrays.copyOf(newElements, j));;
-					size -= data.length - j;
-					return true;
-				}
-				return false;
-			}
-			finally {
-				lock.unlock();
-			}
-		}
-		
-		@Override
-		public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) {
-			ReentrantLock lock = this.lock;
-			lock.lock();
-			try {
-				KEY_TYPE[] data = getter.get();
-				if(c.isEmpty()) {
-					if(size > 0) {
-						forEach(r);
-						clear();
-						return true;
-					}
-					return false;
-				}
-				KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length);
-				int j = 0;
-				for(int i= 0,m=data.length;i= offset+size) newElements[j++] = data[i];
-					else if(c.contains(data[i])) newElements[j++] = data[i];
-					else r.accept(data[i]);
-				}
-				if(data.length != j) {
-					setter.accept(Arrays.copyOf(newElements, j));
-					size -= data.length - j;
-					return true;
-				}
-				return false;
-			}
-			finally {
-				lock.unlock();
-			}
-		}
-		
-#if PRIMITIVES
-		@Override
-		public boolean remIf(JAVA_PREDICATE filter) {
-			Objects.requireNonNull(filter);
-			ReentrantLock lock = this.lock;
-			lock.lock();
-			try {
-				KEY_TYPE[] data = getter.get();
-				KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length);
-				int j = 0;
-				for(int i=0,m=data.length;i= offset+size) newElements[j++] = data[i];
-					else if(!filter.test(data[i])) newElements[j++] = data[i];
-				}
-				if(data.length != j) {
-					setter.accept(Arrays.copyOf(newElements, j));
-					size -= data.length - j;
-					return true;
-				}
-				return false;
-			}
-			finally {
-				lock.unlock();
-			}
-		}
-		
-#endif
-		
-		@Override
-		@Primitive
-		public void replaceAll(UnaryOperator o) {
-#if PRIMITIVES
-			Objects.requireNonNull(o);
-#if TYPE_BYTE || TYPE_SHORT || TYPE_CHAR || TYPE_FLOAT
-			REPLACE(T -> OBJ_TO_KEY(o.apply(KEY_TO_OBJ(SanityChecks.SANITY_CAST(T)))));
-#else
-			REPLACE(T -> OBJ_TO_KEY(o.apply(KEY_TO_OBJ(T))));
-#endif
-#else
-			Objects.requireNonNull(o);
-			ReentrantLock lock = this.lock;
-			lock.lock();
-			try {
-				KEY_TYPE[] data = getter.get();
-				KEY_TYPE[] newData = Arrays.copyOf(data, data.length);
-				for(int i = 0,m=size;i size()) throw new IndexOutOfBoundsException();
-			return new COWSubListIteratorBRACES(this, index);
-		}
-		
-		@Override
-		public LIST KEY_GENERIC_TYPE subList(int fromIndex, int toIndex) {
-			SanityChecks.checkArrayCapacity(size, fromIndex, toIndex-fromIndex);
-			return new COWSubListBRACES(this, lock, setter, getter, offset, fromIndex, toIndex);
-		}
-		
-		protected void checkSubRange(int index) {
-			if (index < 0 || index >= size)
-				throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
-		}
-		
-		protected void checkAddSubRange(int index) {
-			if (index < 0 || index > size)
-				throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
-		}
-	}
-	
-	private static class COWSubListIterator KEY_GENERIC_TYPE implements LIST_ITERATOR KEY_GENERIC_TYPE
-	{
-		ABSTRACT_LIST KEY_GENERIC_TYPE list;
-		int index;
-		
-		COWSubListIterator(ABSTRACT_LIST KEY_GENERIC_TYPE list, int index) {
-			this.list = list;
-			this.index = index;
-		}
-		
-		@Override
-		public boolean hasNext() {
-			return index < list.size();
-		}
-		
-		@Override
-		public KEY_TYPE NEXT() {
-			if(!hasNext()) throw new NoSuchElementException();
-			return list.GET_KEY(index++);
-		}
-		
-		@Override
-		public boolean hasPrevious() {
-			return index > 0;
-		}
-		
-		@Override
-		public KEY_TYPE PREVIOUS() {
-			if(!hasPrevious()) throw new NoSuchElementException();
-			return list.GET_KEY(--index);
-		}
-		
-		@Override
-		public int nextIndex() {
-			return index;
-		}
-		
-		@Override
-		public int previousIndex() {
-			return index-1;
-		}
-		
-		@Override
-		public void remove() { throw new UnsupportedOperationException(); }
-		
-		@Override
-		public void set(KEY_TYPE e) { throw new UnsupportedOperationException(); }
-		
-		@Override
-		public void add(KEY_TYPE e) { throw new UnsupportedOperationException(); }
-		
-		@Override
-		public int skip(int amount) {
-			if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
-			int steps = Math.min(amount, list.size() - index);
-			index += steps;
-			return steps;
-		}
-		
-		@Override
-		public int back(int amount) {
-			if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
-			int steps = Math.min(amount, index);
-			index -= steps;
-			return steps;
-		}
-	}
+package speiger.src.collections.PACKAGE.lists;
+
+import java.util.Arrays;
+#if TYPE_OBJECT
+import java.util.Comparator;
+#endif
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+#if TYPE_OBJECT
+import java.util.function.BiFunction;
+#endif
+#if !TYPE_OBJECT && JDK_FUNCTION
+import java.util.function.PREDICATE;
+#endif
+import java.util.function.Predicate;
+import java.util.function.UnaryOperator;
+#if PRIMITIVES
+#if !JDK_FUNCTION
+import java.util.function.JAVA_PREDICATE;
+#endif
+import java.util.function.JAVA_UNARY_OPERATOR;
+import java.nio.JAVA_BUFFER;
+#endif
+
+import speiger.src.collections.PACKAGE.collections.COLLECTION;
+#if !TYPE_OBJECT
+import speiger.src.collections.PACKAGE.collections.STACK;
+#endif
+import speiger.src.collections.PACKAGE.collections.ITERATOR;
+#if !TYPE_OBJECT
+import speiger.src.collections.PACKAGE.functions.COMPARATOR;
+import speiger.src.collections.PACKAGE.functions.CONSUMER;
+#endif
+import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
+#if !JDK_FUNCTION
+import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
+#endif
+import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
+#if !TYPE_OBJECT
+import speiger.src.collections.PACKAGE.utils.ARRAYS;
+#endif
+import speiger.src.collections.objects.utils.ObjectArrays;
+import speiger.src.collections.PACKAGE.utils.ITERATORS;
+#if TYPE_OBJECT
+import speiger.src.collections.utils.Stack;
+#endif
+#if PRIMITIVES && STREAM_FEATURE && SPLIT_ITERATOR_FEATURE
+import java.util.stream.JAVA_STREAM;
+import java.util.stream.StreamSupport;
+#endif
+#if SPLIT_ITERATOR_FEATURE
+import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR;
+import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
+#endif
+import speiger.src.collections.utils.ITrimmable;
+import speiger.src.collections.utils.SanityChecks;
+
+#if TYPE_OBJECT
+/**
+ * A Type-Specific Array-based implementation of list that is written to reduce (un)boxing
+ * 
+ * 

This implementation is optimized to improve how data is processed with interfaces like {@link ITrimmable}, {@link Stack} + * and with optimized functions that use type-specific implementations for primitives and optimized logic for bulkactions. + * + * @Type(T) + */ +public class COPY_ON_WRITE_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE implements ITrimmable, Stack +#else +/** + * A Type-Specific Array-based implementation of list that is written to reduce (un)boxing + * + *

This implementation is optimized to improve how data is processed with interfaces like {@link ITrimmable}, {@link STACK} + * and with optimized functions that use type-specific implementations for primitives and optimized logic for bulkactions. + */ +public class COPY_ON_WRITE_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE implements ITrimmable, STACK +#endif +{ + /** Access lock */ + transient ReentrantLock lock = new ReentrantLock(); + /** The backing array */ + protected transient KEY_TYPE[] data; + + /** + * Creates a new ArrayList with a Empty array. + */ + public COPY_ON_WRITE_LIST() { + data = EMPTY_KEY_ARRAY; + } + + /** + * Creates a new ArrayList a copy with the contents of the Collection. + * @param c the elements that should be added into the list + */ + @Deprecated + public COPY_ON_WRITE_LIST(Collection c) { + data = NEW_KEY_ARRAY(c.size()); + ITERATORS.unwrap(data, c.iterator()); + } + + /** + * Creates a new ArrayList a copy with the contents of the Collection. + * @param c the elements that should be added into the list + */ + public COPY_ON_WRITE_LIST(COLLECTION KEY_GENERIC_TYPE c) { + data = NEW_KEY_ARRAY(c.size()); + ITERATORS.unwrap(data, c.iterator()); + } + + /** + * Creates a new ArrayList a copy with the contents of the List. + * @param l the elements that should be added into the list + */ + public COPY_ON_WRITE_LIST(LIST KEY_GENERIC_TYPE l) { + data = NEW_KEY_ARRAY(l.size()); + l.getElements(0, data, 0, data.length); + } + + /** + * Creates a new ArrayList with a Copy of the array + * @param a the array that should be copied + */ + public COPY_ON_WRITE_LIST(KEY_TYPE... a) { + this(a, 0, a.length); + } + + /** + * Creates a new ArrayList with a Copy of the array with a custom length + * @param a the array that should be copied + * @param length the desired length that should be copied + */ + public COPY_ON_WRITE_LIST(KEY_TYPE[] a, int length) { + this(a, 0, length); + } + + /** + * Creates a new ArrayList with a Copy of the array with in the custom range. + * @param a the array that should be copied + * @param offset the starting offset of where the array should be copied from + * @param length the desired length that should be copied + * @throws IllegalStateException if offset is smaller then 0 + * @throws IllegalStateException if the offset + length exceeds the array length + */ + public COPY_ON_WRITE_LIST(KEY_TYPE[] a, int offset, int length) { + data = NEW_KEY_ARRAY(length); + SanityChecks.checkArrayCapacity(a.length, offset, length); + System.arraycopy(a, offset, data, 0, length); + } + +#if TYPE_OBJECT + /** + * Creates a new ArrayList with a EmptyObject array of the Type requested + * @param c the type of the array + * @Type(T) + * @return a typed List + */ + public static GENERIC_KEY_BRACES COPY_ON_WRITE_LIST KEY_GENERIC_TYPE of(Class c) { + COPY_ON_WRITE_LIST KEY_GENERIC_TYPE list = new COPY_ON_WRITE_LISTBRACES(); + list.data = (KEY_TYPE[])ObjectArrays.newArray(c, 0); + return list; + } + +#endif + + private void setArray(KEY_TYPE[] data) { + this.data = data; + } + + private KEY_TYPE[] getArray() { + return data; + } + + /** + * Appends the specified element to the end of this list. + * + * @param e element to be appended to this list + * @return true (as specified by {@link Collection#add}) + */ + @Override + public boolean add(KEY_TYPE e) { + ReentrantLock lock = this.lock; + lock.lock(); + try { + KEY_TYPE[] newElements = Arrays.copyOf(data, data.length+1); + newElements[newElements.length-1] = e; + data = newElements; + } + finally { + lock.unlock(); + } + return true; + } + + /** + * Appends the specified element to the end of this Stack. + * @param e element to be appended to this Stack + */ + @Override + public void push(KEY_TYPE e) { + add(e); + } + + /** + * Appends the specified element to the index of the list + * @param index the index where to append the element to + * @param e the element to append to the list + * @throws IndexOutOfBoundsException if index is outside of the lists range + */ + @Override + public void add(int index, KEY_TYPE e) { + ReentrantLock lock = this.lock; + lock.lock(); + try { + KEY_TYPE[] data = this.data; + int size = data.length; + if(index < 0 || index > size) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); + KEY_TYPE[] newElements; + + if(index == size) { + newElements = Arrays.copyOf(data, size+1); + } + else { + newElements = NEW_KEY_ARRAY(size+1); + System.arraycopy(data, 0, newElements, 0, index); + System.arraycopy(data, index, newElements, index + 1, size - index); + } + newElements[index] = e; + this.data = newElements; + } + finally { + lock.unlock(); + } + } + + /** + * Appends the specified elements to the index of the list. + * This function may delegate to more appropriate function if necessary + * @param index the index where to append the elements to + * @param c the elements to append to the list + * @throws IndexOutOfBoundsException if index is outside of the lists range + * @throws NullPointerException if collection contains a null element + */ + @Override + @Deprecated + public boolean addAll(int index, Collection c) { + if(c instanceof COLLECTION) return addAll(index, (COLLECTION KEY_GENERIC_TYPE)c); + int add = c.size(); + if(add <= 0) return false; +#if !TYPE_OBJECT + if(c.contains(null)) throw new NullPointerException(); +#endif + ReentrantLock lock = this.lock; + lock.lock(); + try { + KEY_TYPE[] data = this.data; + int size = data.length; + if(index < 0 || index > size) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); + KEY_TYPE[] newElements; + if(index == size) { + newElements = Arrays.copyOf(data, size+add); + } + else { + newElements = NEW_KEY_ARRAY(size+add); + System.arraycopy(data, 0, newElements, 0, index); + System.arraycopy(data, index, newElements, index + add, size - index); + } + Iterator iter = c.iterator(); + while(add-- != 0) newElements[index++] = OBJ_TO_KEY(iter.next()); + this.data = newElements; + } + finally { + lock.unlock(); + } + return true; + } + + /** + * Appends the specified elements to the index of the list. + * This function may delegate to more appropriate function if necessary + * @param index the index where to append the elements to + * @param c the elements to append to the list + * @throws IndexOutOfBoundsException if index is outside of the lists range + */ + @Override + public boolean addAll(int index, COLLECTION KEY_GENERIC_TYPE c) { + if(c instanceof LIST) return addAll(index, (LIST KEY_GENERIC_TYPE)c); + int add = c.size(); + if(add <= 0) return false; + ReentrantLock lock = this.lock; + lock.lock(); + try { + KEY_TYPE[] data = this.data; + int size = data.length; + if(index < 0 || index > size) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); + KEY_TYPE[] newElements; + if(index == size) { + newElements = Arrays.copyOf(data, size+add); + } + else { + newElements = NEW_KEY_ARRAY(size+add); + System.arraycopy(data, 0, newElements, 0, index); + System.arraycopy(data, index, newElements, index + add, size - index); + } + ITERATOR KEY_GENERIC_TYPE iter = c.iterator(); + while(add-- != 0) newElements[index++] = iter.NEXT(); + this.data = newElements; + } + finally { + lock.unlock(); + } + return true; + } + + /** + * Appends the specified elements to the index of the list. + * @param index the index where to append the elements to + * @param c the elements to append to the list + * @throws IndexOutOfBoundsException if index is outside of the lists range + */ + @Override + public boolean addAll(int index, LIST KEY_GENERIC_TYPE c) { + int add = c.size(); + if(add <= 0) return false; + ReentrantLock lock = this.lock; + lock.lock(); + try { + KEY_TYPE[] data = this.data; + int size = data.length; + if(index < 0 || index > size) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); + KEY_TYPE[] newElements; + if(index == size) { + newElements = Arrays.copyOf(data, size+add); + } + else { + newElements = NEW_KEY_ARRAY(size+add); + System.arraycopy(data, 0, newElements, 0, index); + System.arraycopy(data, index, newElements, index + add, size - index); + } + c.getElements(0, newElements, index, c.size()); + this.data = newElements; + } + finally { + lock.unlock(); + } + return true; + } + + @Override + public boolean addAll(KEY_TYPE[] e, int offset, int length) { + if(length <= 0) return false; + SanityChecks.checkArrayCapacity(e.length, offset, length); + ReentrantLock lock = this.lock; + lock.lock(); + try { + int size = data.length; + KEY_TYPE[] newElements = Arrays.copyOf(data, size+length); + System.arraycopy(e, offset, newElements, size, length); + data = newElements; + } + finally { + lock.unlock(); + } + return true; + } + + /** + * Appends the specified array elements to the index of the list. + * @param from the index where to append the elements to + * @param a the elements to append to the list + * @param offset where to start ino the array + * @param length the amount of elements to insert + * @throws IndexOutOfBoundsException if index is outside of the lists range + */ + @Override + public void addElements(int from, KEY_TYPE[] a, int offset, int length) { + if(length <= 0) return; + ReentrantLock lock = this.lock; + lock.lock(); + try { + KEY_TYPE[] data = this.data; + int size = data.length; + if(from < 0 || from > size) throw new IndexOutOfBoundsException("Index: " + from + ", Size: " + size); + SanityChecks.checkArrayCapacity(a.length, offset, length); + KEY_TYPE[] newElements; + if(from == size) { + newElements = Arrays.copyOf(data, size+length); + } + else { + newElements = NEW_KEY_ARRAY(size+length); + System.arraycopy(data, 0, newElements, 0, from); + System.arraycopy(data, from, newElements, from + length, size - from); + } + System.arraycopy(a, offset, newElements, from, length); + this.data = newElements; + } + finally { + lock.unlock(); + } + } + + /** + * A function to fast fetch elements from the list + * @param from index where the list should be fetching elements from + * @param a the array where the values should be inserted to + * @param offset the startIndex of where the array should be written to + * @param length the number of elements the values should be fetched from + * @return the inputArray + * @throws NullPointerException if the array is null + * @throws IndexOutOfBoundsException if from is outside of the lists range + * @throws IllegalStateException if offset or length are smaller then 0 or exceed the array length + */ + @Override + public KEY_TYPE[] getElements(int from, KEY_TYPE[] a, int offset, int length) { + KEY_TYPE[] data = this.data; + SanityChecks.checkArrayCapacity(data.length, from, length); + SanityChecks.checkArrayCapacity(a.length, offset, length); + System.arraycopy(data, from, a, offset, length); + return a; + } + + /** + * a function to fast remove elements from the list. + * @param from the start index of where the elements should be removed from (inclusive) + * @param to the end index of where the elements should be removed to (exclusive) + */ + @Override + public void removeElements(int from, int to) { + checkRange(from); + checkAddRange(to); + int length = to - from; + if(length <= 0) return; + ReentrantLock lock = this.lock; + lock.lock(); + try { + KEY_TYPE[] data = this.data; + if(to == data.length) this.data = Arrays.copyOf(data, data.length - length); + else { + int size = data.length-length; + KEY_TYPE[] newElements = NEW_KEY_ARRAY(size); + System.arraycopy(data, 0, newElements, 0, from); + System.arraycopy(data, to, newElements, from, data.length - to); + this.data = newElements; + } + } + finally { + lock.unlock(); + } + } + +#if TYPE_OBJECT + /** + * A function to fast extract elements out of the list, this removes the elements that were fetched. + * @param from the start index of where the elements should be fetched from (inclusive) + * @param to the end index of where the elements should be fetched to (exclusive) + * @param type the type of the OutputArray + * @return a array of the elements that were fetched + */ + @Override + public K[] extractElements(int from, int to, Class type) { + checkRange(from); + checkAddRange(to); + int length = to - from; + if(length <= 0) return ARRAYS.newArray(type, 0); + K[] a = ARRAYS.newArray(type, length); + ReentrantLock lock = this.lock; + lock.lock(); + try { + KEY_TYPE[] data = this.data; + System.arraycopy(data, from, a, 0, length); + if(to == data.length) this.data = Arrays.copyOf(data, data.length - length); + else { + int size = data.length; + KEY_TYPE[] newElements = NEW_KEY_ARRAY(size-length); + if(from != 0) System.arraycopy(data, 0, newElements, 0, from); + System.arraycopy(data, to, newElements, from, size - to); + this.data = newElements; + } + return a; + } + finally { + lock.unlock(); + } + } + +#else + /** + * A function to fast extract elements out of the list, this removes the elements that were fetched. + * @param from the start index of where the elements should be fetched from (inclusive) + * @param to the end index of where the elements should be fetched to (exclusive) + * @return a array of the elements that were fetched + */ + @Override + public KEY_TYPE[] extractElements(int from, int to) { + checkRange(from); + checkAddRange(to); + int length = to - from; + if(length <= 0) return EMPTY_KEY_ARRAY; + ReentrantLock lock = this.lock; + lock.lock(); + try { + KEY_TYPE[] data = this.data; + KEY_TYPE[] a = NEW_KEY_ARRAY(length); + System.arraycopy(data, from, a, 0, length); + if(to == data.length) this.data = Arrays.copyOf(data, data.length - length); + else { + int size = data.length; + KEY_TYPE[] newElements = NEW_KEY_ARRAY(size-length); + if(from != 0) System.arraycopy(data, 0, newElements, 0, from); + System.arraycopy(data, to, newElements, from, size - to); + this.data = newElements; + } + return a; + } + finally { + lock.unlock(); + } + } + +#endif +#if PRIMITIVES + @Override + public void fillBuffer(JAVA_BUFFER buffer) { + buffer.put(data, 0, data.length); + } + +#endif + /** + * A function to find if the Element is present in this list. + * @param o the element that is searched for + * @return if the element was found. + */ + @Override + @Deprecated + public boolean contains(Object o) { + return indexOf(o) != -1; + } + + /** + * A function to find the index of a given element + * @param o the element that is searched for + * @return the index of the element if found. (if not found then -1) + */ + @Override + @Deprecated + public int indexOf(Object o) { + KEY_TYPE[] data = this.data; +#if TYPE_OBJECT + if(o == null) { + for(int i = 0,m=data.length;i=0;i--) + if(data[i] == null) return i; + return -1; + } +#else + if(o == null) return -1; +#endif + for(int i = data.length - 1;i>=0;i--) { + if(Objects.equals(o, KEY_TO_OBJ(data[i]))) return i; + } + return -1; + } + +#if TYPE_OBJECT + /** + * Sorts the elements specified by the Natural order either by using the Comparator or the elements + * @param c the sorter of the elements, can be null + * @see java.util.List#sort(Comparator) + */ + @Override + public void sort(Comparator c) { + ReentrantLock lock = this.lock; + lock.lock(); + try { + KEY_TYPE[] newData = Arrays.copyOf(data, data.length); + if(c != null) ARRAYS.stableSort(newData, newData.length, c); + else ARRAYS.stableSort(newData, newData.length); + data = newData; + } + finally { + lock.unlock(); + } + } + + /** + * Sorts the elements specified by the Natural order either by using the Comparator or the elements using a unstable sort + * @param c the sorter of the elements, can be null + * @see java.util.List#sort(Comparator) + */ + @Override + public void unstableSort(Comparator c) { + ReentrantLock lock = this.lock; + lock.lock(); + try { + KEY_TYPE[] newData = Arrays.copyOf(data, data.length); + if(c != null) ARRAYS.unstableSort(newData, newData.length, c); + else ARRAYS.unstableSort(newData, newData.length); + data = newData; + } + finally { + lock.unlock(); + } + } + +#else + /** + * A Type Specific implementation of the Collection#contains function. + * @param e the element that is searched for. + * @return if the element was found + */ + @Override + public boolean contains(KEY_TYPE e) { + return indexOf(e) != -1; + } + + /** + * A Type-Specific function to find the index of a given element + * @param e the element that is searched for + * @return the index of the element if found. (if not found then -1) + */ + @Override + public int indexOf(KEY_TYPE e) { + KEY_TYPE[] data = this.data; + for(int i = 0,m=data.length;i=0;i--) { + if(KEY_EQUALS(data[i], e)) return i; + } + return -1; + } + + /** + * Sorts the elements specified by the Natural order either by using the Comparator or the elements + * @param c the sorter of the elements, can be null + * @see java.util.List#sort(java.util.Comparator) + * @see ARRAYS#stableSort(KEY_TYPE[], COMPARATOR) + */ + @Override + public void sort(COMPARATOR c) { + ReentrantLock lock = this.lock; + lock.lock(); + try { + KEY_TYPE[] newData = Arrays.copyOf(data, data.length); + if(c != null) ARRAYS.stableSort(newData, newData.length, c); + else ARRAYS.stableSort(newData, newData.length); + data = newData; + } + finally { + lock.unlock(); + } + } + + /** + * Sorts the elements specified by the Natural order either by using the Comparator or the elements using a unstable sort + * @param c the sorter of the elements, can be null + * @see java.util.List#sort(java.util.Comparator) + * @see ARRAYS#unstableSort(KEY_TYPE[], COMPARATOR) + */ + @Override + public void unstableSort(COMPARATOR c) { + ReentrantLock lock = this.lock; + lock.lock(); + try { + KEY_TYPE[] newData = Arrays.copyOf(data, data.length); + if(c != null) ARRAYS.unstableSort(newData, newData.length, c); + else ARRAYS.unstableSort(newData, newData.length); + data = newData; + } + finally { + lock.unlock(); + } + } + +#endif + /** + * A Type-Specific get function to reduce (un)boxing + * @param index the index of the element to fetch + * @return the value of the requested index + * @throws IndexOutOfBoundsException if the index is out of range + */ + @Override + public KEY_TYPE GET_KEY(int index) { + checkRange(index); + return data[index]; + } + + /** + * Provides the Selected Object from the stack. + * Top to bottom + * @param index of the element that should be provided + * @return the element that was requested + * @throws ArrayIndexOutOfBoundsException if the index is out of bounds + * @see speiger.src.collections.utils.Stack#peek(int) + */ + @Override + public KEY_TYPE peek(int index) { + checkRange((size() - 1) - index); + return data[(size() - 1) - index]; + } + + @Override + public LIST_ITERATOR KEY_GENERIC_TYPE listIterator(int index) { + if(index < 0 || index > size()) throw new IndexOutOfBoundsException(); + return new COWIteratorBRACES(data, index); + } + + @Override + public LIST KEY_GENERIC_TYPE subList(int fromIndex, int toIndex) { + SanityChecks.checkArrayCapacity(data.length, fromIndex, toIndex-fromIndex); + return new COWSubListBRACES(this, lock, this::setArray, this::getArray, 0, fromIndex, toIndex); + } + + /** + * A Type Specific foreach function that reduces (un)boxing + * + * @implSpec + *

The default implementation behaves as if: + *

{@code
+	 * 	for(int i = 0,m=data.length;i
+	 *
+	 * @param action The action to be performed for each element
+	 * @throws NullPointerException if the specified action is null
+	 * @see Iterable#forEach(java.util.function.Consumer)
+	 */
+	@Override
+	public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
+		Objects.requireNonNull(action);
+		KEY_TYPE[] data = this.data;
+		for(int i = 0,m=data.length;i void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) {
+		Objects.requireNonNull(action);
+		KEY_TYPE[] data = this.data;
+		for(int i = 0,m=data.length;i KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) {
+		Objects.requireNonNull(operator);
+		KEY_TYPE[] data = this.data;
+		KEY_SPECIAL_TYPE state = identity;
+		for(int i = 0,m=data.length;i o) {
+#if PRIMITIVES
+		Objects.requireNonNull(o);
+#if TYPE_BYTE || TYPE_SHORT || TYPE_CHAR || TYPE_FLOAT
+		REPLACE(T -> OBJ_TO_KEY(o.apply(KEY_TO_OBJ(SanityChecks.SANITY_CAST(T)))));
+#else
+		REPLACE(T -> OBJ_TO_KEY(o.apply(KEY_TO_OBJ(T))));
+#endif
+#else
+		Objects.requireNonNull(o);
+		ReentrantLock lock = this.lock;
+		lock.lock();
+		try {
+			KEY_TYPE[] newData = Arrays.copyOf(data, data.length);
+			for(int i = 0,m=newData.length;i c) {
+		if(c.isEmpty()) return false;
+		ReentrantLock lock = this.lock;
+		lock.lock();
+		try {
+			KEY_TYPE[] data = this.data;
+			KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length);
+			int j = 0;
+			for(int i= 0,m=data.length;i c) {
+		ReentrantLock lock = this.lock;
+		lock.lock();
+		try {
+			KEY_TYPE[] data = this.data;
+			if(c.isEmpty()) {
+				if(data.length > 0) {
+					this.data = EMPTY_KEY_ARRAY;
+					return true;
+				}
+				return false;
+			}
+			KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length);
+			int j = 0;
+			for(int i= 0,m=data.length;i filter) {
+		Objects.requireNonNull(filter);
+		ReentrantLock lock = this.lock;
+		lock.lock();
+		try {
+			KEY_TYPE[] data = this.data;
+			KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length);
+			int j = 0;
+			for(int i= 0,m=data.length;i 0) {
+					this.data = EMPTY_KEY_ARRAY;
+					return true;
+				}
+				return false;
+			}
+			KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length);
+			int j = 0;
+			for(int i= 0,m=data.length;i 0) {
+					forEach(r);
+					this.data = EMPTY_KEY_ARRAY;
+					return true;
+				}
+				return false;
+			}
+			KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length);
+			int j = 0;
+			for(int i= 0,m=data.length;i E[] toArray(E[] a) {
+		KEY_TYPE[] data = this.data;
+		int size = data.length;
+		if(a == null) a = (E[])new Object[size];
+		else if(a.length < size) a = (E[])ObjectArrays.newArray(a.getClass().getComponentType(), size);
+#if TYPE_OBJECT
+        System.arraycopy(data, 0, a, 0, size);
+#else
+		for(int i = 0;i size) a[size] = null;
+		return a;
+	}
+	
+#if !TYPE_OBJECT
+	@Override
+	public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) {
+		KEY_TYPE[] data = this.data;
+		int size = data.length;
+		if(a.length < size) a = new KEY_TYPE[size];
+		System.arraycopy(data, 0, a, 0, size);
+		if (a.length > size) a[size] = EMPTY_KEY_VALUE;
+		return a;
+	}
+	
+#endif
+	
+	/**
+	 * A function to return the size of the list
+	 * @return the size of elements in the list
+	 */
+	@Override
+	public int size() {
+		return data.length;
+	}
+	
+	/**
+	 * A function to ensure the elements are within the requested size.
+	 * If smaller then the stored elements they get removed as needed.
+	 * If bigger it is ensured that enough room is provided depending on the implementation
+	 * @param size the requested amount of elements/room for elements
+	 */
+	@Override
+	public void size(int size) {
+		if(size == data.length || size < 0) return;
+		ReentrantLock lock = this.lock;
+		lock.lock();
+		try {
+			data = Arrays.copyOf(data, size);
+		}
+		finally {
+			lock.unlock();
+		}
+	}
+	
+	/**
+	 * A function to clear all elements in the list.
+	 */
+	@Override
+	public void clear() {
+		ReentrantLock lock = this.lock;
+		lock.lock();
+		try {
+			data = EMPTY_KEY_ARRAY;
+		}
+		finally {
+			lock.unlock();
+		}
+	}
+	
+	/**
+	 * Trims the original collection down to the size of the current elements or the requested size depending which is bigger
+	 * @param size the requested trim size.
+	 */
+	@Override
+	public boolean trim(int size) {
+		return false;
+	}
+	
+	/**
+	 * Trims the collection down to the requested size and clears all elements while doing so
+	 * @param size the amount of elements that should be allowed
+	 * @note this will enforce minimum size of the collection itself
+	 */
+	@Override
+	public void clearAndTrim(int size) {
+		ReentrantLock lock = this.lock;
+		lock.lock();
+		try {
+			data = EMPTY_KEY_ARRAY;
+		}
+		finally {
+			lock.unlock();
+		}
+	}
+	
+	@Override
+	public COPY_ON_WRITE_LIST KEY_GENERIC_TYPE copy() {
+		COPY_ON_WRITE_LIST KEY_GENERIC_TYPE list = new COPY_ON_WRITE_LISTBRACES();
+		list.data = Arrays.copyOf(data, data.length);
+		return list;
+	}
+	
+	protected void checkRange(int index) {
+		if (index < 0 || index >= data.length)
+			throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + data.length);
+	}
+	
+	protected void checkAddRange(int index) {
+		if (index < 0 || index > data.length)
+			throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + data.length);
+	}
+
+#if SPLIT_ITERATOR_FEATURE
+#if PRIMITIVES && STREAM_FEATURE
+	/**
+	 * Returns a Java-Type-Specific Stream to reduce boxing/unboxing.
+	 * @return a Stream of the closest java type
+	 * @note characteristics are ordered, sized, subsized
+	 */
+	@Override
+	public JAVA_STREAM primitiveStream() { return StreamSupport.NEW_STREAM(SPLIT_ITERATORS.createArrayJavaSplititerator(data, data.length, 16464), false); }
+	
+#endif
+	/**
+	 * A Type Specific Type Splititerator to reduce boxing/unboxing
+	 * @return type specific splititerator
+	 * @note characteristics are ordered, sized, subsized
+	 */
+	@Override
+	public SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createArraySplititerator(data, data.length, 16464); }
+	
+#endif
+	static final class COWIterator KEY_GENERIC_TYPE implements LIST_ITERATOR KEY_GENERIC_TYPE
+	{
+		KEY_TYPE[] data;
+		int index;
+		
+		public COWIterator(KEY_TYPE[] data, int index) {
+			this.data = data;
+			this.index = index;
+		}
+		
+		@Override
+		public boolean hasNext() {
+			return index < data.length;
+		}
+		
+		@Override
+		public KEY_TYPE NEXT() {
+			if(!hasNext()) throw new NoSuchElementException();
+			return data[index++];
+		}
+		
+		@Override
+		public boolean hasPrevious() {
+			return index > 0;
+		}
+		
+		@Override
+		public KEY_TYPE PREVIOUS() {
+			if(!hasPrevious()) throw new NoSuchElementException();
+			return data[--index];
+		}
+		
+		@Override
+		public int nextIndex() {
+			return index;
+		}
+		
+		@Override
+		public int previousIndex() {
+			return index-1;
+		}
+		
+		@Override
+		public void remove() { throw new UnsupportedOperationException(); }
+		@Override
+		public void set(KEY_TYPE e) { throw new UnsupportedOperationException(); }
+		@Override
+		public void add(KEY_TYPE e) { throw new UnsupportedOperationException(); }
+		
+		@Override
+		public int skip(int amount) {
+			if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
+			int steps = Math.min(amount, data.length - index);
+			index += steps;
+			return steps;
+		}
+		
+		@Override
+		public int back(int amount) {
+			if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
+			int steps = Math.min(amount, index);
+			index -= steps;
+			return steps;
+		}
+	}
+	
+	private static class COWSubList KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
+	{
+		final ABSTRACT_LIST KEY_GENERIC_TYPE list;
+		final ReentrantLock lock;
+		final Consumer setter;
+		final Supplier getter;
+		final int parentOffset;
+		final int offset;
+		int size;
+		
+		public COWSubList(ABSTRACT_LIST KEY_GENERIC_TYPE list, ReentrantLock lock, Consumer setter, Supplier getter, int offset, int from, int to) {
+			this.list = list;
+			this.lock = lock;
+			this.setter = setter;
+			this.getter = getter;
+			this.parentOffset = from;
+			this.offset = offset + from;
+			this.size = to - from;
+		}
+		
+		@Override
+		public void add(int index, KEY_TYPE element) {
+			lock.lock();
+			try {
+				checkAddSubRange(index);
+				list.add(parentOffset+index, element);
+				size++;				
+			}
+			finally {
+				lock.unlock();
+			}
+		}
+		
+		@Override
+		public boolean addAll(int index, Collection c) {
+			int add = c.size();
+			if(add <= 0) return false;
+			lock.lock();
+			try {
+				checkAddSubRange(index);
+				list.addAll(parentOffset+index, c);
+				this.size += add;
+			}
+			finally {
+				lock.unlock();
+			}
+			return true;
+		}
+		
+		@Override
+		public boolean addAll(int index, COLLECTION KEY_GENERIC_TYPE c) {
+			int add = c.size();
+			if(add <= 0) return false;
+			lock.lock();
+			try {
+				checkAddSubRange(index);
+				list.addAll(parentOffset+index, c);
+				this.size += add;
+			}
+			finally {
+				lock.unlock();
+			}
+			return true;
+		}
+
+		@Override
+		public boolean addAll(int index, LIST KEY_GENERIC_TYPE c) {
+			int add = c.size();
+			if(add <= 0) return false;
+			lock.lock();
+			try {
+				checkAddSubRange(index);
+				list.addAll(parentOffset+index, c);
+				this.size += add;
+			}
+			finally {
+				lock.unlock();
+			}
+			return true;
+		}
+		
+		@Override
+		public void addElements(int from, KEY_TYPE[] a, int offset, int length) {
+			if(length <= 0) return;
+			lock.lock();
+			try {
+				checkAddSubRange(from);
+				list.addElements(parentOffset+from, a, offset, length);
+				this.size += length;
+			}
+			finally {
+				lock.unlock();
+			}
+		}
+		
+		@Override
+		public KEY_TYPE[] getElements(int from, KEY_TYPE[] a, int offset, int length) {
+			SanityChecks.checkArrayCapacity(size, from, length);
+			SanityChecks.checkArrayCapacity(a.length, offset, length);
+			return list.getElements(from+parentOffset, a, offset, length);
+		}
+		
+		@Override
+		public void removeElements(int from, int to) {
+			if(to-from <= 0) return;
+			lock.lock();
+			try {
+				checkSubRange(from);
+				checkAddSubRange(to);
+				list.removeElements(from+parentOffset, to+parentOffset);
+				size -= to - from;
+			}
+			finally {
+				lock.unlock();
+			}
+		}
+		
+#if TYPE_OBJECT
+		@Override
+		public  K[] extractElements(int from, int to, Class type) {
+			lock.lock();
+			try {
+				checkSubRange(from);
+				checkAddSubRange(to);
+				K[] result = list.extractElements(from+parentOffset, to+parentOffset, type);
+				size -= result.length;
+				return result;
+			}
+			finally {
+				lock.unlock();
+			}
+		}
+
+#else
+		@Override
+		public KEY_TYPE[] extractElements(int from, int to) {
+			lock.lock();
+			try {
+				checkSubRange(from);
+				checkAddSubRange(to);
+				KEY_TYPE[] result = list.extractElements(from+parentOffset, to+parentOffset);
+				size -= result.length;
+				return result;
+			}
+			finally {
+				lock.unlock();
+			}
+		}
+		
+#endif
+		@Override
+		public KEY_TYPE GET_KEY(int index) {
+			checkSubRange(index);
+			return list.GET_KEY(parentOffset+index);
+		}
+
+		@Override
+		public KEY_TYPE set(int index, KEY_TYPE element) {
+			lock.lock();
+			try {
+				checkSubRange(index);
+				return list.set(parentOffset+index, element);
+			}
+			finally {
+				lock.unlock();
+			}
+		}
+		
+		@Override
+		public KEY_TYPE swapRemove(int index) {
+			if(index < 0 || index >= size) throw new IndexOutOfBoundsException();
+			ReentrantLock lock = this.lock;
+			lock.lock();
+			try {
+				KEY_TYPE[] data = getter.get();
+				KEY_TYPE result = data[offset+index];
+				KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length-1);
+				int end = offset+size-1;
+				System.arraycopy(data, 0, newElements, 0, end);
+				if(end != newElements.length) System.arraycopy(data, end+1, newElements, end, data.length-end-1);
+				if(index+offset != end) newElements[index+offset] = data[end];
+				setter.accept(newElements);
+				size--;
+				return result;
+			}
+			finally {
+				lock.unlock();
+			}
+		}
+		
+		@Override
+		public KEY_TYPE REMOVE(int index) {
+			lock.lock();
+			try {
+				checkSubRange(index);
+				KEY_TYPE result = list.REMOVE(index+parentOffset);
+				size--;
+				return result;
+			}
+			finally {
+				lock.unlock();
+			}
+		}
+		
+#if !TYPE_OBJECT
+		@Override
+		public boolean REMOVE_KEY(KEY_TYPE type) {
+			int index = indexOf(type);
+			if(index == -1) return false;
+			REMOVE(index);
+			return true;
+		}
+		
+#else
+		@Override
+		public boolean remove(Object type) {
+			int index = indexOf(type);
+			if(index == -1) return false;
+			REMOVE(index);
+			return true;
+		}
+		
+#endif
+		
+#if TYPE_OBJECT
+		@Override
+		public void sort(Comparator c) {
+			ReentrantLock lock = this.lock;
+			lock.lock();
+			try {
+				KEY_TYPE[] data = getter.get();
+				KEY_TYPE[] newData = Arrays.copyOf(data, data.length);
+				if(c != null) ARRAYS.stableSort(newData, offset, offset+size, c);
+				else ARRAYS.stableSort(newData, offset, offset+size);
+				setter.accept(newData);
+			}
+			finally {
+				lock.unlock();
+			}
+		}
+		
+		@Override
+		public void unstableSort(Comparator c) {
+			ReentrantLock lock = this.lock;
+			lock.lock();
+			try {
+				KEY_TYPE[] data = getter.get();
+				KEY_TYPE[] newData = Arrays.copyOf(data, data.length);
+				if(c != null) ARRAYS.unstableSort(newData, offset, offset+size, c);
+				else ARRAYS.unstableSort(newData, offset, offset+size);
+				setter.accept(newData);
+			}
+			finally {
+				lock.unlock();
+			}
+		}
+		
+#else
+		@Override
+		public void sort(COMPARATOR c) {
+			ReentrantLock lock = this.lock;
+			lock.lock();
+			try {
+				KEY_TYPE[] data = getter.get();
+				KEY_TYPE[] newData = Arrays.copyOf(data, data.length);
+				if(c != null) ARRAYS.stableSort(newData, offset, offset+size, c);
+				else ARRAYS.stableSort(newData, offset, offset+size);
+				setter.accept(newData);
+			}
+			finally {
+				lock.unlock();
+			}
+		}
+		
+		@Override
+		public void unstableSort(COMPARATOR c) {
+			ReentrantLock lock = this.lock;
+			lock.lock();
+			try {
+				KEY_TYPE[] data = getter.get();
+				KEY_TYPE[] newData = Arrays.copyOf(data, data.length);
+				if(c != null) ARRAYS.unstableSort(newData, offset, offset+size, c);
+				else ARRAYS.unstableSort(newData, offset, offset+size);
+				setter.accept(newData);
+			}
+			finally {
+				lock.unlock();
+			}	
+		}
+		
+#endif
+		
+		@Override
+		@Deprecated
+		public boolean removeAll(Collection c) {
+			if(c.isEmpty()) return false;
+			ReentrantLock lock = this.lock;
+			lock.lock();
+			try {
+				KEY_TYPE[] data = getter.get();
+				KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length);
+				int j = 0;
+				for(int i= 0,m=data.length;i= offset+size) newElements[j++] = data[i];
+					else if(!c.contains(KEY_TO_OBJ(data[i]))) newElements[j++] = data[i];
+				}
+				if(data.length != j) {
+					setter.accept(Arrays.copyOf(newElements, j));
+					size -= data.length - j;
+					return true;
+				}
+				return false;
+			}
+			finally {
+				lock.unlock();
+			}
+		}
+		
+		@Override
+		@Deprecated
+		public boolean retainAll(Collection c) {
+			ReentrantLock lock = this.lock;
+			lock.lock();
+			try {
+				KEY_TYPE[] data = getter.get();
+				if(c.isEmpty()) {
+					if(size > 0) {
+						clear();
+						return true;
+					}
+					return false;
+				}
+				KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length);
+				int j = 0;
+				for(int i= 0,m=data.length;i= offset+size) newElements[j++] = data[i];
+					else if(c.contains(KEY_TO_OBJ(data[i]))) newElements[j++] = data[i];
+				}
+				if(data.length != j) {
+					setter.accept(Arrays.copyOf(newElements, j));
+					size -= data.length - j;
+					return true;
+				}
+				return false;
+			}
+			finally {
+				lock.unlock();
+			}
+		}
+		
+		@Override
+		@Deprecated
+		public boolean removeIf(Predicate filter) {
+			Objects.requireNonNull(filter);
+			ReentrantLock lock = this.lock;
+			lock.lock();
+			try {
+				KEY_TYPE[] data = getter.get();
+				KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length);
+				int j = 0;
+				for(int i= 0,m=data.length;i= offset+size) newElements[j++] = data[i];
+					else if(!filter.test(KEY_TO_OBJ(data[i]))) newElements[j++] = data[i];
+				}
+				if(data.length != j) {
+					setter.accept(Arrays.copyOf(newElements, j));
+					size -= data.length - j;
+					return true;
+				}
+				return false;
+			}
+			finally {
+				lock.unlock();
+			}
+		}
+		
+		@Override
+		public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) {
+			if(c.isEmpty()) return false;
+			ReentrantLock lock = this.lock;
+			lock.lock();
+			try {
+				KEY_TYPE[] data = getter.get();
+				KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length);
+				int j = 0;
+				for(int i= 0,m=data.length;i= offset+size) newElements[j++] = data[i];
+					else if(!c.contains(data[i])) newElements[j++] = data[i];
+				}
+				if(data.length != j) {
+					setter.accept(Arrays.copyOf(newElements, j));
+					size -= data.length - j;
+					return true;
+				}
+				return false;
+			}
+			finally {
+				lock.unlock();
+			}
+		}
+		
+		@Override
+		public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) {
+			if(c.isEmpty()) return false;
+			ReentrantLock lock = this.lock;
+			lock.lock();
+			try {
+				KEY_TYPE[] data = getter.get();
+				KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length);
+				int j = 0;
+				for(int i= 0,m=data.length;i= offset+size) newElements[j++] = data[i];
+					else if(!c.contains(data[i])) newElements[j++] = data[i];
+					else r.accept(data[i]);
+				}
+				if(data.length != j) {
+					setter.accept(Arrays.copyOf(newElements, j));
+					size -= data.length - j;
+					return true;
+				}
+				return false;
+			}
+			finally {
+				lock.unlock();
+			}
+		}
+		
+		@Override
+		public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) {
+			ReentrantLock lock = this.lock;
+			lock.lock();
+			try {
+				KEY_TYPE[] data = getter.get();
+				if(c.isEmpty()) {
+					if(size > 0) {
+						clear();
+						return true;
+					}
+					return false;
+				}
+				KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length);
+				int j = 0;
+				for(int i= 0,m=data.length;i= offset+size) newElements[j++] = data[i];
+					else if(c.contains(data[i])) newElements[j++] = data[i];
+				}
+				if(data.length != j) {
+					setter.accept(Arrays.copyOf(newElements, j));;
+					size -= data.length - j;
+					return true;
+				}
+				return false;
+			}
+			finally {
+				lock.unlock();
+			}
+		}
+		
+		@Override
+		public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) {
+			ReentrantLock lock = this.lock;
+			lock.lock();
+			try {
+				KEY_TYPE[] data = getter.get();
+				if(c.isEmpty()) {
+					if(size > 0) {
+						forEach(r);
+						clear();
+						return true;
+					}
+					return false;
+				}
+				KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length);
+				int j = 0;
+				for(int i= 0,m=data.length;i= offset+size) newElements[j++] = data[i];
+					else if(c.contains(data[i])) newElements[j++] = data[i];
+					else r.accept(data[i]);
+				}
+				if(data.length != j) {
+					setter.accept(Arrays.copyOf(newElements, j));
+					size -= data.length - j;
+					return true;
+				}
+				return false;
+			}
+			finally {
+				lock.unlock();
+			}
+		}
+		
+#if PRIMITIVES
+		@Override
+		public boolean remIf(JAVA_PREDICATE filter) {
+			Objects.requireNonNull(filter);
+			ReentrantLock lock = this.lock;
+			lock.lock();
+			try {
+				KEY_TYPE[] data = getter.get();
+				KEY_TYPE[] newElements = NEW_KEY_ARRAY(data.length);
+				int j = 0;
+				for(int i=0,m=data.length;i= offset+size) newElements[j++] = data[i];
+					else if(!filter.test(data[i])) newElements[j++] = data[i];
+				}
+				if(data.length != j) {
+					setter.accept(Arrays.copyOf(newElements, j));
+					size -= data.length - j;
+					return true;
+				}
+				return false;
+			}
+			finally {
+				lock.unlock();
+			}
+		}
+		
+#endif
+		
+		@Override
+		@Primitive
+		public void replaceAll(UnaryOperator o) {
+#if PRIMITIVES
+			Objects.requireNonNull(o);
+#if TYPE_BYTE || TYPE_SHORT || TYPE_CHAR || TYPE_FLOAT
+			REPLACE(T -> OBJ_TO_KEY(o.apply(KEY_TO_OBJ(SanityChecks.SANITY_CAST(T)))));
+#else
+			REPLACE(T -> OBJ_TO_KEY(o.apply(KEY_TO_OBJ(T))));
+#endif
+#else
+			Objects.requireNonNull(o);
+			ReentrantLock lock = this.lock;
+			lock.lock();
+			try {
+				KEY_TYPE[] data = getter.get();
+				KEY_TYPE[] newData = Arrays.copyOf(data, data.length);
+				for(int i = 0,m=size;i size()) throw new IndexOutOfBoundsException();
+			return new COWSubListIteratorBRACES(this, index);
+		}
+		
+		@Override
+		public LIST KEY_GENERIC_TYPE subList(int fromIndex, int toIndex) {
+			SanityChecks.checkArrayCapacity(size, fromIndex, toIndex-fromIndex);
+			return new COWSubListBRACES(this, lock, setter, getter, offset, fromIndex, toIndex);
+		}
+		
+		protected void checkSubRange(int index) {
+			if (index < 0 || index >= size)
+				throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
+		}
+		
+		protected void checkAddSubRange(int index) {
+			if (index < 0 || index > size)
+				throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
+		}
+	}
+	
+	private static class COWSubListIterator KEY_GENERIC_TYPE implements LIST_ITERATOR KEY_GENERIC_TYPE
+	{
+		ABSTRACT_LIST KEY_GENERIC_TYPE list;
+		int index;
+		
+		COWSubListIterator(ABSTRACT_LIST KEY_GENERIC_TYPE list, int index) {
+			this.list = list;
+			this.index = index;
+		}
+		
+		@Override
+		public boolean hasNext() {
+			return index < list.size();
+		}
+		
+		@Override
+		public KEY_TYPE NEXT() {
+			if(!hasNext()) throw new NoSuchElementException();
+			return list.GET_KEY(index++);
+		}
+		
+		@Override
+		public boolean hasPrevious() {
+			return index > 0;
+		}
+		
+		@Override
+		public KEY_TYPE PREVIOUS() {
+			if(!hasPrevious()) throw new NoSuchElementException();
+			return list.GET_KEY(--index);
+		}
+		
+		@Override
+		public int nextIndex() {
+			return index;
+		}
+		
+		@Override
+		public int previousIndex() {
+			return index-1;
+		}
+		
+		@Override
+		public void remove() { throw new UnsupportedOperationException(); }
+		
+		@Override
+		public void set(KEY_TYPE e) { throw new UnsupportedOperationException(); }
+		
+		@Override
+		public void add(KEY_TYPE e) { throw new UnsupportedOperationException(); }
+		
+		@Override
+		public int skip(int amount) {
+			if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
+			int steps = Math.min(amount, list.size() - index);
+			index += steps;
+			return steps;
+		}
+		
+		@Override
+		public int back(int amount) {
+			if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
+			int steps = Math.min(amount, index);
+			index -= steps;
+			return steps;
+		}
+	}
 }
\ No newline at end of file
diff --git a/src/builder/resources/speiger/assets/collections/templates/lists/LinkedList.template b/src/builder/resources/speiger/assets/collections/templates/lists/LinkedList.template
index 45f34ee..af52b60 100644
--- a/src/builder/resources/speiger/assets/collections/templates/lists/LinkedList.template
+++ b/src/builder/resources/speiger/assets/collections/templates/lists/LinkedList.template
@@ -1,1377 +1,1379 @@
-package speiger.src.collections.PACKAGE.lists;
-
-#if TYPE_OBJECT
-#if DEQUEUE_FEATURE
-import java.util.Comparator;
-#endif
-
-import java.util.function.BiFunction;
-#else if PRIMITIVES
-import java.nio.JAVA_BUFFER;
-#endif
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.Objects;
-import java.util.NoSuchElementException;
-import java.util.Spliterator;
-#if PRIMITIVES
-import java.util.Spliterator.JAVA_SPLIT_ITERATOR;
-#endif
-import java.util.function.Consumer;
-import java.util.function.Predicate;
-#if TYPE_OBJECT
-import java.util.function.IntFunction;
-#endif
-#if !TYPE_OBJECT && JDK_FUNCTION
-import java.util.function.PREDICATE;
-#endif
-import java.util.function.UnaryOperator;
-#if PRIMITIVES
-#if !JDK_FUNCTION
-import java.util.function.JAVA_PREDICATE;
-#endif
-import java.util.function.JAVA_UNARY_OPERATOR;
-#endif
-import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER;
-import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
-#if !JDK_FUNCTION
-import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
-#endif
-import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
-import speiger.src.collections.PACKAGE.collections.COLLECTION;
-#if !TYPE_OBJECT
-import speiger.src.collections.PACKAGE.collections.STACK;
-#endif
-import speiger.src.collections.PACKAGE.collections.ITERATOR;
-#if DEQUEUE_FEATURE
-import speiger.src.collections.PACKAGE.queues.PRIORITY_DEQUEUE;
-#endif
-#if !TYPE_OBJECT
-#if DEQUEUE_FEATURE
-import speiger.src.collections.PACKAGE.functions.COMPARATOR;
-#endif
-
-import speiger.src.collections.PACKAGE.functions.CONSUMER;
-#endif
-import speiger.src.collections.PACKAGE.utils.ARRAYS;
-import speiger.src.collections.objects.utils.ObjectArrays;
-#if TYPE_OBJECT
-import speiger.src.collections.utils.Stack;
-#endif
-#if PRIMITIVES
-import java.util.stream.JAVA_STREAM;
-import java.util.stream.StreamSupport;
-#endif
-import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR;
-import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
-import speiger.src.collections.utils.SanityChecks;
-
-/**
- * A Type-Specific LinkedList implementation of list that is written to reduce (un)boxing
- * 
-#if TYPE_OBJECT
- * 

This implementation is optimized to improve how data is processed with interfaces like {@link Stack} -#else - *

This implementation is optimized to improve how data is processed with interfaces like {@link STACK} -#endif - * and with optimized functions that use type-specific implementations for primitives and optimized logic for bulk actions. - * - * @Type(T) - */ -#if DEQUEUE_FEATURE -public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE implements PRIORITY_DEQUEUE KEY_GENERIC_TYPE, STACK KEY_GENERIC_TYPE -#else -public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE implements STACK KEY_GENERIC_TYPE -#endif -{ - Entry KEY_GENERIC_TYPE first; - Entry KEY_GENERIC_TYPE last; - int size = 0; - - /** - * Creates a new LinkedList. - */ - public LINKED_LIST() { - } - - /** - * Creates a new LinkedList a copy with the contents of the Collection. - * @param c the elements that should be added into the list - */ - @Deprecated - public LINKED_LIST(Collection c) { - addAll(c); - } - - /** - * Creates a new LinkedList a copy with the contents of the Collection. - * @param c the elements that should be added into the list - */ - public LINKED_LIST(COLLECTION KEY_GENERIC_TYPE c) { - addAll(c); - } - - /** - * Creates a new LinkedList a copy with the contents of the List. - * @param l the elements that should be added into the list - */ - public LINKED_LIST(LIST KEY_GENERIC_TYPE l) { - addAll(l); - } - - /** - * Creates a new LinkedList with a Copy of the array - * @param a the array that should be copied - */ - public LINKED_LIST(KEY_TYPE... a) { - for(int i = 0,m=a.length;i c) { - if(c instanceof COLLECTION) return addAll(index, (COLLECTION KEY_GENERIC_TYPE)c); - int length = c.size(); - if(length == 0) return false; - checkAddRange(index); - Entry KEY_GENERIC_TYPE next; - Entry KEY_GENERIC_TYPE prev; - if(index == size) { - prev = last; - next = null; - } - else if(index == 0) { - next = first; - prev = null; - } - else { - next = getNode(index); - prev = next.prev; - } - for(Iterator iter = c.iterator();iter.hasNext();) { - Entry KEY_GENERIC_TYPE entry = new EntryBRACES(OBJ_TO_KEY(iter.next()), prev, null); - if(prev == null) first = entry; - else prev.next = entry; - prev = entry; - } - if(next == null) last = prev; - else { - prev.next = next; - next.prev = prev; - } - size += length; - return true; - } - -#if DEQUEUE_FEATURE - @Override - public void enqueue(KEY_TYPE e) { - add(e); - } - - @Override - public void enqueueFirst(KEY_TYPE e) { - add(0, e); - } - -#endif - @Override - public void push(KEY_TYPE e) { - add(e); - } - - @Override - public boolean addAll(KEY_TYPE[] e, int offset, int length) { - if(length <= 0) return false; - SanityChecks.checkArrayCapacity(e.length, offset, length); - for(int i = 0;i 0) { - a[offset++] = entry.value; - length--; - entry = entry.next; - } - return a; - } - -#if DEQUEUE_FEATURE - @Override - public KEY_TYPE first() { - if(first == null) throw new NoSuchElementException(); - return first.value; - } - - @Override - public KEY_TYPE last() { - if(last == null) throw new NoSuchElementException(); - return last.value; - } - -#endif - @Override - public KEY_TYPE peek(int index) { - return GET_KEY((size() - 1) - index); - } - @Override - public KEY_TYPE GET_KEY(int index) { - checkRange(index); - return getNode(index).value; - } - - @Override - @Primitive - public boolean contains(Object e) { - return indexOf(e) != -1; - } - - @Override - @Primitive - public int indexOf(Object o) { - Entry KEY_GENERIC_TYPE entry = first; - for(int i = 0;entry != null;entry = entry.next,i++) { - if(Objects.equals(KEY_TO_OBJ(entry.value), o)) return i; - } - return -1; - } - - @Override - @Primitive - public int lastIndexOf(Object o) { - Entry KEY_GENERIC_TYPE entry = last; - for(int i = size-1;entry != null;entry = entry.prev,i--) { - if(Objects.equals(KEY_TO_OBJ(entry.value), o)) return i; - } - return -1; - } - -#if !TYPE_OBJECT - @Override - public boolean contains(KEY_TYPE e) { - return indexOf(e) != -1; - } - - @Override - public int indexOf(KEY_TYPE e) { - Entry entry = first; - for(int i = 0;entry != null;entry = entry.next,i++) { - if(KEY_EQUALS(entry.value, e)) return i; - } - return -1; - } - - @Override - public int lastIndexOf(KEY_TYPE e) { - Entry entry = last; - for(int i = size-1;entry != null;entry = entry.prev,i--) { - if(KEY_EQUALS(entry.value, e)) return i; - } - return -1; - } - -#endif - @Override - public LIST_ITERATOR KEY_GENERIC_TYPE listIterator(int index) { - if(index < 0 || index > size()) throw new IndexOutOfBoundsException(); - if(index == size) return new ListIter(null, index); - if(index == 0) return new ListIter(first, index); - return new ListIter(getNode(index), index); - } - -#if PRIMITIVES - /** - * Returns a Java-Type-Specific Stream to reduce boxing/unboxing. - * @return a Stream of the closest java type - */ - public JAVA_STREAM primitiveStream() { return StreamSupport.NEW_STREAM(new SplitIterator(this, first, 0), false); } - - /** - * Returns a Java-Type-Specific Parallel Stream to reduce boxing/unboxing. - * @return a Stream of the closest java type - */ - public JAVA_STREAM parallelPrimitiveStream() { return StreamSupport.NEW_STREAM(new SplitIterator(this, first, 0), true); } -#endif - /** - * A Type Specific Type Splititerator to reduce boxing/unboxing - * @return type specific splititerator - */ - @Override - public SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return new TypeSplitIteratorBRACES(this, first, 0); } - - @Override - public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { - Objects.requireNonNull(action); - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { - action.accept(entry.value); - } - } - - @Override - public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) { - Objects.requireNonNull(action); - int index = 0; - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) - action.accept(index++, entry.value); - } - - @Override - public void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { - Objects.requireNonNull(action); - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) - action.accept(input, entry.value); - } - - @Override - public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { - if(filter.test(entry.value)) return true; - } - return false; - } - - @Override - public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { - if(filter.test(entry.value)) return false; - } - return true; - } - - @Override - public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { - if(!filter.test(entry.value)) return false; - } - return true; - } - - @Override - public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { - if(filter.test(entry.value)) return entry.value; - } - return EMPTY_VALUE; - } - -#if !TYPE_OBJECT - @Override - public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - KEY_TYPE state = identity; - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { - state = operator.APPLY_VALUE(state, entry.value); - } - return state; - } - -#else - @Override - public KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) { - Objects.requireNonNull(operator); - KEY_SPECIAL_TYPE state = identity; - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { - state = operator.APPLY_VALUE(state, entry.value); - } - return state; - } - -#endif - @Override - public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - KEY_TYPE state = EMPTY_VALUE; - boolean empty = true; - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { - if(empty) { - empty = false; - state = entry.value; - continue; - } - state = operator.APPLY_VALUE(state, entry.value); - } - return state; - } - - @Override - public int count(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - int result = 0; - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { - if(filter.test(entry.value)) result++; - } - return result; - } - - @Override - public KEY_TYPE set(int index, KEY_TYPE e) { - checkRange(index); - Entry KEY_GENERIC_TYPE node = getNode(index); - KEY_TYPE prev = node.value; - node.value = e; - return prev; - } - - @Override - @Primitive - public void replaceAll(UnaryOperator o) { - Objects.requireNonNull(o); - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { - entry.value = OBJ_TO_KEY(o.apply(KEY_TO_OBJ(entry.value))); - } - } - -#if PRIMITIVES - @Override - public void REPLACE(JAVA_UNARY_OPERATOR o) { - Objects.requireNonNull(o); - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { -#if TYPE_BYTE || TYPE_SHORT || TYPE_CHAR || TYPE_FLOAT - entry.value = SanityChecks.SANITY_CAST(o.APPLY_CAST(entry.value)); -#else - entry.value = o.APPLY(entry.value); -#endif - } - } - -#endif -#if DEQUEUE_FEATURE - @Override - public void onChanged() {} - @Override - public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; } - - @Override - public KEY_TYPE dequeue() { - if(first == null) throw new NoSuchElementException(); - return unlinkFirst(first); - } - - @Override - public KEY_TYPE dequeueLast() { - return pop(); - } - -#endif - @Override - public KEY_TYPE pop() { - if(last == null) throw new NoSuchElementException(); - return unlinkLast(last); - } - -#if DEQUEUE_FEATURE - @Override - public boolean removeFirst(KEY_TYPE e) { -#if TYPE_OBJECT - return remove(e); -#else - return REMOVE_KEY(e); -#endif - } - - @Override - public boolean removeLast(KEY_TYPE e) { - if(size == 0) return false; - for(Entry KEY_GENERIC_TYPE entry = last;entry != null;entry = entry.prev) { - if(KEY_EQUALS(entry.value, e)) { - unlink(entry); - return true; - } - } - return false; - } - -#endif - @Override - public KEY_TYPE swapRemove(int index) { - checkRange(index); - Entry KEY_GENERIC_TYPE entry = getNode(index); - if(entry == null) return EMPTY_KEY_VALUE; - if(entry.next == null) return unlinkLast(entry); - Entry KEY_GENERIC_TYPE before = entry.prev; - KEY_TYPE result = unlink(entry); - if(before == null) { - Entry KEY_GENERIC_TYPE temp = last; - last = temp.prev; - last.next = null; - temp.next = first; - temp.prev = null; - first.prev = temp; - first = temp; - return result; - } - else if(before.next != last) { - Entry KEY_GENERIC_TYPE temp = last; - last = temp.prev; - last.next = null; - temp.next = before.next; - temp.prev = before; - before.next = temp; - temp.next.prev = temp; - } - return result; - } - - @Override - public boolean REMOVE_SWAP(KEY_TYPE e) { - if(size == 0) return false; - for(Entry KEY_GENERIC_TYPE entry = last;entry != null;entry = entry.prev) { - if(KEY_EQUALS(entry.value, e)) { - if(entry.next == null) { - unlinkLast(entry); - return true; - } - Entry KEY_GENERIC_TYPE before = entry.prev; - unlink(entry); - if(before == null) { - Entry KEY_GENERIC_TYPE temp = last; - last = temp.prev; - last.next = null; - temp.next = first; - temp.prev = null; - first.prev = temp; - first = temp; - return true; - } - else if(before.next != last) { - Entry KEY_GENERIC_TYPE temp = last; - last = temp.prev; - last.next = null; - temp.next = before.next; - temp.prev = before; - before.next = temp; - temp.next.prev = temp; - } - return true; - } - } - return false; - } - -#if TYPE_OBJECT - @Override - public boolean remove(Object e) { - if(size <= 0) return false; - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { - if(KEY_EQUALS(entry.value, e)) { - unlink(entry); - return true; - } - } - return false; - } - -#else - @Override - public boolean REMOVE_KEY(KEY_TYPE e) { - if(size == 0) return false; - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { - if(KEY_EQUALS(entry.value, e)) { - unlink(entry); - return true; - } - } - return false; - } - -#endif - @Override - public KEY_TYPE REMOVE(int index) { - checkRange(index); - Entry KEY_GENERIC_TYPE entry = getNode(index); - return entry == null ? EMPTY_KEY_VALUE : unlink(entry); - } - - @Override - public void removeElements(int from, int to) { - checkRange(from); - checkAddRange(to); - int length = to - from; - if(length <= 0) return; - if(from < size - to) { - Entry KEY_GENERIC_TYPE entry = getNode(from); - while(length > 0) { - Entry KEY_GENERIC_TYPE next = entry.next; - unlink(entry); - entry = next; - length--; - } - return; - } - Entry KEY_GENERIC_TYPE entry = getNode(to-1); - while(length > 0) { - Entry KEY_GENERIC_TYPE prev = entry.prev; - unlink(entry); - entry = prev; - length--; - } - } - -#if TYPE_OBJECT - @Override - public K[] extractElements(int from, int to, Class type) { - checkRange(from); - checkAddRange(to); - int length = to - from; - if(length <= 0) return ARRAYS.newArray(type, 0); - K[] a = ARRAYS.newArray(type, length); - if(from < size - to) { - Entry KEY_GENERIC_TYPE entry = getNode(from); - for(int i = 0;length > 0;i++, length--) { - Entry KEY_GENERIC_TYPE next = entry.next; - a[i] = (K)unlink(entry); - entry = next; - } - return a; - } - Entry KEY_GENERIC_TYPE entry = getNode(to-1); - for(int i = length-1;length > 0;i--, length--) { - Entry KEY_GENERIC_TYPE prev = entry.prev; - a[i] = (K)unlink(entry); - entry = prev; - } - return a; - } - -#else - @Override - public KEY_TYPE[] extractElements(int from, int to) { - checkRange(from); - checkAddRange(to); - int length = to - from; - if(length <= 0) return ARRAYS.EMPTY_ARRAY; - KEY_TYPE[] d = new KEY_TYPE[length]; - if(from < size - to) { - Entry KEY_GENERIC_TYPE entry = getNode(from); - for(int i = 0;length > 0;i++, length--) { - Entry KEY_GENERIC_TYPE next = entry.next; - d[i] = unlink(entry); - entry = next; - } - return d; - } - Entry KEY_GENERIC_TYPE entry = getNode(to-1); - for(int i = length-1;length > 0;i--, length--) { - Entry KEY_GENERIC_TYPE prev = entry.prev; - d[i] = unlink(entry); - entry = prev; - } - return d; - } - -#endif -#if PRIMITIVES - @Override - public void fillBuffer(JAVA_BUFFER buffer) { - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) - buffer.put(entry.value); - } - -#endif - @Override - @Primitive - public boolean removeAll(Collection c) { - if(c.isEmpty()) return false; - boolean modified = false; - int j = 0; - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;) { - if(c.contains(KEY_TO_OBJ(entry.value))) { - Entry KEY_GENERIC_TYPE next = entry.next; - unlink(entry); - entry = next; - modified = true; - continue; - } - else j++; - entry = entry.next; - } - size = j; - return modified; - } - - @Override - @Primitive - public boolean retainAll(Collection c) { - if(c.isEmpty()) { - boolean changed = size > 0; - clear(); - return changed; - } - boolean modified = false; - int j = 0; - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;) { - if(!c.contains(KEY_TO_OBJ(entry.value))) { - Entry KEY_GENERIC_TYPE next = entry.next; - unlink(entry); - entry = next; - modified = true; - continue; - } - else j++; - entry = entry.next; - } - size = j; - return modified; - } - - @Override - public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) { - if(c.isEmpty()) return false; - boolean modified = false; - int j = 0; - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;) { - if(c.contains(entry.value)) { - Entry KEY_GENERIC_TYPE next = entry.next; - unlink(entry); - entry = next; - modified = true; - continue; - } - else j++; - entry = entry.next; - } - size = j; - return modified; - } - - @Override - public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { - if(c.isEmpty()) return false; - boolean modified = false; - int j = 0; - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;) { - if(c.contains(entry.value)) { - r.accept(entry.value); - Entry KEY_GENERIC_TYPE next = entry.next; - unlink(entry); - entry = next; - modified = true; - continue; - } - else j++; - entry = entry.next; - } - size = j; - return modified; - } - - @Override - public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) { - if(c.isEmpty()) { - boolean changed = size > 0; - clear(); - return changed; - } - boolean modified = false; - int j = 0; - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;) { - if(!c.contains(entry.value)) { - Entry KEY_GENERIC_TYPE next = entry.next; - unlink(entry); - entry = next; - modified = true; - continue; - } - else j++; - entry = entry.next; - } - size = j; - return modified; - } - - @Override - public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { - if(c.isEmpty()) { - boolean changed = size > 0; - forEach(r); - clear(); - return changed; - } - boolean modified = false; - int j = 0; - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;) { - if(!c.contains(entry.value)) { - r.accept(entry.value); - Entry KEY_GENERIC_TYPE next = entry.next; - unlink(entry); - entry = next; - modified = true; - continue; - } - else j++; - entry = entry.next; - } - size = j; - return modified; - } - - @Override - @Primitive - public boolean removeIf(Predicate filter) { - Objects.requireNonNull(filter); - boolean modified = false; - int j = 0; - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;) { - if(filter.test(KEY_TO_OBJ(entry.value))) { - Entry KEY_GENERIC_TYPE next = entry.next; - unlink(entry); - entry = next; - modified = true; - continue; - } - else j++; - entry = entry.next; - } - size = j; - return modified; - } - -#if PRIMITIVES - @Override - public boolean remIf(JAVA_PREDICATE filter) { - boolean modified = false; - int j = 0; - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;) { - if(filter.test(entry.value)) { - Entry KEY_GENERIC_TYPE next = entry.next; - unlink(entry); - entry = next; - modified = true; - continue; - } - else j++; - entry = entry.next; - } - size = j; - return modified; - } - -#endif - @Override - public Object[] toArray() { - if(size == 0) return ObjectArrays.EMPTY_ARRAY; - Object[] obj = new Object[size]; - int i = 0; - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { - obj[i++] = KEY_TO_OBJ(entry.value); - } - return obj; - } - - @Override - public E[] toArray(E[] a) { - if(a == null) a = (E[])new Object[size]; - else if(a.length < size) a = (E[])ObjectArrays.newArray(a.getClass().getComponentType(), size); - int i = 0; - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { - a[i++] = (E)KEY_TO_OBJ(entry.value); - } - if (a.length > size) a[size] = null; - return a; - } - -#if !TYPE_OBJECT - @Override - public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) { - if(a.length < size) a = new KEY_TYPE[size]; - int i = 0; - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { - a[i++] = entry.value; - } - if (a.length > size) a[size] = EMPTY_KEY_VALUE; - return a; - } - -#else - @Override - public E[] toArray(IntFunction action) { - return super.toArray(action); - } - -#endif - @Override - public int size() { - return size; - } - - @Override - public void clear() { - for(Entry KEY_GENERIC_TYPE entry = first;entry != null;) { - Entry KEY_GENERIC_TYPE next = entry.next; - entry.next = entry.prev = null; - entry = next; - } - first = null; - last = null; - size = 0; - } - - @Override - public LINKED_LIST KEY_GENERIC_TYPE copy() { - LINKED_LIST KEY_GENERIC_TYPE list = new LINKED_LISTBRACES(); - list.size = size; - if(first != null) { - list.first = new EntryBRACES(first.value, null, null); - Entry KEY_GENERIC_TYPE lastReturned = list.first; - for(Entry KEY_GENERIC_TYPE entry = first.next;entry != null;entry = entry.next) { - Entry KEY_GENERIC_TYPE next = new EntryBRACES(entry.value, lastReturned, null); - lastReturned.next = next; - lastReturned = next; - } - list.last = lastReturned; - } - return list; - } - - protected Entry KEY_GENERIC_TYPE getNode(int index) { - if(index < size >> 2) { - Entry KEY_GENERIC_TYPE x = first; - for (int i = 0; i < index; i++) - x = x.next; - return x; - } - Entry KEY_GENERIC_TYPE x = last; - for (int i = size - 1; i > index; i--) - x = x.prev; - return x; - } - - protected void linkFirst(KEY_TYPE e) { - Entry KEY_GENERIC_TYPE f = first; - Entry KEY_GENERIC_TYPE newNode = new EntryBRACES(e, null, f); - first = newNode; - if (f == null) last = newNode; - else f.prev = newNode; - size++; - } - - protected void linkLast(KEY_TYPE e) { - Entry KEY_GENERIC_TYPE l = last; - Entry KEY_GENERIC_TYPE newNode = new EntryBRACES(e, l, null); - last = newNode; - if (l == null) first = newNode; - else l.next = newNode; - size++; - } - - protected void linkBefore(KEY_TYPE e, Entry KEY_GENERIC_TYPE succ) { - Entry KEY_GENERIC_TYPE prev = succ.prev; - Entry KEY_GENERIC_TYPE newNode = new EntryBRACES(e, prev, succ); - succ.prev = newNode; - if (prev == null) first = newNode; - else prev.next = newNode; - size++; - } - - protected KEY_TYPE unlinkFirst(Entry KEY_GENERIC_TYPE f) { - KEY_TYPE element = f.value; - Entry KEY_GENERIC_TYPE next = f.next; - f.next = null; -#if TYPE_OBJECT - f.value = null; -#endif - first = next; - if (next == null) last = null; - else next.prev = null; - size--; - return element; - } - - protected KEY_TYPE unlinkLast(Entry KEY_GENERIC_TYPE l) { - KEY_TYPE element = l.value; - Entry KEY_GENERIC_TYPE prev = l.prev; - l.prev = null; -#if TYPE_OBJECT - l.value = null; -#endif - last = prev; - if (prev == null) first = null; - else prev.next = null; - size--; - return element; - } - - protected KEY_TYPE unlink(Entry KEY_GENERIC_TYPE x) { - KEY_TYPE element = x.value; - Entry KEY_GENERIC_TYPE next = x.next; - Entry KEY_GENERIC_TYPE prev = x.prev; -#if TYPE_OBJECT - x.value = null; -#endif - if (prev == null) first = next; - else { - prev.next = next; - x.prev = null; - } - if (next == null) last = prev; - else { - next.prev = prev; - x.next = null; - } - size--; - return element; - } - - protected void checkRange(int index) { - if (index < 0 || index >= size) - throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); - } - - protected void checkAddRange(int index) { - if (index < 0 || index > size) - throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); - } - - protected static class Entry KEY_GENERIC_TYPE { - KEY_TYPE value; - Entry KEY_GENERIC_TYPE prev; - Entry KEY_GENERIC_TYPE next; - - public Entry(KEY_TYPE value, Entry KEY_GENERIC_TYPE prev, Entry KEY_GENERIC_TYPE next) - { - this.value = value; - this.prev = prev; - this.next = next; - } - - @Override - public String toString() { - return KEY_TO_STRING(value); - } - } - - private class ListIter implements LIST_ITERATOR KEY_GENERIC_TYPE - { - Entry KEY_GENERIC_TYPE next; - Entry KEY_GENERIC_TYPE lastReturned; - int index; - - ListIter(Entry KEY_GENERIC_TYPE next, int index) { - this.next = next; - this.index = index; - } - - @Override - public boolean hasNext() { - return index < size; - } - - @Override - public boolean hasPrevious() { - return index > 0; - } - - @Override - public int nextIndex() { - return index; - } - - @Override - public int previousIndex() { - return index-1; - } - - @Override - public void remove() { - if(lastReturned == null) throw new IllegalStateException(); - Entry KEY_GENERIC_TYPE lastNext = lastReturned.next; - unlink(lastReturned); - if (next == lastReturned) next = lastNext; - else index--; - lastReturned = null; - } - - @Override - public KEY_TYPE PREVIOUS() { - if(!hasPrevious()) throw new NoSuchElementException(); - lastReturned = next = (next == null) ? last : next.prev; - index--; - return lastReturned.value; - } - - @Override - public KEY_TYPE NEXT() { - if(!hasNext()) throw new NoSuchElementException(); - lastReturned = next; - next = next.next; - index++; - return lastReturned.value; - } - - @Override - public void set(KEY_TYPE e) { - if(lastReturned == null) throw new IllegalStateException(); - lastReturned.value = e; - } - - @Override - public void add(KEY_TYPE e) { - lastReturned = null; - if (next == null) linkLast(e); - else linkBefore(e, next); - index++; - } - } - - private static class TypeSplitIterator KEY_GENERIC_TYPE implements SPLIT_ITERATOR KEY_GENERIC_TYPE - { - static final int BATCH_UNIT = 1 << 10; - static final int MAX_BATCH = 1 << 25; - LINKED_LIST KEY_GENERIC_TYPE list; - Entry KEY_GENERIC_TYPE entry; - int index; - - TypeSplitIterator(LINKED_LIST KEY_GENERIC_TYPE list, Entry KEY_GENERIC_TYPE entry, int index) - { - this.list = list; - this.entry = entry; - this.index = index; - } - - @Override - public SPLIT_ITERATOR KEY_GENERIC_TYPE trySplit() { - if(entry == null && estimateSize() > 0) { - int size = Math.min(Math.min(index + BATCH_UNIT, MAX_BATCH), list.size) - index; - if(size <= 0) return null; - KEY_TYPE[] data = NEW_KEY_ARRAY(size); - int subSize = 0; - for(;subSize action) { - if(hasNext()) { - action.accept(KEY_TO_OBJ(NEXT())); - return true; - } - return false; - } - - @Override - public long estimateSize() { - return (long)list.size - (long)index; - } - - @Override - public int characteristics() { - return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED; - } - - @Override - public KEY_TYPE NEXT() { - KEY_TYPE value = entry.value; - entry = entry.next; - index++; - return value; - } - - @Override - public boolean hasNext() { - return entry != null; - } - } - -#if PRIMITIVES - private static class SplitIterator KEY_GENERIC_TYPE implements JAVA_SPLIT_ITERATOR KEY_GENERIC_TYPE - { - static final int BATCH_UNIT = 1 << 10; - static final int MAX_BATCH = 1 << 25; - LINKED_LIST KEY_GENERIC_TYPE list; - Entry entry; - int index; - - SplitIterator(LINKED_LIST KEY_GENERIC_TYPE list, Entry entry, int index) - { - this.list = list; - this.entry = entry; - this.index = index; - } - - @Override - public JAVA_SPLIT_ITERATOR KEY_GENERIC_TYPE trySplit() { - if(entry == null && estimateSize() > 0) { - int size = Math.min(Math.min(index + BATCH_UNIT, MAX_BATCH), list.size) - index; - if(size <= 0) return null; - KEY_TYPE[] data = new KEY_TYPE[size]; - int subSize = 0; - for(;subSizeThis implementation is optimized to improve how data is processed with interfaces like {@link Stack} +#else + *

This implementation is optimized to improve how data is processed with interfaces like {@link STACK} +#endif + * and with optimized functions that use type-specific implementations for primitives and optimized logic for bulk actions. + * + * @Type(T) + */ +#if DEQUEUE_FEATURE +public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE implements PRIORITY_DEQUEUE KEY_GENERIC_TYPE, STACK KEY_GENERIC_TYPE +#else +public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE implements STACK KEY_GENERIC_TYPE +#endif +{ + Entry KEY_GENERIC_TYPE first; + Entry KEY_GENERIC_TYPE last; + int size = 0; + + /** + * Creates a new LinkedList. + */ + public LINKED_LIST() { + } + + /** + * Creates a new LinkedList a copy with the contents of the Collection. + * @param c the elements that should be added into the list + */ + @Deprecated + public LINKED_LIST(Collection c) { + addAll(c); + } + + /** + * Creates a new LinkedList a copy with the contents of the Collection. + * @param c the elements that should be added into the list + */ + public LINKED_LIST(COLLECTION KEY_GENERIC_TYPE c) { + addAll(c); + } + + /** + * Creates a new LinkedList a copy with the contents of the List. + * @param l the elements that should be added into the list + */ + public LINKED_LIST(LIST KEY_GENERIC_TYPE l) { + addAll(l); + } + + /** + * Creates a new LinkedList with a Copy of the array + * @param a the array that should be copied + */ + public LINKED_LIST(KEY_TYPE... a) { + for(int i = 0,m=a.length;i c) { + if(c instanceof COLLECTION) return addAll(index, (COLLECTION KEY_GENERIC_TYPE)c); + int length = c.size(); + if(length == 0) return false; + checkAddRange(index); + Entry KEY_GENERIC_TYPE next; + Entry KEY_GENERIC_TYPE prev; + if(index == size) { + prev = last; + next = null; + } + else if(index == 0) { + next = first; + prev = null; + } + else { + next = getNode(index); + prev = next.prev; + } + for(Iterator iter = c.iterator();iter.hasNext();) { + Entry KEY_GENERIC_TYPE entry = new EntryBRACES(OBJ_TO_KEY(iter.next()), prev, null); + if(prev == null) first = entry; + else prev.next = entry; + prev = entry; + } + if(next == null) last = prev; + else { + prev.next = next; + next.prev = prev; + } + size += length; + return true; + } + +#if DEQUEUE_FEATURE + @Override + public void enqueue(KEY_TYPE e) { + add(e); + } + + @Override + public void enqueueFirst(KEY_TYPE e) { + add(0, e); + } + +#endif + @Override + public void push(KEY_TYPE e) { + add(e); + } + + @Override + public boolean addAll(KEY_TYPE[] e, int offset, int length) { + if(length <= 0) return false; + SanityChecks.checkArrayCapacity(e.length, offset, length); + for(int i = 0;i 0) { + a[offset++] = entry.value; + length--; + entry = entry.next; + } + return a; + } + +#if DEQUEUE_FEATURE + @Override + public KEY_TYPE first() { + if(first == null) throw new NoSuchElementException(); + return first.value; + } + + @Override + public KEY_TYPE last() { + if(last == null) throw new NoSuchElementException(); + return last.value; + } + +#endif + @Override + public KEY_TYPE peek(int index) { + return GET_KEY((size() - 1) - index); + } + @Override + public KEY_TYPE GET_KEY(int index) { + checkRange(index); + return getNode(index).value; + } + + @Override + @Primitive + public boolean contains(Object e) { + return indexOf(e) != -1; + } + + @Override + @Primitive + public int indexOf(Object o) { + Entry KEY_GENERIC_TYPE entry = first; + for(int i = 0;entry != null;entry = entry.next,i++) { + if(Objects.equals(KEY_TO_OBJ(entry.value), o)) return i; + } + return -1; + } + + @Override + @Primitive + public int lastIndexOf(Object o) { + Entry KEY_GENERIC_TYPE entry = last; + for(int i = size-1;entry != null;entry = entry.prev,i--) { + if(Objects.equals(KEY_TO_OBJ(entry.value), o)) return i; + } + return -1; + } + +#if !TYPE_OBJECT + @Override + public boolean contains(KEY_TYPE e) { + return indexOf(e) != -1; + } + + @Override + public int indexOf(KEY_TYPE e) { + Entry entry = first; + for(int i = 0;entry != null;entry = entry.next,i++) { + if(KEY_EQUALS(entry.value, e)) return i; + } + return -1; + } + + @Override + public int lastIndexOf(KEY_TYPE e) { + Entry entry = last; + for(int i = size-1;entry != null;entry = entry.prev,i--) { + if(KEY_EQUALS(entry.value, e)) return i; + } + return -1; + } + +#endif + @Override + public LIST_ITERATOR KEY_GENERIC_TYPE listIterator(int index) { + if(index < 0 || index > size()) throw new IndexOutOfBoundsException(); + if(index == size) return new ListIter(null, index); + if(index == 0) return new ListIter(first, index); + return new ListIter(getNode(index), index); + } + +#if PRIMITIVES + /** + * Returns a Java-Type-Specific Stream to reduce boxing/unboxing. + * @return a Stream of the closest java type + */ + public JAVA_STREAM primitiveStream() { return StreamSupport.NEW_STREAM(new SplitIterator(this, first, 0), false); } + + /** + * Returns a Java-Type-Specific Parallel Stream to reduce boxing/unboxing. + * @return a Stream of the closest java type + */ + public JAVA_STREAM parallelPrimitiveStream() { return StreamSupport.NEW_STREAM(new SplitIterator(this, first, 0), true); } +#endif + /** + * A Type Specific Type Splititerator to reduce boxing/unboxing + * @return type specific splititerator + */ + @Override + public SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return new TypeSplitIteratorBRACES(this, first, 0); } + + @Override + public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { + Objects.requireNonNull(action); + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { + action.accept(entry.value); + } + } + + @Override + public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) { + Objects.requireNonNull(action); + int index = 0; + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) + action.accept(index++, entry.value); + } + + @Override + public void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { + Objects.requireNonNull(action); + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) + action.accept(input, entry.value); + } + + @Override + public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { + if(filter.test(entry.value)) return true; + } + return false; + } + + @Override + public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { + if(filter.test(entry.value)) return false; + } + return true; + } + + @Override + public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { + if(!filter.test(entry.value)) return false; + } + return true; + } + + @Override + public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { + if(filter.test(entry.value)) return entry.value; + } + return EMPTY_VALUE; + } + +#if !TYPE_OBJECT + @Override + public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + KEY_TYPE state = identity; + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { + state = operator.APPLY_VALUE(state, entry.value); + } + return state; + } + +#else + @Override + public KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) { + Objects.requireNonNull(operator); + KEY_SPECIAL_TYPE state = identity; + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { + state = operator.APPLY_VALUE(state, entry.value); + } + return state; + } + +#endif + @Override + public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + KEY_TYPE state = EMPTY_VALUE; + boolean empty = true; + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { + if(empty) { + empty = false; + state = entry.value; + continue; + } + state = operator.APPLY_VALUE(state, entry.value); + } + return state; + } + + @Override + public int count(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + int result = 0; + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { + if(filter.test(entry.value)) result++; + } + return result; + } + + @Override + public KEY_TYPE set(int index, KEY_TYPE e) { + checkRange(index); + Entry KEY_GENERIC_TYPE node = getNode(index); + KEY_TYPE prev = node.value; + node.value = e; + return prev; + } + + @Override + @Primitive + public void replaceAll(UnaryOperator o) { + Objects.requireNonNull(o); + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { + entry.value = OBJ_TO_KEY(o.apply(KEY_TO_OBJ(entry.value))); + } + } + +#if PRIMITIVES + @Override + public void REPLACE(JAVA_UNARY_OPERATOR o) { + Objects.requireNonNull(o); + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { +#if TYPE_BYTE || TYPE_SHORT || TYPE_CHAR || TYPE_FLOAT + entry.value = SanityChecks.SANITY_CAST(o.APPLY_CAST(entry.value)); +#else + entry.value = o.APPLY(entry.value); +#endif + } + } + +#endif +#if DEQUEUE_FEATURE + @Override + public void onChanged() {} + @Override + public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; } + + @Override + public KEY_TYPE dequeue() { + if(first == null) throw new NoSuchElementException(); + return unlinkFirst(first); + } + + @Override + public KEY_TYPE dequeueLast() { + return pop(); + } + +#endif + @Override + public KEY_TYPE pop() { + if(last == null) throw new NoSuchElementException(); + return unlinkLast(last); + } + +#if DEQUEUE_FEATURE + @Override + public boolean removeFirst(KEY_TYPE e) { +#if TYPE_OBJECT + return remove(e); +#else + return REMOVE_KEY(e); +#endif + } + + @Override + public boolean removeLast(KEY_TYPE e) { + if(size == 0) return false; + for(Entry KEY_GENERIC_TYPE entry = last;entry != null;entry = entry.prev) { + if(KEY_EQUALS(entry.value, e)) { + unlink(entry); + return true; + } + } + return false; + } + +#endif + @Override + public KEY_TYPE swapRemove(int index) { + checkRange(index); + Entry KEY_GENERIC_TYPE entry = getNode(index); + if(entry == null) return EMPTY_KEY_VALUE; + if(entry.next == null) return unlinkLast(entry); + Entry KEY_GENERIC_TYPE before = entry.prev; + KEY_TYPE result = unlink(entry); + if(before == null) { + Entry KEY_GENERIC_TYPE temp = last; + last = temp.prev; + last.next = null; + temp.next = first; + temp.prev = null; + first.prev = temp; + first = temp; + return result; + } + else if(before.next != last) { + Entry KEY_GENERIC_TYPE temp = last; + last = temp.prev; + last.next = null; + temp.next = before.next; + temp.prev = before; + before.next = temp; + temp.next.prev = temp; + } + return result; + } + + @Override + public boolean REMOVE_SWAP(KEY_TYPE e) { + if(size == 0) return false; + for(Entry KEY_GENERIC_TYPE entry = last;entry != null;entry = entry.prev) { + if(KEY_EQUALS(entry.value, e)) { + if(entry.next == null) { + unlinkLast(entry); + return true; + } + Entry KEY_GENERIC_TYPE before = entry.prev; + unlink(entry); + if(before == null) { + Entry KEY_GENERIC_TYPE temp = last; + last = temp.prev; + last.next = null; + temp.next = first; + temp.prev = null; + first.prev = temp; + first = temp; + return true; + } + else if(before.next != last) { + Entry KEY_GENERIC_TYPE temp = last; + last = temp.prev; + last.next = null; + temp.next = before.next; + temp.prev = before; + before.next = temp; + temp.next.prev = temp; + } + return true; + } + } + return false; + } + +#if TYPE_OBJECT + @Override + public boolean remove(Object e) { + if(size <= 0) return false; + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { + if(KEY_EQUALS(entry.value, e)) { + unlink(entry); + return true; + } + } + return false; + } + +#else + @Override + public boolean REMOVE_KEY(KEY_TYPE e) { + if(size == 0) return false; + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { + if(KEY_EQUALS(entry.value, e)) { + unlink(entry); + return true; + } + } + return false; + } + +#endif + @Override + public KEY_TYPE REMOVE(int index) { + checkRange(index); + Entry KEY_GENERIC_TYPE entry = getNode(index); + return entry == null ? EMPTY_KEY_VALUE : unlink(entry); + } + + @Override + public void removeElements(int from, int to) { + checkRange(from); + checkAddRange(to); + int length = to - from; + if(length <= 0) return; + if(from < size - to) { + Entry KEY_GENERIC_TYPE entry = getNode(from); + while(length > 0) { + Entry KEY_GENERIC_TYPE next = entry.next; + unlink(entry); + entry = next; + length--; + } + return; + } + Entry KEY_GENERIC_TYPE entry = getNode(to-1); + while(length > 0) { + Entry KEY_GENERIC_TYPE prev = entry.prev; + unlink(entry); + entry = prev; + length--; + } + } + +#if TYPE_OBJECT + @Override + public K[] extractElements(int from, int to, Class type) { + checkRange(from); + checkAddRange(to); + int length = to - from; + if(length <= 0) return ARRAYS.newArray(type, 0); + K[] a = ARRAYS.newArray(type, length); + if(from < size - to) { + Entry KEY_GENERIC_TYPE entry = getNode(from); + for(int i = 0;length > 0;i++, length--) { + Entry KEY_GENERIC_TYPE next = entry.next; + a[i] = (K)unlink(entry); + entry = next; + } + return a; + } + Entry KEY_GENERIC_TYPE entry = getNode(to-1); + for(int i = length-1;length > 0;i--, length--) { + Entry KEY_GENERIC_TYPE prev = entry.prev; + a[i] = (K)unlink(entry); + entry = prev; + } + return a; + } + +#else + @Override + public KEY_TYPE[] extractElements(int from, int to) { + checkRange(from); + checkAddRange(to); + int length = to - from; + if(length <= 0) return ARRAYS.EMPTY_ARRAY; + KEY_TYPE[] d = new KEY_TYPE[length]; + if(from < size - to) { + Entry KEY_GENERIC_TYPE entry = getNode(from); + for(int i = 0;length > 0;i++, length--) { + Entry KEY_GENERIC_TYPE next = entry.next; + d[i] = unlink(entry); + entry = next; + } + return d; + } + Entry KEY_GENERIC_TYPE entry = getNode(to-1); + for(int i = length-1;length > 0;i--, length--) { + Entry KEY_GENERIC_TYPE prev = entry.prev; + d[i] = unlink(entry); + entry = prev; + } + return d; + } + +#endif +#if PRIMITIVES + @Override + public void fillBuffer(JAVA_BUFFER buffer) { + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) + buffer.put(entry.value); + } + +#endif + @Override + @Primitive + public boolean removeAll(Collection c) { + if(c.isEmpty()) return false; + boolean modified = false; + int j = 0; + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;) { + if(c.contains(KEY_TO_OBJ(entry.value))) { + Entry KEY_GENERIC_TYPE next = entry.next; + unlink(entry); + entry = next; + modified = true; + continue; + } + else j++; + entry = entry.next; + } + size = j; + return modified; + } + + @Override + @Primitive + public boolean retainAll(Collection c) { + if(c.isEmpty()) { + boolean changed = size > 0; + clear(); + return changed; + } + boolean modified = false; + int j = 0; + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;) { + if(!c.contains(KEY_TO_OBJ(entry.value))) { + Entry KEY_GENERIC_TYPE next = entry.next; + unlink(entry); + entry = next; + modified = true; + continue; + } + else j++; + entry = entry.next; + } + size = j; + return modified; + } + + @Override + public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) { + if(c.isEmpty()) return false; + boolean modified = false; + int j = 0; + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;) { + if(c.contains(entry.value)) { + Entry KEY_GENERIC_TYPE next = entry.next; + unlink(entry); + entry = next; + modified = true; + continue; + } + else j++; + entry = entry.next; + } + size = j; + return modified; + } + + @Override + public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { + if(c.isEmpty()) return false; + boolean modified = false; + int j = 0; + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;) { + if(c.contains(entry.value)) { + r.accept(entry.value); + Entry KEY_GENERIC_TYPE next = entry.next; + unlink(entry); + entry = next; + modified = true; + continue; + } + else j++; + entry = entry.next; + } + size = j; + return modified; + } + + @Override + public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) { + if(c.isEmpty()) { + boolean changed = size > 0; + clear(); + return changed; + } + boolean modified = false; + int j = 0; + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;) { + if(!c.contains(entry.value)) { + Entry KEY_GENERIC_TYPE next = entry.next; + unlink(entry); + entry = next; + modified = true; + continue; + } + else j++; + entry = entry.next; + } + size = j; + return modified; + } + + @Override + public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { + if(c.isEmpty()) { + boolean changed = size > 0; + forEach(r); + clear(); + return changed; + } + boolean modified = false; + int j = 0; + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;) { + if(!c.contains(entry.value)) { + r.accept(entry.value); + Entry KEY_GENERIC_TYPE next = entry.next; + unlink(entry); + entry = next; + modified = true; + continue; + } + else j++; + entry = entry.next; + } + size = j; + return modified; + } + + @Override + @Primitive + public boolean removeIf(Predicate filter) { + Objects.requireNonNull(filter); + boolean modified = false; + int j = 0; + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;) { + if(filter.test(KEY_TO_OBJ(entry.value))) { + Entry KEY_GENERIC_TYPE next = entry.next; + unlink(entry); + entry = next; + modified = true; + continue; + } + else j++; + entry = entry.next; + } + size = j; + return modified; + } + +#if PRIMITIVES + @Override + public boolean remIf(JAVA_PREDICATE filter) { + boolean modified = false; + int j = 0; + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;) { + if(filter.test(entry.value)) { + Entry KEY_GENERIC_TYPE next = entry.next; + unlink(entry); + entry = next; + modified = true; + continue; + } + else j++; + entry = entry.next; + } + size = j; + return modified; + } + +#endif + @Override + public Object[] toArray() { + if(size == 0) return ObjectArrays.EMPTY_ARRAY; + Object[] obj = new Object[size]; + int i = 0; + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { + obj[i++] = KEY_TO_OBJ(entry.value); + } + return obj; + } + + @Override + public E[] toArray(E[] a) { + if(a == null) a = (E[])new Object[size]; + else if(a.length < size) a = (E[])ObjectArrays.newArray(a.getClass().getComponentType(), size); + int i = 0; + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { + a[i++] = (E)KEY_TO_OBJ(entry.value); + } + if (a.length > size) a[size] = null; + return a; + } + +#if !TYPE_OBJECT + @Override + public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) { + if(a.length < size) a = new KEY_TYPE[size]; + int i = 0; + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next) { + a[i++] = entry.value; + } + if (a.length > size) a[size] = EMPTY_KEY_VALUE; + return a; + } + +#else + @Override + public E[] toArray(IntFunction action) { + return super.toArray(action); + } + +#endif + @Override + public int size() { + return size; + } + + @Override + public void clear() { + for(Entry KEY_GENERIC_TYPE entry = first;entry != null;) { + Entry KEY_GENERIC_TYPE next = entry.next; + entry.next = entry.prev = null; + entry = next; + } + first = null; + last = null; + size = 0; + } + + @Override + public LINKED_LIST KEY_GENERIC_TYPE copy() { + LINKED_LIST KEY_GENERIC_TYPE list = new LINKED_LISTBRACES(); + list.size = size; + if(first != null) { + list.first = new EntryBRACES(first.value, null, null); + Entry KEY_GENERIC_TYPE lastReturned = list.first; + for(Entry KEY_GENERIC_TYPE entry = first.next;entry != null;entry = entry.next) { + Entry KEY_GENERIC_TYPE next = new EntryBRACES(entry.value, lastReturned, null); + lastReturned.next = next; + lastReturned = next; + } + list.last = lastReturned; + } + return list; + } + + protected Entry KEY_GENERIC_TYPE getNode(int index) { + if(index < size >> 2) { + Entry KEY_GENERIC_TYPE x = first; + for (int i = 0; i < index; i++) + x = x.next; + return x; + } + Entry KEY_GENERIC_TYPE x = last; + for (int i = size - 1; i > index; i--) + x = x.prev; + return x; + } + + protected void linkFirst(KEY_TYPE e) { + Entry KEY_GENERIC_TYPE f = first; + Entry KEY_GENERIC_TYPE newNode = new EntryBRACES(e, null, f); + first = newNode; + if (f == null) last = newNode; + else f.prev = newNode; + size++; + } + + protected void linkLast(KEY_TYPE e) { + Entry KEY_GENERIC_TYPE l = last; + Entry KEY_GENERIC_TYPE newNode = new EntryBRACES(e, l, null); + last = newNode; + if (l == null) first = newNode; + else l.next = newNode; + size++; + } + + protected void linkBefore(KEY_TYPE e, Entry KEY_GENERIC_TYPE succ) { + Entry KEY_GENERIC_TYPE prev = succ.prev; + Entry KEY_GENERIC_TYPE newNode = new EntryBRACES(e, prev, succ); + succ.prev = newNode; + if (prev == null) first = newNode; + else prev.next = newNode; + size++; + } + + protected KEY_TYPE unlinkFirst(Entry KEY_GENERIC_TYPE f) { + KEY_TYPE element = f.value; + Entry KEY_GENERIC_TYPE next = f.next; + f.next = null; +#if TYPE_OBJECT + f.value = null; +#endif + first = next; + if (next == null) last = null; + else next.prev = null; + size--; + return element; + } + + protected KEY_TYPE unlinkLast(Entry KEY_GENERIC_TYPE l) { + KEY_TYPE element = l.value; + Entry KEY_GENERIC_TYPE prev = l.prev; + l.prev = null; +#if TYPE_OBJECT + l.value = null; +#endif + last = prev; + if (prev == null) first = null; + else prev.next = null; + size--; + return element; + } + + protected KEY_TYPE unlink(Entry KEY_GENERIC_TYPE x) { + KEY_TYPE element = x.value; + Entry KEY_GENERIC_TYPE next = x.next; + Entry KEY_GENERIC_TYPE prev = x.prev; +#if TYPE_OBJECT + x.value = null; +#endif + if (prev == null) first = next; + else { + prev.next = next; + x.prev = null; + } + if (next == null) last = prev; + else { + next.prev = prev; + x.next = null; + } + size--; + return element; + } + + protected void checkRange(int index) { + if (index < 0 || index >= size) + throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); + } + + protected void checkAddRange(int index) { + if (index < 0 || index > size) + throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); + } + + protected static class Entry KEY_GENERIC_TYPE { + KEY_TYPE value; + Entry KEY_GENERIC_TYPE prev; + Entry KEY_GENERIC_TYPE next; + + public Entry(KEY_TYPE value, Entry KEY_GENERIC_TYPE prev, Entry KEY_GENERIC_TYPE next) + { + this.value = value; + this.prev = prev; + this.next = next; + } + + @Override + public String toString() { + return KEY_TO_STRING(value); + } + } + + private class ListIter implements LIST_ITERATOR KEY_GENERIC_TYPE + { + Entry KEY_GENERIC_TYPE next; + Entry KEY_GENERIC_TYPE lastReturned; + int index; + + ListIter(Entry KEY_GENERIC_TYPE next, int index) { + this.next = next; + this.index = index; + } + + @Override + public boolean hasNext() { + return index < size; + } + + @Override + public boolean hasPrevious() { + return index > 0; + } + + @Override + public int nextIndex() { + return index; + } + + @Override + public int previousIndex() { + return index-1; + } + + @Override + public void remove() { + if(lastReturned == null) throw new IllegalStateException(); + Entry KEY_GENERIC_TYPE lastNext = lastReturned.next; + unlink(lastReturned); + if (next == lastReturned) next = lastNext; + else index--; + lastReturned = null; + } + + @Override + public KEY_TYPE PREVIOUS() { + if(!hasPrevious()) throw new NoSuchElementException(); + lastReturned = next = (next == null) ? last : next.prev; + index--; + return lastReturned.value; + } + + @Override + public KEY_TYPE NEXT() { + if(!hasNext()) throw new NoSuchElementException(); + lastReturned = next; + next = next.next; + index++; + return lastReturned.value; + } + + @Override + public void set(KEY_TYPE e) { + if(lastReturned == null) throw new IllegalStateException(); + lastReturned.value = e; + } + + @Override + public void add(KEY_TYPE e) { + lastReturned = null; + if (next == null) linkLast(e); + else linkBefore(e, next); + index++; + } + } + + private static class TypeSplitIterator KEY_GENERIC_TYPE implements SPLIT_ITERATOR KEY_GENERIC_TYPE + { + static final int BATCH_UNIT = 1 << 10; + static final int MAX_BATCH = 1 << 25; + LINKED_LIST KEY_GENERIC_TYPE list; + Entry KEY_GENERIC_TYPE entry; + int index; + + TypeSplitIterator(LINKED_LIST KEY_GENERIC_TYPE list, Entry KEY_GENERIC_TYPE entry, int index) + { + this.list = list; + this.entry = entry; + this.index = index; + } + + @Override + public SPLIT_ITERATOR KEY_GENERIC_TYPE trySplit() { + if(entry == null && estimateSize() > 0) { + int size = Math.min(Math.min(index + BATCH_UNIT, MAX_BATCH), list.size) - index; + if(size <= 0) return null; + KEY_TYPE[] data = NEW_KEY_ARRAY(size); + int subSize = 0; + for(;subSize action) { + if(hasNext()) { + action.accept(KEY_TO_OBJ(NEXT())); + return true; + } + return false; + } + + @Override + public long estimateSize() { + return (long)list.size - (long)index; + } + + @Override + public int characteristics() { + return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED; + } + + @Override + public KEY_TYPE NEXT() { + KEY_TYPE value = entry.value; + entry = entry.next; + index++; + return value; + } + + @Override + public boolean hasNext() { + return entry != null; + } + } + +#if PRIMITIVES + private static class SplitIterator KEY_GENERIC_TYPE implements JAVA_SPLIT_ITERATOR KEY_GENERIC_TYPE + { + static final int BATCH_UNIT = 1 << 10; + static final int MAX_BATCH = 1 << 25; + LINKED_LIST KEY_GENERIC_TYPE list; + Entry entry; + int index; + + SplitIterator(LINKED_LIST KEY_GENERIC_TYPE list, Entry entry, int index) + { + this.list = list; + this.entry = entry; + this.index = index; + } + + @Override + public JAVA_SPLIT_ITERATOR KEY_GENERIC_TYPE trySplit() { + if(entry == null && estimateSize() > 0) { + int size = Math.min(Math.min(index + BATCH_UNIT, MAX_BATCH), list.size) - index; + if(size <= 0) return null; + KEY_TYPE[] data = new KEY_TYPE[size]; + int subSize = 0; + for(;subSizeGuavas approach and backing array implementations. - * Like Guavas implementation this solution can be accessed by multiple threads, but it is not as flexible as Javas implementation. - * The concurrencyLevel decides how many pools exist, and each pool can be accessed by 1 thread for writing and as many threads for reading. - * Though it is ill adviced to iterate over the collection using the Iterator if the Map is written to. Keep that in mind. - * - * - * @Type(T) - * @ValueType(V) - */ -public class CONCURRENT_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements CONCURRENT_MAP KEY_VALUE_GENERIC_TYPE, ITrimmable -{ - /** Segment Limit */ - private static final int MAX_SEGMENTS = 1 << 16; - /** Buckets of the ConcurrentMap */ - protected transient Segment KEY_VALUE_GENERIC_TYPE[] segments; - /** Bitshift of the HashCode */ - protected transient int segmentShift; - /** Max Bits thats used in the segments */ - protected transient int segmentMask; - /** EntrySet cache */ - protected transient FastEntrySet KEY_VALUE_GENERIC_TYPE entrySet; - /** KeySet cache */ - protected transient SET KEY_GENERIC_TYPE keySet; - /** Values cache */ - protected transient VALUE_COLLECTION VALUE_GENERIC_TYPE values; - - /** - * Copy constructor that doesn't trigger the building of segments and allows to copy it faster. - * @param unused not used, Just to keep all constructors accessible. - */ - protected CONCURRENT_HASH_MAP(boolean unused) {} - - /** - * Default Constructor - */ - public CONCURRENT_HASH_MAP() { - this(HashUtil.DEFAULT_MIN_CAPACITY, HashUtil.DEFAULT_LOAD_FACTOR, HashUtil.DEFAULT_MIN_CONCURRENCY); - } - - /** - * Constructor that defines the minimum capacity - * @param minCapacity the minimum capacity the HashMap is allowed to be. - * @throws IllegalStateException if the minimum capacity is negative - */ - public CONCURRENT_HASH_MAP(int minCapacity) { - this(minCapacity, HashUtil.DEFAULT_LOAD_FACTOR, HashUtil.DEFAULT_MIN_CONCURRENCY); - } - - /** - * Constructor that defines the minimum capacity and load factor - * @param minCapacity the minimum capacity the HashMap is allowed to be. - * @param loadFactor the percentage of how full the backing array can be before they resize - * @throws IllegalStateException if the minimum capacity is negative - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - */ - public CONCURRENT_HASH_MAP(int minCapacity, float loadFactor) { - this(minCapacity, loadFactor, HashUtil.DEFAULT_MIN_CONCURRENCY); - } - - /** - * Constructor that defines the minimum capacity and concurrencyLevel - * @param minCapacity the minimum capacity the HashMap is allowed to be. - * @param concurrencyLevel decides how many operations can be performed at once. - * @throws IllegalStateException if the minimum capacity is negative - * @throws IllegalStateException if the concurrencyLevel is either below/equal to 0 or above/equal to 65535 - */ - public CONCURRENT_HASH_MAP(int minCapacity, int concurrencyLevel) { - this(minCapacity, HashUtil.DEFAULT_LOAD_FACTOR, concurrencyLevel); - } - - /** - * Constructor that defines the load factor and concurrencyLevel - * @param loadFactor the percentage of how full the backing array can be before they resize - * @param concurrencyLevel decides how many operations can be performed at once. - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - * @throws IllegalStateException if the concurrencyLevel is either below/equal to 0 or above/equal to 65535 - */ - public CONCURRENT_HASH_MAP(float loadFactor, int concurrencyLevel) { - this(HashUtil.DEFAULT_MIN_CAPACITY, loadFactor, concurrencyLevel); - } - - /** - * Constructor that defines the minimum capacity, load factor and concurrencyLevel - * @param minCapacity the minimum capacity the HashMap is allowed to be. - * @param loadFactor the percentage of how full the backing array can be before they resize - * @param concurrencyLevel decides how many operations can be performed at once. - * @throws IllegalStateException if the minimum capacity is negative - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - * @throws IllegalStateException if the concurrencyLevel is either below/equal to 0 or above/equal to 65535 - */ - public CONCURRENT_HASH_MAP(int minCapacity, float loadFactor, int concurrencyLevel) { - if(minCapacity < 0) throw new IllegalStateException("Minimum Capacity is negative. This is not allowed"); - if(loadFactor <= 0 || loadFactor >= 1F) throw new IllegalStateException("Load Factor is not between 0 and 1"); - if(concurrencyLevel <= 0 || concurrencyLevel >= MAX_SEGMENTS) throw new IllegalStateException("concurrencyLevel has to be between 0 and 65536"); - int segmentCount = HashUtil.nextPowerOfTwo(concurrencyLevel); - int shift = Integer.numberOfTrailingZeros(segmentCount); - segments = new Segment[segmentCount]; - segmentShift = 32 - shift; - segmentMask = segmentCount - 1; - int segmentCapacity = minCapacity / segmentCount; - if(segmentCapacity * segmentCount < minCapacity) { - segmentCapacity++; - } - segmentCapacity = HashUtil.arraySize(segmentCapacity, loadFactor); - for(int i = 0;i map) { - this(map, HashUtil.DEFAULT_LOAD_FACTOR, HashUtil.DEFAULT_MIN_CONCURRENCY); - } - - /** - * A Helper constructor that allows to create a Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - * @param loadFactor the percentage of how full the backing array can be before they resize - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - */ - public CONCURRENT_HASH_MAP(Map map, float loadFactor) { - this(map, loadFactor, HashUtil.DEFAULT_MIN_CONCURRENCY); - } - - /** - * A Helper constructor that allows to create a Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - * @param concurrencyLevel decides how many operations can be performed at once. - * @throws IllegalStateException if the concurrencyLevel is either below/equal to 0 or above/equal to 65535 - */ - public CONCURRENT_HASH_MAP(Map map, int concurrencyLevel) { - this(map, HashUtil.DEFAULT_LOAD_FACTOR, concurrencyLevel); - } - - /** - * A Helper constructor that allows to create a Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - * @param loadFactor the percentage of how full the backing array can be before they resize - * @param concurrencyLevel decides how many operations can be performed at once. - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - * @throws IllegalStateException if the concurrencyLevel is either below/equal to 0 or above/equal to 65535 - */ - public CONCURRENT_HASH_MAP(Map map, float loadFactor, int concurrencyLevel) { - this(map.size(), loadFactor, concurrencyLevel); - putAll(map); - } - - /** - * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - */ - public CONCURRENT_HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map) { - this(map, HashUtil.DEFAULT_LOAD_FACTOR, HashUtil.DEFAULT_MIN_CONCURRENCY); - } - - /** - * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - * @param loadFactor the percentage of how full the backing array can be before they resize - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - */ - public CONCURRENT_HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map, float loadFactor) { - this(map, loadFactor, HashUtil.DEFAULT_MIN_CONCURRENCY); - } - - /** - * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - * @param concurrencyLevel decides how many operations can be performed at once. - * @throws IllegalStateException if the concurrencyLevel is either below/equal to 0 or above/equal to 65535 - */ - public CONCURRENT_HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map, int concurrencyLevel) { - this(map, HashUtil.DEFAULT_LOAD_FACTOR, concurrencyLevel); - } - - /** - * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - * @param loadFactor the percentage of how full the backing array can be before they resize - * @param concurrencyLevel decides how many operations can be performed at once. - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - * @throws IllegalStateException if the concurrencyLevel is either below/equal to 0 or above/equal to 65535 - */ - public CONCURRENT_HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map, float loadFactor, int concurrencyLevel) { - this(map.size(), loadFactor, concurrencyLevel); - putAll(map); - } - - @Override - public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { - int hash = getHashCode(key); - return getSegment(hash).put(hash, key, value); - } - - @Override - public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { - int hash = getHashCode(key); - return getSegment(hash).putIfAbsent(hash, key, value); - } - -#if VALUE_PRIMITIVES - @Override - public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { - int hash = getHashCode(key); - return getSegment(hash).addTo(hash, key, value); - } - - @Override - public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { - int hash = getHashCode(key); - return getSegment(hash).subFrom(hash, key, value); - } - -#endif - @Override - public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { - int hash = getHashCode(key); - return getSegment(hash).remove(hash, key); - } - -#if !TYPE_OBJECT || !VALUE_OBJECT - @Override - public boolean remove(KEY_TYPE key, VALUE_TYPE value) { - int hash = getHashCode(key); - return getSegment(hash).remove(hash, key, value); - } - -#endif - @Override - public boolean remove(Object key, Object value) { - int hash = getHashCode(key); - return getSegment(hash).remove(hash, key, value); - } - - @Override - public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { - int hash = getHashCode(key); - return getSegment(hash).removeOrDefault(hash, key, defaultValue); - } - - @Override - public VALUE_TYPE GET_VALUE(KEY_TYPE key) { - int hash = getHashCode(key); - return getSegment(hash).get(hash, key); - } - - @Override - public CLASS_VALUE_TYPE get(Object key) { - int hash = getHashCode(key); - return VALUE_TO_OBJ(getSegment(hash).get(hash, key)); - } - -#if TYPE_OBJECT && VALUE_OBJECT - @Override - public VALUE_TYPE getOrDefault(Object key, VALUE_TYPE defaultValue) { - int hash = getHashCode(key); - return getSegment(hash).getOrDefault(hash, key, defaultValue); - } - -#else - @Override - public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { - int hash = getHashCode(key); - return getSegment(hash).getOrDefault(hash, key, defaultValue); - } - -#endif - - @Override - public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { - for(int i = 0,m=segments.length;i 0) return false; - } - return true; - } - - @Override - public int size() { - long size = 0L; - for(int i = 0,m=segments.length;i Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)size; - } - - @Override - public ObjectSet ENTRY_SET() { - if(entrySet == null) entrySet = new MapEntrySet(); - return entrySet; - } - - @Override - public SET KEY_GENERIC_TYPE keySet() { - if(keySet == null) keySet = new KeySet(); - return keySet; - } - - @Override - public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { - if(values == null) values = new Values(); - return values; - } - - protected int getSegmentIndex(int hash) { - return (hash >>> segmentShift) & segmentMask; - } - - protected Segment KEY_VALUE_GENERIC_TYPE getSegment(int hash) { - return segments[(hash >>> segmentShift) & segmentMask]; - } - -#if !TYPE_OBJECT - protected int getHashCode(KEY_TYPE key) { - return HashUtil.mix(KEY_TO_HASH(key)); - } - -#endif - protected int getHashCode(Object obj) { - return HashUtil.mix(Objects.hashCode(obj)); - } - - private class MapEntrySet extends AbstractObjectSet implements MAP.FastEntrySet KEY_VALUE_GENERIC_TYPE { - @Override - public ObjectBidirectionalIterator iterator() { - return new EntryIterator(); - } - - @Override - public ObjectBidirectionalIterator fastIterator() { - return new FastEntryIterator(); - } - - @Override - public MapEntrySet copy() { throw new UnsupportedOperationException(); } - - @Override - public void forEach(Consumer action) { - for(int i = 0,m=segments.length;i action) { - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - for(int i = 0,m=segments.length;i action) { - Objects.requireNonNull(action); - int count = 0; - for(int i = 0,m=segments.length;i void forEach(E input, ObjectObjectConsumer action) { - Objects.requireNonNull(action); - for(int i = 0,m=segments.length;i filter) { - Objects.requireNonNull(filter); - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - for(int i = 0,m=segments.length;i filter) { - Objects.requireNonNull(filter); - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - for(int i = 0,m=segments.length;i filter) { - Objects.requireNonNull(filter); - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - for(int i = 0,m=segments.length;i E reduce(E identity, BiFunction operator) { - Objects.requireNonNull(operator); - E state = identity; - for(int i = 0,m=segments.length;i operator) { - Objects.requireNonNull(operator); - MAP.Entry KEY_VALUE_GENERIC_TYPE state = null; - boolean empty = true; - for(int i = 0,m=segments.length;i filter) { - Objects.requireNonNull(filter); - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - for(int i = 0,m=segments.length;i filter) { - Objects.requireNonNull(filter); - int result = 0; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - for(int i = 0,m=segments.length;i= 0) return VALUE_EQUALS(entry.ENTRY_VALUE(), seg.values[index]); - } - finally { - seg.unlockRead(stamp); - } - } - else { - Map.Entry entry = (Map.Entry)o; - int hash = getHashCode(entry.getKey()); - Segment KEY_VALUE_GENERIC_TYPE seg = getSegment(hash); - long stamp = seg.readLock(); - try { - int index = seg.findIndex(hash, entry.getKey()); - if(index >= 0) return Objects.equals(entry.getValue(), VALUE_TO_OBJ(seg.values[index])); - } - finally { - seg.unlockRead(stamp); - } - } - } - return false; - } - - @Override - @Deprecated - public boolean remove(Object o) { - if(o instanceof Map.Entry) { - if(o instanceof MAP.Entry) { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; - return CONCURRENT_HASH_MAP.this.remove(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); - } - Map.Entry entry = (Map.Entry)o; - return CONCURRENT_HASH_MAP.this.remove(entry.getKey(), entry.getValue()); - } - return false; - } - - @Override - public int size() { - return CONCURRENT_HASH_MAP.this.size(); - } - - @Override - public void clear() { - CONCURRENT_HASH_MAP.this.clear(); - } - } - - private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE implements SET KEY_GENERIC_TYPE { - - @Override - public boolean add(KEY_TYPE key) { throw new UnsupportedOperationException(); } - -#if TYPE_OBJECT - @Override - @Deprecated - public boolean contains(Object e) { - return containsKey(e); - } - - @Override - public boolean remove(Object o) { - int oldSize = size(); - CONCURRENT_HASH_MAP.this.remove(o); - return size() != oldSize; - } - -#else - @Override - public boolean contains(KEY_TYPE e) { - return containsKey(e); - } - - @Override - public boolean remove(KEY_TYPE o) { - int oldSize = size(); - CONCURRENT_HASH_MAP.this.remove(o); - return size() != oldSize; - } - -#endif - @Override - public BI_ITERATOR KEY_GENERIC_TYPE iterator() { - return new KeyIterator(); - } - - @Override - public KeySet copy() { throw new UnsupportedOperationException(); } - - @Override - public int size() { - return CONCURRENT_HASH_MAP.this.size(); - } - - @Override - public void clear() { - CONCURRENT_HASH_MAP.this.clear(); - } - - @Override - public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { - Objects.requireNonNull(action); - for(int i = 0,m=segments.length;i void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { - Objects.requireNonNull(action); - for(int i = 0,m=segments.length;i KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) { - Objects.requireNonNull(operator); - KEY_SPECIAL_TYPE state = identity; - for(int i = 0,m=segments.length;i void forEach(E input, VALUE_BI_FROM_OBJECT_CONSUMER VSV_GENERIC_TYPE action) { - Objects.requireNonNull(action); - for(int i = 0,m=segments.length;i VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction operator) { - Objects.requireNonNull(operator); - VALUE_SPECIAL_TYPE state = identity; - for(int i = 0,m=segments.length;i { - MapEntry entry = new MapEntry(); - - public FastEntryIterator() {} - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { - entry.set(nextEntry(), currentSegment()); - return entry; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { - entry.set(previousEntry(), currentSegment()); - return entry; - } - } - - private class EntryIterator extends MapIterator implements ObjectBidirectionalIterator { - MapEntry entry; - - public EntryIterator() {} - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { - return entry = new MapEntry(nextEntry(), currentSegment()); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { - return entry = new MapEntry(previousEntry(), currentSegment()); - } - - @Override - public void remove() { - super.remove(); - entry.clear(); - } - } - - private class ValueIterator extends MapIterator implements VALUE_BI_ITERATOR VALUE_GENERIC_TYPE { - public ValueIterator() {} - - @Override - public VALUE_TYPE VALUE_PREVIOUS() { - return entry(previousEntry(), currentSegment()); - } - - @Override - public VALUE_TYPE VALUE_NEXT() { - return entry(nextEntry(), currentSegment()); - } - - protected VALUE_TYPE entry(int entry, int segment) { - return segments[segment].values[entry]; - } - } - - private class KeyIterator extends MapIterator implements BI_ITERATOR KEY_GENERIC_TYPE { - - public KeyIterator() {} - - @Override - public KEY_TYPE PREVIOUS() { - return entry(previousEntry(), currentSegment()); - } - - @Override - public KEY_TYPE NEXT() { - return entry(nextEntry(), currentSegment()); - } - - protected KEY_TYPE entry(int entry, int segment) { - return segments[segment].keys[entry]; - } - } - - private class MapIterator { - int previous = -1; - int next = -1; - int current = -1; - int previousSegment = -1; - int nextSegment = -1; - int currentSegment = -1; - - MapIterator() { - currentSegment = getFirstSegment(); - if(currentSegment != -1) next = segments[currentSegment].firstIndex; - } - - public boolean hasNext() { - return next != -1 || nextSegment != -1; - } - - public boolean hasPrevious() { - return previous != -1 || previousSegment != -1; - } - - public int currentSegment() { - return currentSegment; - } - - public int previousEntry() { - if(!hasPrevious()) throw new NoSuchElementException(); - if(previousSegment != -1) { - nextSegment = currentSegment; - currentSegment = previousSegment; - previousSegment = -1; - next = current = segments[currentSegment].lastIndex; - } - else { - if(next != -1) nextSegment = -1; - next = current = previous; - } - findPreviousIndex(); - return current; - } - - public int nextEntry() { - if(!hasNext()) throw new NoSuchElementException(); - if(nextSegment != -1) { - previousSegment = currentSegment; - currentSegment = nextSegment; - nextSegment = -1; - previous = current = segments[currentSegment].firstIndex; - } - else { - if(previous != -1) previousSegment = -1; - previous = current = next; - } - findNextIndex(); - return current; - } - - public void remove() { - if(current == -1) throw new IllegalStateException(); - Segment KEY_VALUE_GENERIC_TYPE seg = segments[currentSegment]; - long stamp = seg.writeLock(); - try { - if(current == previous) findPreviousIndex(); - else findNextIndex(); - seg.size--; - if(previous == -1) seg.firstIndex = next; - else seg.links[previous] ^= ((seg.links[previous] ^ (next & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - - if(next == -1) seg.lastIndex = previous; - else seg.links[next] ^= ((seg.links[next] ^ ((previous & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); - - if(current == seg.nullIndex) { - current = -1; - seg.containsNull = false; - seg.keys[seg.nullIndex] = EMPTY_KEY_VALUE; - seg.values[seg.nullIndex] = EMPTY_VALUE; - } - else { - int slot, last, startPos = current; - current = -1; - KEY_TYPE current; - while(true) { - startPos = ((last = startPos) + 1) & seg.mask; - while(true){ - if(KEY_EQUALS_NULL((current = seg.keys[startPos]))) { - seg.keys[last] = EMPTY_KEY_VALUE; - seg.values[last] = EMPTY_VALUE; - return; - } - slot = HashUtil.mix(KEY_TO_HASH(current)) & seg.mask; - if(last <= startPos ? (last >= slot || slot > startPos) : (last >= slot && slot > startPos)) break; - startPos = ++startPos & seg.mask; - } - seg.keys[last] = current; - seg.values[last] = seg.values[startPos]; - if(next == startPos) next = last; - if(previous == startPos) previous = last; - seg.onNodeMoved(startPos, last); - } - } - } - finally { - seg.unlockWrite(stamp); - } - } - - protected void findPreviousIndex() { - previous = (int)(segments[currentSegment].links[current] >>> 32); - if(previous == -1) { - previousSegment = findPreviousSegment(currentSegment-1); - } - } - - protected void findNextIndex() { - next = (int)(segments[currentSegment].links[current]); - if(next == -1) { - nextSegment = findNextSegment(currentSegment+1); - } - } - - private int getFirstSegment() { - for(int i = 0,m=segments.length;i= segments.length ? -1 : index; - } - - private int findPreviousSegment(int index) { - for(;index >= 0 && segments[index].lastIndex == -1;index--); - return index >= 0 ? index : -1; - } - } - - protected class MapEntry implements MAP.Entry KEY_VALUE_GENERIC_TYPE, Map.Entry { - int index = -1; - int segmentIndex = -1; - - public MapEntry() {} - public MapEntry(int index, int segmentIndex) { - set(index, segmentIndex); - } - - public void set(int index, int segmentIndex) { - this.index = index; - this.segmentIndex = segmentIndex; - } - - public void clear() { - index = -1; - segmentIndex = -1; - } - - @Override - public KEY_TYPE ENTRY_KEY() { - return segments[segmentIndex].keys[index]; - } - - @Override - public VALUE_TYPE ENTRY_VALUE() { - return segments[segmentIndex].values[index]; - } - - @Override - public VALUE_TYPE setValue(VALUE_TYPE value) { - Segment KEY_VALUE_GENERIC_TYPE seg = segments[segmentIndex]; - long stamp = seg.writeLock(); - try - { - VALUE_TYPE oldValue = ENTRY_VALUE(); - seg.values[index] = value; - return oldValue; - } - finally { - seg.unlockWrite(stamp); - } - } - - @Override - public boolean equals(Object obj) { - if(obj instanceof Map.Entry) { - if(obj instanceof MAP.Entry) { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)obj; - return KEY_EQUALS(ENTRY_KEY(), entry.ENTRY_KEY()) && VALUE_EQUALS(ENTRY_VALUE(), entry.ENTRY_VALUE()); - } - Map.Entry entry = (Map.Entry)obj; - Object key = entry.getKey(); - Object value = entry.getValue(); -#if TYPE_OBJECT && VALUE_OBJECT - return KEY_EQUALS(ENTRY_KEY(), key) && VALUE_EQUALS(ENTRY_VALUE(), value); -#else if TYPE_OBJECT - return value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(ENTRY_KEY(), key) && VALUE_EQUALS(ENTRY_VALUE(), CLASS_TO_VALUE(value)); -#else if VALUE_OBJECT - return key instanceof CLASS_TYPE && KEY_EQUALS(ENTRY_KEY(), CLASS_TO_KEY(key)) && VALUE_EQUALS(ENTRY_VALUE(), value); -#else - return key instanceof CLASS_TYPE && value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(ENTRY_KEY(), CLASS_TO_KEY(key)) && VALUE_EQUALS(ENTRY_VALUE(), CLASS_TO_VALUE(value)); -#endif - } - return false; - } - - @Override - public int hashCode() { - return KEY_TO_HASH(ENTRY_KEY()) ^ VALUE_TO_HASH(ENTRY_VALUE()); - } - - @Override - public String toString() { - return KEY_TO_STRING(ENTRY_KEY()) + "=" + VALUE_TO_STRING(ENTRY_VALUE()); - } - } - - protected static class Segment KEY_VALUE_GENERIC_TYPE extends StampedLock - { - private static final long serialVersionUID = -446894977795760975L; - protected final CONCURRENT_HASH_MAP KEY_VALUE_GENERIC_TYPE map; - /** The Backing keys array */ - protected transient KEY_TYPE[] keys; - /** The Backing values array */ - protected transient VALUE_TYPE[] values; - /** The Backing array for links between nodes. Left 32 Bits => Previous Entry, Right 32 Bits => Next Entry */ - protected transient long[] links; - /** The First Index in the Map */ - protected int firstIndex = -1; - /** The Last Index in the Map */ - protected int lastIndex = -1; - /** If a null value is present */ - protected transient boolean containsNull; - /** Index of the Null Value */ - protected transient int nullIndex; - /** Maximum amount of Values that can be stored before the array gets expanded usually 75% */ - protected transient int maxFill; - /** Max Index that is allowed to be searched through nullIndex - 1 */ - protected transient int mask; - /** Amount of Elements stored in the HashMap */ - protected int size; - /** Minimum array size the Segment will be */ - protected transient int minCapacity; - /** How full the Arrays are allowed to get before resize */ - protected float loadFactor; - - protected Segment(CONCURRENT_HASH_MAP KEY_VALUE_GENERIC_TYPE map) { - this.map = map; - } - - protected Segment(CONCURRENT_HASH_MAP KEY_VALUE_GENERIC_TYPE map, int minCapacity, float loadFactor, boolean isNullContainer) { - this.map = map; - this.minCapacity = minCapacity; - this.loadFactor = loadFactor; - mask = minCapacity - 1; - maxFill = Math.min((int)Math.ceil(minCapacity * loadFactor), minCapacity - 1); - nullIndex = isNullContainer ? minCapacity : -1; - int arraySize = minCapacity + (isNullContainer ? 1 : 0); - keys = NEW_KEY_ARRAY(arraySize); - values = NEW_VALUE_ARRAY(arraySize); - links = new long[arraySize]; - } - - protected Segment KEY_VALUE_GENERIC_TYPE copy(CONCURRENT_HASH_MAP KEY_VALUE_GENERIC_TYPE newMap) { - long stamp = readLock(); - try - { - Segment KEY_VALUE_GENERIC_TYPE copy = new SegmentKV_BRACES(newMap); - copy.keys = Arrays.copyOf(keys, keys.length); - copy.values = Arrays.copyOf(values, values.length); - copy.links = Arrays.copyOf(links, links.length); - copy.firstIndex = firstIndex; - copy.lastIndex = lastIndex; - copy.containsNull = containsNull; - copy.nullIndex = nullIndex; - copy.maxFill = maxFill; - copy.mask = mask; - copy.size = size; - copy.minCapacity = minCapacity; - copy.loadFactor = loadFactor; - return copy; - } - finally { - unlockRead(stamp); - } - } - - protected VALUE_TYPE getDefaultReturnValue() { - return map.getDefaultReturnValue(); - } - - protected VALUE_TYPE put(int hash, KEY_TYPE key, VALUE_TYPE value) { - long stamp = writeLock(); - try { - int slot = findIndex(hash, key); - if(slot < 0) { - insert(-slot-1, key, value); - return getDefaultReturnValue(); - } - VALUE_TYPE oldValue = values[slot]; - values[slot] = value; - return oldValue; - } - finally { - unlockWrite(stamp); - } - } - - protected VALUE_TYPE putIfAbsent(int hash, KEY_TYPE key, VALUE_TYPE value) { - long stamp = writeLock(); - try { - int slot = findIndex(hash, key); - if(slot < 0) { - insert(-slot-1, key, value); - return getDefaultReturnValue(); - } - else if(VALUE_EQUALS(values[slot], getDefaultReturnValue())) { - VALUE_TYPE oldValue = values[slot]; - values[slot] = value; - return oldValue; - } - return values[slot]; - } - finally { - unlockWrite(stamp); - } - } - -#if VALUE_PRIMITIVES - protected VALUE_TYPE addTo(int hash, KEY_TYPE key, VALUE_TYPE value) { - long stamp = writeLock(); - try { - int slot = findIndex(hash, key); - if(slot < 0) { - insert(-slot-1, key, value); - return getDefaultReturnValue(); - } - VALUE_TYPE oldValue = values[slot]; - values[slot] += value; - return oldValue; - } - finally { - unlockWrite(stamp); - } - } - - protected VALUE_TYPE subFrom(int hash, KEY_TYPE key, VALUE_TYPE value) { - long stamp = writeLock(); - try { - int slot = findIndex(hash, key); - if(slot < 0) return getDefaultReturnValue(); - VALUE_TYPE oldValue = values[slot]; - values[slot] -= value; - if(value < 0 ? (values[slot] >= getDefaultReturnValue()) : (values[slot] <= getDefaultReturnValue())) removeIndex(slot); - return oldValue; - } - finally { - unlockWrite(stamp); - } - } -#endif - -#if !TYPE_OBJECT - protected boolean containsKey(int hash, KEY_TYPE key) { - long stamp = readLock(); - try { - return findIndex(hash, key) >= 0; - } - finally { - unlockRead(stamp); - } - } - -#endif - @Deprecated - protected boolean containsKey(int hash, Object key) { - long stamp = readLock(); - try { - return findIndex(hash, key) >= 0; - } - finally { - unlockRead(stamp); - } - } - -#if !VALUE_OBJECT - protected boolean containsValue(VALUE_TYPE value) { - long stamp = readLock(); - try { - int index = firstIndex; - while(index != -1) { - if(VALUE_EQUALS(values[index], value)) return true; - index = (int)links[index]; - } - return false; - } - finally { - unlockRead(stamp); - } - } - -#endif - @Deprecated - protected boolean containsValue(Object value) { - long stamp = readLock(); - try { - int index = firstIndex; - while(index != -1) { -#if VALUE_OBJECT - if(VALUE_EQUALS(values[index], value)) return true; -#else - if((value == null && values[index] == getDefaultReturnValue()) || EQUALS_VALUE_TYPE(values[index], value)) return true; -#endif - index = (int)links[index]; - } - return false; - } - finally { - unlockRead(stamp); - } - } - -#if !TYPE_OBJECT - protected VALUE_TYPE get(int hash, KEY_TYPE key) { - long stamp = readLock(); - try { - int slot = findIndex(hash, key); - return slot < 0 ? getDefaultReturnValue() : values[slot]; - } - finally { - unlockRead(stamp); - } - } - -#endif - protected VALUE_TYPE get(int hash, Object key) { - long stamp = readLock(); - try { - int slot = findIndex(hash, key); - return slot < 0 ? getDefaultReturnValue() : values[slot]; - } - finally { - unlockRead(stamp); - } - } - -#if TYPE_OBJECT && VALUE_OBJECT - protected VALUE_TYPE getOrDefault(int hash, Object key, VALUE_TYPE defaultValue) { - long stamp = readLock(); - try { - int slot = findIndex(hash, key); - return slot < 0 ? defaultValue : values[slot]; - } - finally { - unlockRead(stamp); - } - } - -#else - protected VALUE_TYPE getOrDefault(int hash, KEY_TYPE key, VALUE_TYPE defaultValue) { - long stamp = readLock(); - try { - int slot = findIndex(hash, key); - return slot < 0 ? defaultValue : values[slot]; - } - finally { - unlockRead(stamp); - } - } - -#endif - protected void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { - long stamp = readLock(); - try { - int index = firstIndex; - while(index != -1) { - action.accept(keys[index], values[index]); - index = (int)links[index]; - } - } - finally { - unlockRead(stamp); - } - } - -#if !TYPE_OBJECT - protected VALUE_TYPE remove(int hash, KEY_TYPE key) { - long stamp = writeLock(); - try { - int slot = findIndex(hash, key); - if(slot < 0) return getDefaultReturnValue(); - return removeIndex(slot); - } - finally { - unlockWrite(stamp); - } - } - -#endif - protected VALUE_TYPE removeOrDefault(int hash, KEY_TYPE key, VALUE_TYPE defaultValue) { - long stamp = writeLock(); - try { - int slot = findIndex(hash, key); - if(slot < 0) return defaultValue; - return removeIndex(slot); - } - finally { - unlockWrite(stamp); - } - } - - protected CLASS_VALUE_TYPE remove(int hash, Object key) { - long stamp = writeLock(); - try { - int slot = findIndex(hash, key); - if(slot < 0) return VALUE_TO_OBJ(getDefaultReturnValue()); - return VALUE_TO_OBJ(removeIndex(slot)); - } - finally { - unlockWrite(stamp); - } - } - -#if !TYPE_OBJECT || !VALUE_OBJECT - protected boolean remove(int hash, KEY_TYPE key, VALUE_TYPE value) { - long stamp = writeLock(); - try { - if(KEY_EQUALS_NULL(key)) { - if(containsNull && VALUE_EQUALS(value, values[nullIndex])) { - removeNullIndex(); - return true; - } - return false; - } - int pos = hash & mask; - KEY_TYPE current = keys[pos]; - if(KEY_EQUALS_NULL(current)) return false; - if(KEY_EQUALS(current, key) && VALUE_EQUALS(value, values[pos])) { - removeIndex(pos); - return true; - } - while(true) { - if(KEY_EQUALS_NULL((current = keys[pos = (++pos & mask)]))) return false; - else if(KEY_EQUALS(current, key) && VALUE_EQUALS(value, values[pos])) { - removeIndex(pos); - return true; - } - } - } - finally { - unlockWrite(stamp); - } - } - -#endif - protected boolean remove(int hash, Object key, Object value) { - long stamp = writeLock(); - try - { -#if TYPE_OBJECT - if(key == null) { -#else - if(key == null || (key instanceof CLASS_TYPE && KEY_EQUALS_NULL(CLASS_TO_KEY(key)))) { -#endif - if(containsNull && EQUALS_VALUE_TYPE(values[nullIndex], value)) { - removeNullIndex(); - return true; - } - return false; - } - int pos = hash & mask; - KEY_TYPE current = keys[pos]; - if(KEY_EQUALS_NULL(current)) return false; - if(EQUALS_KEY_TYPE(current, key) && EQUALS_VALUE_TYPE(values[pos], value)) { - removeIndex(pos); - return true; - } - while(true) { - if(KEY_EQUALS_NULL((current = keys[pos = (++pos & mask)]))) return false; - else if(EQUALS_KEY_TYPE(current, key) && EQUALS_VALUE_TYPE(values[pos], value)){ - removeIndex(pos); - return true; - } - } - } - finally { - unlockWrite(stamp); - } - } - - protected boolean replace(int hash, KEY_TYPE key, VALUE_TYPE oldValue, VALUE_TYPE newValue) { - long stamp = writeLock(); - try { - int index = findIndex(hash, key); - if(index < 0 || values[index] != oldValue) return false; - values[index] = newValue; - return true; - } - finally { - unlockWrite(stamp); - } - } - - protected VALUE_TYPE replace(int hash, KEY_TYPE key, VALUE_TYPE value) { - long stamp = writeLock(); - try { - int index = findIndex(hash, key); - if(index < 0) return getDefaultReturnValue(); - VALUE_TYPE oldValue = values[index]; - values[index] = value; - return oldValue; - } - finally { - unlockWrite(stamp); - } - } - - protected VALUE_TYPE compute(int hash, KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { - long stamp = writeLock(); - try { - int index = findIndex(hash, key); - if(index < 0) { - VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, getDefaultReturnValue()); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - insert(-index-1, key, newValue); - return newValue; - } - VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, values[index]); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - removeIndex(index); - return newValue; - } - values[index] = newValue; - return newValue; - } - finally { - unlockWrite(stamp); - } - } - - protected VALUE_TYPE computeIfAbsent(int hash, KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) { - long stamp = writeLock(); - try { - int index = findIndex(hash, key); - if(index < 0) { - VALUE_TYPE newValue = mappingFunction.APPLY(key); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - insert(-index-1, key, newValue); - return newValue; - } - VALUE_TYPE newValue = values[index]; - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - newValue = mappingFunction.APPLY(key); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - values[index] = newValue; - } - return newValue; - } - finally { - unlockWrite(stamp); - } - } - - protected VALUE_TYPE supplyIfAbsent(int hash, KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) { - long stamp = writeLock(); - try { - int index = findIndex(hash, key); - if(index < 0) { - VALUE_TYPE newValue = valueProvider.VALUE_SUPPLY_GET(); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - insert(-index-1, key, newValue); - return newValue; - } - VALUE_TYPE newValue = values[index]; - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - newValue = valueProvider.VALUE_SUPPLY_GET(); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - values[index] = newValue; - } - return newValue; - } - finally { - unlockWrite(stamp); - } - } - - protected VALUE_TYPE computeIfPresent(int hash, KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { - long stamp = writeLock(); - try { - int index = findIndex(hash, key); - if(index < 0 || VALUE_EQUALS(values[index], getDefaultReturnValue())) return getDefaultReturnValue(); - VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, values[index]); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - removeIndex(index); - return newValue; - } - values[index] = newValue; - return newValue; - } - finally { - unlockWrite(stamp); - } - } - - protected VALUE_TYPE merge(int hash, KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { - long stamp = writeLock(); - try { - int index = findIndex(hash, key); - VALUE_TYPE newValue = index < 0 || VALUE_EQUALS(values[index], getDefaultReturnValue()) ? value : mappingFunction.APPLY_VALUE(values[index], value); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - if(index >= 0) - removeIndex(index); - } - else if(index < 0) insert(-index-1, key, newValue); - else values[index] = newValue; - return newValue; - } - finally { - unlockWrite(stamp); - } - } - - protected void clear() { - if(size == 0) return; - long stamp = writeLock(); - try { - size = 0; - containsNull = false; - Arrays.fill(keys, EMPTY_KEY_VALUE); - Arrays.fill(values, EMPTY_VALUE); - firstIndex = -1; - lastIndex = -1; - } - finally { - unlockWrite(stamp); - } - } - - protected boolean trim(int size) { - int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor))); - if(request >= mask+1 || this.size > Math.min((int)Math.ceil(request * loadFactor), request - 1)) return false; - long stamp = writeLock(); - try { - try { - rehash(request); - } - catch(OutOfMemoryError noMemory) { return false; } - return true; - } - finally { - unlockWrite(stamp); - } - } - - protected void clearAndTrim(int size) { - int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor))); - if(request >= mask+1) { - clear(); - return; - } - long stamp = writeLock(); - try { - if(nullIndex != -1) { - nullIndex = request; - } - mask = request-1; - maxFill = Math.min((int)Math.ceil(request * loadFactor), request - 1); - int arraySize = request + (nullIndex != -1 ? 1 : 0); - keys = NEW_KEY_ARRAY(arraySize); - values = NEW_VALUE_ARRAY(arraySize); - links = new long[arraySize]; - this.size = 0; - firstIndex = -1; - lastIndex = -1; - containsNull = false; - } - finally { - unlockWrite(stamp); - } - } - - protected void insert(int slot, KEY_TYPE key, VALUE_TYPE value) { - if(slot == nullIndex) containsNull = true; - keys[slot] = key; - values[slot] = value; - if(size == 0) { - firstIndex = lastIndex = slot; - links[slot] = -1L; - } - else { - links[lastIndex] ^= ((links[lastIndex] ^ (slot & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - links[slot] = ((lastIndex & 0xFFFFFFFFL) << 32) | 0xFFFFFFFFL; - lastIndex = slot; - } - if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor)); - } - - protected VALUE_TYPE removeIndex(int pos) { - if(pos == nullIndex) return containsNull ? removeNullIndex() : getDefaultReturnValue(); - VALUE_TYPE value = values[pos]; - keys[pos] = EMPTY_KEY_VALUE; - values[pos] = EMPTY_VALUE; - size--; - onNodeRemoved(pos); - shiftKeys(pos); - if(nullIndex > minCapacity && size < maxFill / 4 && nullIndex > HashUtil.DEFAULT_MIN_CAPACITY) rehash(nullIndex / 2); - return value; - } - - protected VALUE_TYPE removeNullIndex() { - VALUE_TYPE value = values[nullIndex]; - containsNull = false; - keys[nullIndex] = EMPTY_KEY_VALUE; - values[nullIndex] = EMPTY_VALUE; - size--; - onNodeRemoved(nullIndex); - if(nullIndex > minCapacity && size < maxFill / 4 && nullIndex > HashUtil.DEFAULT_MIN_CAPACITY) rehash(nullIndex / 2); - return value; - } - -#if !TYPE_OBJECT - protected int findIndex(int hash, KEY_TYPE key) { - if(KEY_EQUALS_NULL(key)) return containsNull ? nullIndex : -(nullIndex + 1); - int pos = hash & mask; - KEY_TYPE current = keys[pos]; - if(KEY_EQUALS_NOT_NULL(current)) { - if(KEY_EQUALS(current, key)) return pos; - while(KEY_EQUALS_NOT_NULL((current = keys[pos = (++pos & mask)]))) - if(KEY_EQUALS(current, key)) return pos; - } - return -(pos + 1); - } - -#endif - protected int findIndex(int hash, Object key) { - if(key == null) return containsNull ? nullIndex : -(nullIndex + 1); -#if !TYPE_OBJECT - if(KEY_EQUALS_NULL(CLASS_TO_KEY(key))) return containsNull ? nullIndex : -(nullIndex + 1); -#endif - int pos = hash & mask; - KEY_TYPE current = keys[pos]; - if(KEY_EQUALS_NOT_NULL(current)) { - if(EQUALS_KEY_TYPE(current, key)) return pos; - while(KEY_EQUALS_NOT_NULL((current = keys[pos = (++pos & mask)]))) - if(EQUALS_KEY_TYPE(current, key)) return pos; - } - return -(pos + 1); - } - - protected void shiftKeys(int startPos) { - int slot, last; - KEY_TYPE current; - while(true) { - startPos = ((last = startPos) + 1) & mask; - while(true){ - if(KEY_EQUALS_NULL((current = keys[startPos]))) { - keys[last] = EMPTY_KEY_VALUE; - values[last] = EMPTY_VALUE; - return; - } - slot = HashUtil.mix(KEY_TO_HASH(current)) & mask; - if(last <= startPos ? (last >= slot || slot > startPos) : (last >= slot && slot > startPos)) break; - startPos = ++startPos & mask; - } - keys[last] = current; - values[last] = values[startPos]; - onNodeMoved(startPos, last); - } - } - - protected void rehash(int newSize) { - int newMask = newSize - 1; - int arraySize = newSize + (nullIndex != -1 ? 1 : 0); - KEY_TYPE[] newKeys = NEW_KEY_ARRAY(arraySize); - VALUE_TYPE[] newValues = NEW_VALUE_ARRAY(arraySize); - long[] newLinks = new long[arraySize]; - int i = firstIndex, prev = -1, newPrev = -1, pos; - firstIndex = -1; - for(int j = size; j-- != 0;) { - if(KEY_EQUALS_NULL(keys[i])) pos = newSize; - else { - pos = HashUtil.mix(KEY_TO_HASH(keys[i])) & newMask; - while(KEY_EQUALS_NOT_NULL(newKeys[pos])) pos = ++pos & newMask; - } - newKeys[pos] = keys[i]; - newValues[pos] = values[i]; - if(prev != -1) { - newLinks[newPrev] ^= ((newLinks[newPrev] ^ (pos & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - newLinks[pos] ^= ((newLinks[pos] ^ ((newPrev & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); - newPrev = pos; - } - else { - newPrev = firstIndex = pos; - newLinks[pos] = -1L; - } - i = (int)links[prev = i]; - } - links = newLinks; - lastIndex = newPrev; - if(newPrev != -1) newLinks[newPrev] |= 0xFFFFFFFFL; - if(nullIndex != -1) { - nullIndex = newSize; - } - mask = newMask; - maxFill = Math.min((int)Math.ceil(newSize * loadFactor), newSize - 1); - keys = newKeys; - values = newValues; - } - - protected void onNodeRemoved(int pos) { - if(size == 0) firstIndex = lastIndex = -1; - else if(firstIndex == pos) { - firstIndex = (int)links[pos]; - if(0 <= firstIndex) links[firstIndex] |= 0xFFFFFFFF00000000L; - } - else if(lastIndex == pos) { - lastIndex = (int)(links[pos] >>> 32); - if(0 <= lastIndex) links[lastIndex] |= 0xFFFFFFFFL; - } - else { - long link = links[pos]; - int prev = (int)(link >>> 32); - int next = (int)link; - links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L); - } - } - - protected void onNodeMoved(int from, int to) { - if(size == 1) { - firstIndex = lastIndex = to; - links[to] = -1L; - } - else if(firstIndex == from) { - firstIndex = to; - links[(int)links[from]] ^= ((links[(int)links[from]] ^ ((to & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); - links[to] = links[from]; - } - else if(lastIndex == from) { - lastIndex = to; - links[(int)(links[from] >>> 32)] ^= ((links[(int)(links[from] >>> 32)] ^ (to & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - links[to] = links[from]; - } - else { - long link = links[from]; - int prev = (int)(link >>> 32); - int next = (int)link; - links[prev] ^= ((links[prev] ^ (to & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - links[next] ^= ((links[next] ^ ((to & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); - links[to] = link; - } - } - } -} +package speiger.src.collections.PACKAGE.maps.impl.concurrent; + +import java.util.Arrays; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Objects; +import java.util.concurrent.locks.StampedLock; +import java.util.function.Consumer; +import java.util.function.Predicate; +import java.util.function.BiFunction; +#if !TYPE_OBJECT && JDK_TYPE +import java.util.function.PREDICATE; +#endif +#if !SAME_TYPE && JDK_VALUE && !VALUE_OBJECT +import java.util.function.VALUE_PREDICATE; +#endif + +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; +#if SAME_TYPE +import speiger.src.collections.PACKAGE.collections.ITERATOR; +#endif +import speiger.src.collections.PACKAGE.functions.CONSUMER; +import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; +#endif +import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER; +#if !TYPE_OBJECT && !VALUE_OBJECT +import speiger.src.collections.ints.functions.consumer.IntObjectConsumer; +#endif +#if !SAME_TYPE && !TYPE_INT +import speiger.src.collections.ints.functions.consumer.VALUE_BI_FROM_INT_CONSUMER; +#endif +#if !TYPE_INT || !SAME_TYPE +import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; +#endif +#if !VALUE_BOOLEAN || !JDK_TYPE +import speiger.src.collections.PACKAGE.functions.function.FUNCTION; +#endif +import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; +#if !SAME_TYPE +import speiger.src.collections.PACKAGE.functions.function.SINGLE_UNARY_OPERATOR; +#endif +#if !TYPE_OBJECT && !VALUE_BOOLEAN && !JDK_TYPE +import speiger.src.collections.PACKAGE.functions.function.PREDICATE; +#endif +import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.CONCURRENT_MAP; +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET; +import speiger.src.collections.PACKAGE.sets.SET; +#endif +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; +import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_SUPPLIER; +#if !SAME_TYPE +import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR; + +#if !VALUE_OBJECT +#if !TYPE_OBJECT +import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator; +#endif + +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_BI_ITERATOR; +import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER; +#endif +#else if !VALUE_OBJECT +import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator; + +#endif +#if !TYPE_OBJECT && !VALUE_OBJECT || !VALUE_OBJECT +import speiger.src.collections.objects.functions.consumer.ObjectObjectConsumer; +#endif +#if !SAME_TYPE +#if !TYPE_OBJECT +import speiger.src.collections.objects.functions.consumer.VALUE_BI_FROM_OBJECT_CONSUMER; +#endif +#if !JDK_VALUE +import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE; +#endif +#endif +#if VALUE_OBJECT +import speiger.src.collections.objects.collections.ObjectIterator; +#endif +import speiger.src.collections.objects.collections.ObjectBidirectionalIterator; +import speiger.src.collections.objects.sets.AbstractObjectSet; +import speiger.src.collections.objects.sets.ObjectSet; +import speiger.src.collections.utils.HashUtil; +import speiger.src.collections.utils.ITrimmable; + +/** + * A TypeSpecific ConcurrentHashMap implementation that is based on Guavas approach and backing array implementations. + * Like Guavas implementation this solution can be accessed by multiple threads, but it is not as flexible as Javas implementation. + * The concurrencyLevel decides how many pools exist, and each pool can be accessed by 1 thread for writing and as many threads for reading. + * Though it is ill adviced to iterate over the collection using the Iterator if the Map is written to. Keep that in mind. + * + * + * @Type(T) + * @ValueType(V) + */ +public class CONCURRENT_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements CONCURRENT_MAP KEY_VALUE_GENERIC_TYPE, ITrimmable +{ + /** Segment Limit */ + private static final int MAX_SEGMENTS = 1 << 16; + /** Buckets of the ConcurrentMap */ + protected transient Segment KEY_VALUE_GENERIC_TYPE[] segments; + /** Bitshift of the HashCode */ + protected transient int segmentShift; + /** Max Bits thats used in the segments */ + protected transient int segmentMask; + /** EntrySet cache */ + protected transient FastEntrySet KEY_VALUE_GENERIC_TYPE entrySet; + /** KeySet cache */ + protected transient SET KEY_GENERIC_TYPE keySet; + /** Values cache */ + protected transient VALUE_COLLECTION VALUE_GENERIC_TYPE values; + + /** + * Copy constructor that doesn't trigger the building of segments and allows to copy it faster. + * @param unused not used, Just to keep all constructors accessible. + */ + protected CONCURRENT_HASH_MAP(boolean unused) {} + + /** + * Default Constructor + */ + public CONCURRENT_HASH_MAP() { + this(HashUtil.DEFAULT_MIN_CAPACITY, HashUtil.DEFAULT_LOAD_FACTOR, HashUtil.DEFAULT_MIN_CONCURRENCY); + } + + /** + * Constructor that defines the minimum capacity + * @param minCapacity the minimum capacity the HashMap is allowed to be. + * @throws IllegalStateException if the minimum capacity is negative + */ + public CONCURRENT_HASH_MAP(int minCapacity) { + this(minCapacity, HashUtil.DEFAULT_LOAD_FACTOR, HashUtil.DEFAULT_MIN_CONCURRENCY); + } + + /** + * Constructor that defines the minimum capacity and load factor + * @param minCapacity the minimum capacity the HashMap is allowed to be. + * @param loadFactor the percentage of how full the backing array can be before they resize + * @throws IllegalStateException if the minimum capacity is negative + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + */ + public CONCURRENT_HASH_MAP(int minCapacity, float loadFactor) { + this(minCapacity, loadFactor, HashUtil.DEFAULT_MIN_CONCURRENCY); + } + + /** + * Constructor that defines the minimum capacity and concurrencyLevel + * @param minCapacity the minimum capacity the HashMap is allowed to be. + * @param concurrencyLevel decides how many operations can be performed at once. + * @throws IllegalStateException if the minimum capacity is negative + * @throws IllegalStateException if the concurrencyLevel is either below/equal to 0 or above/equal to 65535 + */ + public CONCURRENT_HASH_MAP(int minCapacity, int concurrencyLevel) { + this(minCapacity, HashUtil.DEFAULT_LOAD_FACTOR, concurrencyLevel); + } + + /** + * Constructor that defines the load factor and concurrencyLevel + * @param loadFactor the percentage of how full the backing array can be before they resize + * @param concurrencyLevel decides how many operations can be performed at once. + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + * @throws IllegalStateException if the concurrencyLevel is either below/equal to 0 or above/equal to 65535 + */ + public CONCURRENT_HASH_MAP(float loadFactor, int concurrencyLevel) { + this(HashUtil.DEFAULT_MIN_CAPACITY, loadFactor, concurrencyLevel); + } + + /** + * Constructor that defines the minimum capacity, load factor and concurrencyLevel + * @param minCapacity the minimum capacity the HashMap is allowed to be. + * @param loadFactor the percentage of how full the backing array can be before they resize + * @param concurrencyLevel decides how many operations can be performed at once. + * @throws IllegalStateException if the minimum capacity is negative + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + * @throws IllegalStateException if the concurrencyLevel is either below/equal to 0 or above/equal to 65535 + */ + public CONCURRENT_HASH_MAP(int minCapacity, float loadFactor, int concurrencyLevel) { + if(minCapacity < 0) throw new IllegalStateException("Minimum Capacity is negative. This is not allowed"); + if(loadFactor <= 0 || loadFactor >= 1F) throw new IllegalStateException("Load Factor is not between 0 and 1"); + if(concurrencyLevel <= 0 || concurrencyLevel >= MAX_SEGMENTS) throw new IllegalStateException("concurrencyLevel has to be between 0 and 65536"); + int segmentCount = HashUtil.nextPowerOfTwo(concurrencyLevel); + int shift = Integer.numberOfTrailingZeros(segmentCount); + segments = new Segment[segmentCount]; + segmentShift = 32 - shift; + segmentMask = segmentCount - 1; + int segmentCapacity = minCapacity / segmentCount; + if(segmentCapacity * segmentCount < minCapacity) { + segmentCapacity++; + } + segmentCapacity = HashUtil.arraySize(segmentCapacity, loadFactor); + for(int i = 0;i map) { + this(map, HashUtil.DEFAULT_LOAD_FACTOR, HashUtil.DEFAULT_MIN_CONCURRENCY); + } + + /** + * A Helper constructor that allows to create a Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + * @param loadFactor the percentage of how full the backing array can be before they resize + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + */ + public CONCURRENT_HASH_MAP(Map map, float loadFactor) { + this(map, loadFactor, HashUtil.DEFAULT_MIN_CONCURRENCY); + } + + /** + * A Helper constructor that allows to create a Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + * @param concurrencyLevel decides how many operations can be performed at once. + * @throws IllegalStateException if the concurrencyLevel is either below/equal to 0 or above/equal to 65535 + */ + public CONCURRENT_HASH_MAP(Map map, int concurrencyLevel) { + this(map, HashUtil.DEFAULT_LOAD_FACTOR, concurrencyLevel); + } + + /** + * A Helper constructor that allows to create a Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + * @param loadFactor the percentage of how full the backing array can be before they resize + * @param concurrencyLevel decides how many operations can be performed at once. + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + * @throws IllegalStateException if the concurrencyLevel is either below/equal to 0 or above/equal to 65535 + */ + public CONCURRENT_HASH_MAP(Map map, float loadFactor, int concurrencyLevel) { + this(map.size(), loadFactor, concurrencyLevel); + putAll(map); + } + + /** + * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + */ + public CONCURRENT_HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map) { + this(map, HashUtil.DEFAULT_LOAD_FACTOR, HashUtil.DEFAULT_MIN_CONCURRENCY); + } + + /** + * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + * @param loadFactor the percentage of how full the backing array can be before they resize + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + */ + public CONCURRENT_HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map, float loadFactor) { + this(map, loadFactor, HashUtil.DEFAULT_MIN_CONCURRENCY); + } + + /** + * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + * @param concurrencyLevel decides how many operations can be performed at once. + * @throws IllegalStateException if the concurrencyLevel is either below/equal to 0 or above/equal to 65535 + */ + public CONCURRENT_HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map, int concurrencyLevel) { + this(map, HashUtil.DEFAULT_LOAD_FACTOR, concurrencyLevel); + } + + /** + * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + * @param loadFactor the percentage of how full the backing array can be before they resize + * @param concurrencyLevel decides how many operations can be performed at once. + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + * @throws IllegalStateException if the concurrencyLevel is either below/equal to 0 or above/equal to 65535 + */ + public CONCURRENT_HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map, float loadFactor, int concurrencyLevel) { + this(map.size(), loadFactor, concurrencyLevel); + putAll(map); + } + + @Override + public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { + int hash = getHashCode(key); + return getSegment(hash).put(hash, key, value); + } + + @Override + public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { + int hash = getHashCode(key); + return getSegment(hash).putIfAbsent(hash, key, value); + } + +#if VALUE_PRIMITIVES + @Override + public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { + int hash = getHashCode(key); + return getSegment(hash).addTo(hash, key, value); + } + + @Override + public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { + int hash = getHashCode(key); + return getSegment(hash).subFrom(hash, key, value); + } + +#endif + @Override + public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { + int hash = getHashCode(key); + return getSegment(hash).remove(hash, key); + } + +#if !TYPE_OBJECT || !VALUE_OBJECT + @Override + public boolean remove(KEY_TYPE key, VALUE_TYPE value) { + int hash = getHashCode(key); + return getSegment(hash).remove(hash, key, value); + } + +#endif + @Override + public boolean remove(Object key, Object value) { + int hash = getHashCode(key); + return getSegment(hash).remove(hash, key, value); + } + + @Override + public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { + int hash = getHashCode(key); + return getSegment(hash).removeOrDefault(hash, key, defaultValue); + } + + @Override + public VALUE_TYPE GET_VALUE(KEY_TYPE key) { + int hash = getHashCode(key); + return getSegment(hash).get(hash, key); + } + + @Override + public CLASS_VALUE_TYPE get(Object key) { + int hash = getHashCode(key); + return VALUE_TO_OBJ(getSegment(hash).get(hash, key)); + } + +#if TYPE_OBJECT && VALUE_OBJECT + @Override + public VALUE_TYPE getOrDefault(Object key, VALUE_TYPE defaultValue) { + int hash = getHashCode(key); + return getSegment(hash).getOrDefault(hash, key, defaultValue); + } + +#else + @Override + public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { + int hash = getHashCode(key); + return getSegment(hash).getOrDefault(hash, key, defaultValue); + } + +#endif + + @Override + public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { + for(int i = 0,m=segments.length;i 0) return false; + } + return true; + } + + @Override + public int size() { + long size = 0L; + for(int i = 0,m=segments.length;i Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)size; + } + + @Override + public ObjectSet ENTRY_SET() { + if(entrySet == null) entrySet = new MapEntrySet(); + return entrySet; + } + + @Override + public SET KEY_GENERIC_TYPE keySet() { + if(keySet == null) keySet = new KeySet(); + return keySet; + } + + @Override + public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { + if(values == null) values = new Values(); + return values; + } + + protected int getSegmentIndex(int hash) { + return (hash >>> segmentShift) & segmentMask; + } + + protected Segment KEY_VALUE_GENERIC_TYPE getSegment(int hash) { + return segments[(hash >>> segmentShift) & segmentMask]; + } + +#if !TYPE_OBJECT + protected int getHashCode(KEY_TYPE key) { + return HashUtil.mix(KEY_TO_HASH(key)); + } + +#endif + protected int getHashCode(Object obj) { + return HashUtil.mix(Objects.hashCode(obj)); + } + + private class MapEntrySet extends AbstractObjectSet implements MAP.FastEntrySet KEY_VALUE_GENERIC_TYPE { + @Override + public ObjectBidirectionalIterator iterator() { + return new EntryIterator(); + } + + @Override + public ObjectBidirectionalIterator fastIterator() { + return new FastEntryIterator(); + } + + @Override + public MapEntrySet copy() { throw new UnsupportedOperationException(); } + + @Override + public void forEach(Consumer action) { + for(int i = 0,m=segments.length;i action) { + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + for(int i = 0,m=segments.length;i action) { + Objects.requireNonNull(action); + int count = 0; + for(int i = 0,m=segments.length;i void forEach(E input, ObjectObjectConsumer action) { + Objects.requireNonNull(action); + for(int i = 0,m=segments.length;i filter) { + Objects.requireNonNull(filter); + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + for(int i = 0,m=segments.length;i filter) { + Objects.requireNonNull(filter); + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + for(int i = 0,m=segments.length;i filter) { + Objects.requireNonNull(filter); + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + for(int i = 0,m=segments.length;i E reduce(E identity, BiFunction operator) { + Objects.requireNonNull(operator); + E state = identity; + for(int i = 0,m=segments.length;i operator) { + Objects.requireNonNull(operator); + MAP.Entry KEY_VALUE_GENERIC_TYPE state = null; + boolean empty = true; + for(int i = 0,m=segments.length;i filter) { + Objects.requireNonNull(filter); + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + for(int i = 0,m=segments.length;i filter) { + Objects.requireNonNull(filter); + int result = 0; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + for(int i = 0,m=segments.length;i= 0) return VALUE_EQUALS(entry.ENTRY_VALUE(), seg.values[index]); + } + finally { + seg.unlockRead(stamp); + } + } + else { + Map.Entry entry = (Map.Entry)o; + int hash = getHashCode(entry.getKey()); + Segment KEY_VALUE_GENERIC_TYPE seg = getSegment(hash); + long stamp = seg.readLock(); + try { + int index = seg.findIndex(hash, entry.getKey()); + if(index >= 0) return Objects.equals(entry.getValue(), VALUE_TO_OBJ(seg.values[index])); + } + finally { + seg.unlockRead(stamp); + } + } + } + return false; + } + + @Override + @Deprecated + public boolean remove(Object o) { + if(o instanceof Map.Entry) { + if(o instanceof MAP.Entry) { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; + return CONCURRENT_HASH_MAP.this.remove(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); + } + Map.Entry entry = (Map.Entry)o; + return CONCURRENT_HASH_MAP.this.remove(entry.getKey(), entry.getValue()); + } + return false; + } + + @Override + public int size() { + return CONCURRENT_HASH_MAP.this.size(); + } + + @Override + public void clear() { + CONCURRENT_HASH_MAP.this.clear(); + } + } + + private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE implements SET KEY_GENERIC_TYPE { + + @Override + public boolean add(KEY_TYPE key) { throw new UnsupportedOperationException(); } + +#if TYPE_OBJECT + @Override + @Deprecated + public boolean contains(Object e) { + return containsKey(e); + } + + @Override + public boolean remove(Object o) { + int oldSize = size(); + CONCURRENT_HASH_MAP.this.remove(o); + return size() != oldSize; + } + +#else + @Override + public boolean contains(KEY_TYPE e) { + return containsKey(e); + } + + @Override + public boolean remove(KEY_TYPE o) { + int oldSize = size(); + CONCURRENT_HASH_MAP.this.remove(o); + return size() != oldSize; + } + +#endif + @Override + public BI_ITERATOR KEY_GENERIC_TYPE iterator() { + return new KeyIterator(); + } + + @Override + public KeySet copy() { throw new UnsupportedOperationException(); } + + @Override + public int size() { + return CONCURRENT_HASH_MAP.this.size(); + } + + @Override + public void clear() { + CONCURRENT_HASH_MAP.this.clear(); + } + + @Override + public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { + Objects.requireNonNull(action); + for(int i = 0,m=segments.length;i void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { + Objects.requireNonNull(action); + for(int i = 0,m=segments.length;i KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) { + Objects.requireNonNull(operator); + KEY_SPECIAL_TYPE state = identity; + for(int i = 0,m=segments.length;i void forEach(E input, VALUE_BI_FROM_OBJECT_CONSUMER VSV_GENERIC_TYPE action) { + Objects.requireNonNull(action); + for(int i = 0,m=segments.length;i VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction operator) { + Objects.requireNonNull(operator); + VALUE_SPECIAL_TYPE state = identity; + for(int i = 0,m=segments.length;i { + MapEntry entry = new MapEntry(); + + public FastEntryIterator() {} + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { + entry.set(nextEntry(), currentSegment()); + return entry; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { + entry.set(previousEntry(), currentSegment()); + return entry; + } + } + + private class EntryIterator extends MapIterator implements ObjectBidirectionalIterator { + MapEntry entry; + + public EntryIterator() {} + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { + return entry = new MapEntry(nextEntry(), currentSegment()); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { + return entry = new MapEntry(previousEntry(), currentSegment()); + } + + @Override + public void remove() { + super.remove(); + entry.clear(); + } + } + + private class ValueIterator extends MapIterator implements VALUE_BI_ITERATOR VALUE_GENERIC_TYPE { + public ValueIterator() {} + + @Override + public VALUE_TYPE VALUE_PREVIOUS() { + return entry(previousEntry(), currentSegment()); + } + + @Override + public VALUE_TYPE VALUE_NEXT() { + return entry(nextEntry(), currentSegment()); + } + + protected VALUE_TYPE entry(int entry, int segment) { + return segments[segment].values[entry]; + } + } + + private class KeyIterator extends MapIterator implements BI_ITERATOR KEY_GENERIC_TYPE { + + public KeyIterator() {} + + @Override + public KEY_TYPE PREVIOUS() { + return entry(previousEntry(), currentSegment()); + } + + @Override + public KEY_TYPE NEXT() { + return entry(nextEntry(), currentSegment()); + } + + protected KEY_TYPE entry(int entry, int segment) { + return segments[segment].keys[entry]; + } + } + + private class MapIterator { + int previous = -1; + int next = -1; + int current = -1; + int previousSegment = -1; + int nextSegment = -1; + int currentSegment = -1; + + MapIterator() { + currentSegment = getFirstSegment(); + if(currentSegment != -1) next = segments[currentSegment].firstIndex; + } + + public boolean hasNext() { + return next != -1 || nextSegment != -1; + } + + public boolean hasPrevious() { + return previous != -1 || previousSegment != -1; + } + + public int currentSegment() { + return currentSegment; + } + + public int previousEntry() { + if(!hasPrevious()) throw new NoSuchElementException(); + if(previousSegment != -1) { + nextSegment = currentSegment; + currentSegment = previousSegment; + previousSegment = -1; + next = current = segments[currentSegment].lastIndex; + } + else { + if(next != -1) nextSegment = -1; + next = current = previous; + } + findPreviousIndex(); + return current; + } + + public int nextEntry() { + if(!hasNext()) throw new NoSuchElementException(); + if(nextSegment != -1) { + previousSegment = currentSegment; + currentSegment = nextSegment; + nextSegment = -1; + previous = current = segments[currentSegment].firstIndex; + } + else { + if(previous != -1) previousSegment = -1; + previous = current = next; + } + findNextIndex(); + return current; + } + + public void remove() { + if(current == -1) throw new IllegalStateException(); + Segment KEY_VALUE_GENERIC_TYPE seg = segments[currentSegment]; + long stamp = seg.writeLock(); + try { + if(current == previous) findPreviousIndex(); + else findNextIndex(); + seg.size--; + if(previous == -1) seg.firstIndex = next; + else seg.links[previous] ^= ((seg.links[previous] ^ (next & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + + if(next == -1) seg.lastIndex = previous; + else seg.links[next] ^= ((seg.links[next] ^ ((previous & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); + + if(current == seg.nullIndex) { + current = -1; + seg.containsNull = false; + seg.keys[seg.nullIndex] = EMPTY_KEY_VALUE; + seg.values[seg.nullIndex] = EMPTY_VALUE; + } + else { + int slot, last, startPos = current; + current = -1; + KEY_TYPE current; + while(true) { + startPos = ((last = startPos) + 1) & seg.mask; + while(true){ + if(KEY_EQUALS_NULL((current = seg.keys[startPos]))) { + seg.keys[last] = EMPTY_KEY_VALUE; + seg.values[last] = EMPTY_VALUE; + return; + } + slot = HashUtil.mix(KEY_TO_HASH(current)) & seg.mask; + if(last <= startPos ? (last >= slot || slot > startPos) : (last >= slot && slot > startPos)) break; + startPos = ++startPos & seg.mask; + } + seg.keys[last] = current; + seg.values[last] = seg.values[startPos]; + if(next == startPos) next = last; + if(previous == startPos) previous = last; + seg.onNodeMoved(startPos, last); + } + } + } + finally { + seg.unlockWrite(stamp); + } + } + + protected void findPreviousIndex() { + previous = (int)(segments[currentSegment].links[current] >>> 32); + if(previous == -1) { + previousSegment = findPreviousSegment(currentSegment-1); + } + } + + protected void findNextIndex() { + next = (int)(segments[currentSegment].links[current]); + if(next == -1) { + nextSegment = findNextSegment(currentSegment+1); + } + } + + private int getFirstSegment() { + for(int i = 0,m=segments.length;i= segments.length ? -1 : index; + } + + private int findPreviousSegment(int index) { + for(;index >= 0 && segments[index].lastIndex == -1;index--); + return index >= 0 ? index : -1; + } + } + + protected class MapEntry implements MAP.Entry KEY_VALUE_GENERIC_TYPE, Map.Entry { + int index = -1; + int segmentIndex = -1; + + public MapEntry() {} + public MapEntry(int index, int segmentIndex) { + set(index, segmentIndex); + } + + public void set(int index, int segmentIndex) { + this.index = index; + this.segmentIndex = segmentIndex; + } + + public void clear() { + index = -1; + segmentIndex = -1; + } + + @Override + public KEY_TYPE ENTRY_KEY() { + return segments[segmentIndex].keys[index]; + } + + @Override + public VALUE_TYPE ENTRY_VALUE() { + return segments[segmentIndex].values[index]; + } + + @Override + public VALUE_TYPE setValue(VALUE_TYPE value) { + Segment KEY_VALUE_GENERIC_TYPE seg = segments[segmentIndex]; + long stamp = seg.writeLock(); + try + { + VALUE_TYPE oldValue = ENTRY_VALUE(); + seg.values[index] = value; + return oldValue; + } + finally { + seg.unlockWrite(stamp); + } + } + + @Override + public boolean equals(Object obj) { + if(obj instanceof Map.Entry) { + if(obj instanceof MAP.Entry) { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)obj; + return KEY_EQUALS(ENTRY_KEY(), entry.ENTRY_KEY()) && VALUE_EQUALS(ENTRY_VALUE(), entry.ENTRY_VALUE()); + } + Map.Entry entry = (Map.Entry)obj; + Object key = entry.getKey(); + Object value = entry.getValue(); +#if TYPE_OBJECT && VALUE_OBJECT + return KEY_EQUALS(ENTRY_KEY(), key) && VALUE_EQUALS(ENTRY_VALUE(), value); +#else if TYPE_OBJECT + return value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(ENTRY_KEY(), key) && VALUE_EQUALS(ENTRY_VALUE(), CLASS_TO_VALUE(value)); +#else if VALUE_OBJECT + return key instanceof CLASS_TYPE && KEY_EQUALS(ENTRY_KEY(), CLASS_TO_KEY(key)) && VALUE_EQUALS(ENTRY_VALUE(), value); +#else + return key instanceof CLASS_TYPE && value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(ENTRY_KEY(), CLASS_TO_KEY(key)) && VALUE_EQUALS(ENTRY_VALUE(), CLASS_TO_VALUE(value)); +#endif + } + return false; + } + + @Override + public int hashCode() { + return KEY_TO_HASH(ENTRY_KEY()) ^ VALUE_TO_HASH(ENTRY_VALUE()); + } + + @Override + public String toString() { + return KEY_TO_STRING(ENTRY_KEY()) + "=" + VALUE_TO_STRING(ENTRY_VALUE()); + } + } + + protected static class Segment KEY_VALUE_GENERIC_TYPE extends StampedLock + { + private static final long serialVersionUID = -446894977795760975L; + protected final CONCURRENT_HASH_MAP KEY_VALUE_GENERIC_TYPE map; + /** The Backing keys array */ + protected transient KEY_TYPE[] keys; + /** The Backing values array */ + protected transient VALUE_TYPE[] values; + /** The Backing array for links between nodes. Left 32 Bits => Previous Entry, Right 32 Bits => Next Entry */ + protected transient long[] links; + /** The First Index in the Map */ + protected int firstIndex = -1; + /** The Last Index in the Map */ + protected int lastIndex = -1; + /** If a null value is present */ + protected transient boolean containsNull; + /** Index of the Null Value */ + protected transient int nullIndex; + /** Maximum amount of Values that can be stored before the array gets expanded usually 75% */ + protected transient int maxFill; + /** Max Index that is allowed to be searched through nullIndex - 1 */ + protected transient int mask; + /** Amount of Elements stored in the HashMap */ + protected int size; + /** Minimum array size the Segment will be */ + protected transient int minCapacity; + /** How full the Arrays are allowed to get before resize */ + protected float loadFactor; + + protected Segment(CONCURRENT_HASH_MAP KEY_VALUE_GENERIC_TYPE map) { + this.map = map; + } + + protected Segment(CONCURRENT_HASH_MAP KEY_VALUE_GENERIC_TYPE map, int minCapacity, float loadFactor, boolean isNullContainer) { + this.map = map; + this.minCapacity = minCapacity; + this.loadFactor = loadFactor; + mask = minCapacity - 1; + maxFill = Math.min((int)Math.ceil(minCapacity * loadFactor), minCapacity - 1); + nullIndex = isNullContainer ? minCapacity : -1; + int arraySize = minCapacity + (isNullContainer ? 1 : 0); + keys = NEW_KEY_ARRAY(arraySize); + values = NEW_VALUE_ARRAY(arraySize); + links = new long[arraySize]; + } + + protected Segment KEY_VALUE_GENERIC_TYPE copy(CONCURRENT_HASH_MAP KEY_VALUE_GENERIC_TYPE newMap) { + long stamp = readLock(); + try + { + Segment KEY_VALUE_GENERIC_TYPE copy = new SegmentKV_BRACES(newMap); + copy.keys = Arrays.copyOf(keys, keys.length); + copy.values = Arrays.copyOf(values, values.length); + copy.links = Arrays.copyOf(links, links.length); + copy.firstIndex = firstIndex; + copy.lastIndex = lastIndex; + copy.containsNull = containsNull; + copy.nullIndex = nullIndex; + copy.maxFill = maxFill; + copy.mask = mask; + copy.size = size; + copy.minCapacity = minCapacity; + copy.loadFactor = loadFactor; + return copy; + } + finally { + unlockRead(stamp); + } + } + + protected VALUE_TYPE getDefaultReturnValue() { + return map.getDefaultReturnValue(); + } + + protected VALUE_TYPE put(int hash, KEY_TYPE key, VALUE_TYPE value) { + long stamp = writeLock(); + try { + int slot = findIndex(hash, key); + if(slot < 0) { + insert(-slot-1, key, value); + return getDefaultReturnValue(); + } + VALUE_TYPE oldValue = values[slot]; + values[slot] = value; + return oldValue; + } + finally { + unlockWrite(stamp); + } + } + + protected VALUE_TYPE putIfAbsent(int hash, KEY_TYPE key, VALUE_TYPE value) { + long stamp = writeLock(); + try { + int slot = findIndex(hash, key); + if(slot < 0) { + insert(-slot-1, key, value); + return getDefaultReturnValue(); + } + else if(VALUE_EQUALS(values[slot], getDefaultReturnValue())) { + VALUE_TYPE oldValue = values[slot]; + values[slot] = value; + return oldValue; + } + return values[slot]; + } + finally { + unlockWrite(stamp); + } + } + +#if VALUE_PRIMITIVES + protected VALUE_TYPE addTo(int hash, KEY_TYPE key, VALUE_TYPE value) { + long stamp = writeLock(); + try { + int slot = findIndex(hash, key); + if(slot < 0) { + insert(-slot-1, key, value); + return getDefaultReturnValue(); + } + VALUE_TYPE oldValue = values[slot]; + values[slot] += value; + return oldValue; + } + finally { + unlockWrite(stamp); + } + } + + protected VALUE_TYPE subFrom(int hash, KEY_TYPE key, VALUE_TYPE value) { + long stamp = writeLock(); + try { + int slot = findIndex(hash, key); + if(slot < 0) return getDefaultReturnValue(); + VALUE_TYPE oldValue = values[slot]; + values[slot] -= value; + if(value < 0 ? (values[slot] >= getDefaultReturnValue()) : (values[slot] <= getDefaultReturnValue())) removeIndex(slot); + return oldValue; + } + finally { + unlockWrite(stamp); + } + } +#endif + +#if !TYPE_OBJECT + protected boolean containsKey(int hash, KEY_TYPE key) { + long stamp = readLock(); + try { + return findIndex(hash, key) >= 0; + } + finally { + unlockRead(stamp); + } + } + +#endif + @Deprecated + protected boolean containsKey(int hash, Object key) { + long stamp = readLock(); + try { + return findIndex(hash, key) >= 0; + } + finally { + unlockRead(stamp); + } + } + +#if !VALUE_OBJECT + protected boolean containsValue(VALUE_TYPE value) { + long stamp = readLock(); + try { + int index = firstIndex; + while(index != -1) { + if(VALUE_EQUALS(values[index], value)) return true; + index = (int)links[index]; + } + return false; + } + finally { + unlockRead(stamp); + } + } + +#endif + @Deprecated + protected boolean containsValue(Object value) { + long stamp = readLock(); + try { + int index = firstIndex; + while(index != -1) { +#if VALUE_OBJECT + if(VALUE_EQUALS(values[index], value)) return true; +#else + if((value == null && values[index] == getDefaultReturnValue()) || EQUALS_VALUE_TYPE(values[index], value)) return true; +#endif + index = (int)links[index]; + } + return false; + } + finally { + unlockRead(stamp); + } + } + +#if !TYPE_OBJECT + protected VALUE_TYPE get(int hash, KEY_TYPE key) { + long stamp = readLock(); + try { + int slot = findIndex(hash, key); + return slot < 0 ? getDefaultReturnValue() : values[slot]; + } + finally { + unlockRead(stamp); + } + } + +#endif + protected VALUE_TYPE get(int hash, Object key) { + long stamp = readLock(); + try { + int slot = findIndex(hash, key); + return slot < 0 ? getDefaultReturnValue() : values[slot]; + } + finally { + unlockRead(stamp); + } + } + +#if TYPE_OBJECT && VALUE_OBJECT + protected VALUE_TYPE getOrDefault(int hash, Object key, VALUE_TYPE defaultValue) { + long stamp = readLock(); + try { + int slot = findIndex(hash, key); + return slot < 0 ? defaultValue : values[slot]; + } + finally { + unlockRead(stamp); + } + } + +#else + protected VALUE_TYPE getOrDefault(int hash, KEY_TYPE key, VALUE_TYPE defaultValue) { + long stamp = readLock(); + try { + int slot = findIndex(hash, key); + return slot < 0 ? defaultValue : values[slot]; + } + finally { + unlockRead(stamp); + } + } + +#endif + protected void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { + long stamp = readLock(); + try { + int index = firstIndex; + while(index != -1) { + action.accept(keys[index], values[index]); + index = (int)links[index]; + } + } + finally { + unlockRead(stamp); + } + } + +#if !TYPE_OBJECT + protected VALUE_TYPE remove(int hash, KEY_TYPE key) { + long stamp = writeLock(); + try { + int slot = findIndex(hash, key); + if(slot < 0) return getDefaultReturnValue(); + return removeIndex(slot); + } + finally { + unlockWrite(stamp); + } + } + +#endif + protected VALUE_TYPE removeOrDefault(int hash, KEY_TYPE key, VALUE_TYPE defaultValue) { + long stamp = writeLock(); + try { + int slot = findIndex(hash, key); + if(slot < 0) return defaultValue; + return removeIndex(slot); + } + finally { + unlockWrite(stamp); + } + } + + protected CLASS_VALUE_TYPE remove(int hash, Object key) { + long stamp = writeLock(); + try { + int slot = findIndex(hash, key); + if(slot < 0) return VALUE_TO_OBJ(getDefaultReturnValue()); + return VALUE_TO_OBJ(removeIndex(slot)); + } + finally { + unlockWrite(stamp); + } + } + +#if !TYPE_OBJECT || !VALUE_OBJECT + protected boolean remove(int hash, KEY_TYPE key, VALUE_TYPE value) { + long stamp = writeLock(); + try { + if(KEY_EQUALS_NULL(key)) { + if(containsNull && VALUE_EQUALS(value, values[nullIndex])) { + removeNullIndex(); + return true; + } + return false; + } + int pos = hash & mask; + KEY_TYPE current = keys[pos]; + if(KEY_EQUALS_NULL(current)) return false; + if(KEY_EQUALS(current, key) && VALUE_EQUALS(value, values[pos])) { + removeIndex(pos); + return true; + } + while(true) { + if(KEY_EQUALS_NULL((current = keys[pos = (++pos & mask)]))) return false; + else if(KEY_EQUALS(current, key) && VALUE_EQUALS(value, values[pos])) { + removeIndex(pos); + return true; + } + } + } + finally { + unlockWrite(stamp); + } + } + +#endif + protected boolean remove(int hash, Object key, Object value) { + long stamp = writeLock(); + try + { +#if TYPE_OBJECT + if(key == null) { +#else + if(key == null || (key instanceof CLASS_TYPE && KEY_EQUALS_NULL(CLASS_TO_KEY(key)))) { +#endif + if(containsNull && EQUALS_VALUE_TYPE(values[nullIndex], value)) { + removeNullIndex(); + return true; + } + return false; + } + int pos = hash & mask; + KEY_TYPE current = keys[pos]; + if(KEY_EQUALS_NULL(current)) return false; + if(EQUALS_KEY_TYPE(current, key) && EQUALS_VALUE_TYPE(values[pos], value)) { + removeIndex(pos); + return true; + } + while(true) { + if(KEY_EQUALS_NULL((current = keys[pos = (++pos & mask)]))) return false; + else if(EQUALS_KEY_TYPE(current, key) && EQUALS_VALUE_TYPE(values[pos], value)){ + removeIndex(pos); + return true; + } + } + } + finally { + unlockWrite(stamp); + } + } + + protected boolean replace(int hash, KEY_TYPE key, VALUE_TYPE oldValue, VALUE_TYPE newValue) { + long stamp = writeLock(); + try { + int index = findIndex(hash, key); + if(index < 0 || values[index] != oldValue) return false; + values[index] = newValue; + return true; + } + finally { + unlockWrite(stamp); + } + } + + protected VALUE_TYPE replace(int hash, KEY_TYPE key, VALUE_TYPE value) { + long stamp = writeLock(); + try { + int index = findIndex(hash, key); + if(index < 0) return getDefaultReturnValue(); + VALUE_TYPE oldValue = values[index]; + values[index] = value; + return oldValue; + } + finally { + unlockWrite(stamp); + } + } + + protected VALUE_TYPE compute(int hash, KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { + long stamp = writeLock(); + try { + int index = findIndex(hash, key); + if(index < 0) { + VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, getDefaultReturnValue()); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + insert(-index-1, key, newValue); + return newValue; + } + VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, values[index]); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + removeIndex(index); + return newValue; + } + values[index] = newValue; + return newValue; + } + finally { + unlockWrite(stamp); + } + } + + protected VALUE_TYPE computeIfAbsent(int hash, KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) { + long stamp = writeLock(); + try { + int index = findIndex(hash, key); + if(index < 0) { + VALUE_TYPE newValue = mappingFunction.APPLY(key); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + insert(-index-1, key, newValue); + return newValue; + } + VALUE_TYPE newValue = values[index]; + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + newValue = mappingFunction.APPLY(key); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + values[index] = newValue; + } + return newValue; + } + finally { + unlockWrite(stamp); + } + } + + protected VALUE_TYPE supplyIfAbsent(int hash, KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) { + long stamp = writeLock(); + try { + int index = findIndex(hash, key); + if(index < 0) { + VALUE_TYPE newValue = valueProvider.VALUE_SUPPLY_GET(); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + insert(-index-1, key, newValue); + return newValue; + } + VALUE_TYPE newValue = values[index]; + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + newValue = valueProvider.VALUE_SUPPLY_GET(); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + values[index] = newValue; + } + return newValue; + } + finally { + unlockWrite(stamp); + } + } + + protected VALUE_TYPE computeIfPresent(int hash, KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { + long stamp = writeLock(); + try { + int index = findIndex(hash, key); + if(index < 0 || VALUE_EQUALS(values[index], getDefaultReturnValue())) return getDefaultReturnValue(); + VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, values[index]); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + removeIndex(index); + return newValue; + } + values[index] = newValue; + return newValue; + } + finally { + unlockWrite(stamp); + } + } + + protected VALUE_TYPE merge(int hash, KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { + long stamp = writeLock(); + try { + int index = findIndex(hash, key); + VALUE_TYPE newValue = index < 0 || VALUE_EQUALS(values[index], getDefaultReturnValue()) ? value : mappingFunction.APPLY_VALUE(values[index], value); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + if(index >= 0) + removeIndex(index); + } + else if(index < 0) insert(-index-1, key, newValue); + else values[index] = newValue; + return newValue; + } + finally { + unlockWrite(stamp); + } + } + + protected void clear() { + if(size == 0) return; + long stamp = writeLock(); + try { + size = 0; + containsNull = false; + Arrays.fill(keys, EMPTY_KEY_VALUE); + Arrays.fill(values, EMPTY_VALUE); + firstIndex = -1; + lastIndex = -1; + } + finally { + unlockWrite(stamp); + } + } + + protected boolean trim(int size) { + int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor))); + if(request >= mask+1 || this.size > Math.min((int)Math.ceil(request * loadFactor), request - 1)) return false; + long stamp = writeLock(); + try { + try { + rehash(request); + } + catch(OutOfMemoryError noMemory) { return false; } + return true; + } + finally { + unlockWrite(stamp); + } + } + + protected void clearAndTrim(int size) { + int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor))); + if(request >= mask+1) { + clear(); + return; + } + long stamp = writeLock(); + try { + if(nullIndex != -1) { + nullIndex = request; + } + mask = request-1; + maxFill = Math.min((int)Math.ceil(request * loadFactor), request - 1); + int arraySize = request + (nullIndex != -1 ? 1 : 0); + keys = NEW_KEY_ARRAY(arraySize); + values = NEW_VALUE_ARRAY(arraySize); + links = new long[arraySize]; + this.size = 0; + firstIndex = -1; + lastIndex = -1; + containsNull = false; + } + finally { + unlockWrite(stamp); + } + } + + protected void insert(int slot, KEY_TYPE key, VALUE_TYPE value) { + if(slot == nullIndex) containsNull = true; + keys[slot] = key; + values[slot] = value; + if(size == 0) { + firstIndex = lastIndex = slot; + links[slot] = -1L; + } + else { + links[lastIndex] ^= ((links[lastIndex] ^ (slot & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + links[slot] = ((lastIndex & 0xFFFFFFFFL) << 32) | 0xFFFFFFFFL; + lastIndex = slot; + } + if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor)); + } + + protected VALUE_TYPE removeIndex(int pos) { + if(pos == nullIndex) return containsNull ? removeNullIndex() : getDefaultReturnValue(); + VALUE_TYPE value = values[pos]; + keys[pos] = EMPTY_KEY_VALUE; + values[pos] = EMPTY_VALUE; + size--; + onNodeRemoved(pos); + shiftKeys(pos); + if(nullIndex > minCapacity && size < maxFill / 4 && nullIndex > HashUtil.DEFAULT_MIN_CAPACITY) rehash(nullIndex / 2); + return value; + } + + protected VALUE_TYPE removeNullIndex() { + VALUE_TYPE value = values[nullIndex]; + containsNull = false; + keys[nullIndex] = EMPTY_KEY_VALUE; + values[nullIndex] = EMPTY_VALUE; + size--; + onNodeRemoved(nullIndex); + if(nullIndex > minCapacity && size < maxFill / 4 && nullIndex > HashUtil.DEFAULT_MIN_CAPACITY) rehash(nullIndex / 2); + return value; + } + +#if !TYPE_OBJECT + protected int findIndex(int hash, KEY_TYPE key) { + if(KEY_EQUALS_NULL(key)) return containsNull ? nullIndex : -(nullIndex + 1); + int pos = hash & mask; + KEY_TYPE current = keys[pos]; + if(KEY_EQUALS_NOT_NULL(current)) { + if(KEY_EQUALS(current, key)) return pos; + while(KEY_EQUALS_NOT_NULL((current = keys[pos = (++pos & mask)]))) + if(KEY_EQUALS(current, key)) return pos; + } + return -(pos + 1); + } + +#endif + protected int findIndex(int hash, Object key) { + if(key == null) return containsNull ? nullIndex : -(nullIndex + 1); +#if !TYPE_OBJECT + if(KEY_EQUALS_NULL(CLASS_TO_KEY(key))) return containsNull ? nullIndex : -(nullIndex + 1); +#endif + int pos = hash & mask; + KEY_TYPE current = keys[pos]; + if(KEY_EQUALS_NOT_NULL(current)) { + if(EQUALS_KEY_TYPE(current, key)) return pos; + while(KEY_EQUALS_NOT_NULL((current = keys[pos = (++pos & mask)]))) + if(EQUALS_KEY_TYPE(current, key)) return pos; + } + return -(pos + 1); + } + + protected void shiftKeys(int startPos) { + int slot, last; + KEY_TYPE current; + while(true) { + startPos = ((last = startPos) + 1) & mask; + while(true){ + if(KEY_EQUALS_NULL((current = keys[startPos]))) { + keys[last] = EMPTY_KEY_VALUE; + values[last] = EMPTY_VALUE; + return; + } + slot = HashUtil.mix(KEY_TO_HASH(current)) & mask; + if(last <= startPos ? (last >= slot || slot > startPos) : (last >= slot && slot > startPos)) break; + startPos = ++startPos & mask; + } + keys[last] = current; + values[last] = values[startPos]; + onNodeMoved(startPos, last); + } + } + + protected void rehash(int newSize) { + int newMask = newSize - 1; + int arraySize = newSize + (nullIndex != -1 ? 1 : 0); + KEY_TYPE[] newKeys = NEW_KEY_ARRAY(arraySize); + VALUE_TYPE[] newValues = NEW_VALUE_ARRAY(arraySize); + long[] newLinks = new long[arraySize]; + int i = firstIndex, prev = -1, newPrev = -1, pos; + firstIndex = -1; + for(int j = size; j-- != 0;) { + if(KEY_EQUALS_NULL(keys[i])) pos = newSize; + else { + pos = HashUtil.mix(KEY_TO_HASH(keys[i])) & newMask; + while(KEY_EQUALS_NOT_NULL(newKeys[pos])) pos = ++pos & newMask; + } + newKeys[pos] = keys[i]; + newValues[pos] = values[i]; + if(prev != -1) { + newLinks[newPrev] ^= ((newLinks[newPrev] ^ (pos & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + newLinks[pos] ^= ((newLinks[pos] ^ ((newPrev & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); + newPrev = pos; + } + else { + newPrev = firstIndex = pos; + newLinks[pos] = -1L; + } + i = (int)links[prev = i]; + } + links = newLinks; + lastIndex = newPrev; + if(newPrev != -1) newLinks[newPrev] |= 0xFFFFFFFFL; + if(nullIndex != -1) { + nullIndex = newSize; + } + mask = newMask; + maxFill = Math.min((int)Math.ceil(newSize * loadFactor), newSize - 1); + keys = newKeys; + values = newValues; + } + + protected void onNodeRemoved(int pos) { + if(size == 0) firstIndex = lastIndex = -1; + else if(firstIndex == pos) { + firstIndex = (int)links[pos]; + if(0 <= firstIndex) links[firstIndex] |= 0xFFFFFFFF00000000L; + } + else if(lastIndex == pos) { + lastIndex = (int)(links[pos] >>> 32); + if(0 <= lastIndex) links[lastIndex] |= 0xFFFFFFFFL; + } + else { + long link = links[pos]; + int prev = (int)(link >>> 32); + int next = (int)link; + links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L); + } + } + + protected void onNodeMoved(int from, int to) { + if(size == 1) { + firstIndex = lastIndex = to; + links[to] = -1L; + } + else if(firstIndex == from) { + firstIndex = to; + links[(int)links[from]] ^= ((links[(int)links[from]] ^ ((to & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); + links[to] = links[from]; + } + else if(lastIndex == from) { + lastIndex = to; + links[(int)(links[from] >>> 32)] ^= ((links[(int)(links[from] >>> 32)] ^ (to & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + links[to] = links[from]; + } + else { + long link = links[from]; + int prev = (int)(link >>> 32); + int next = (int)link; + links[prev] ^= ((links[prev] ^ (to & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + links[next] ^= ((links[next] ^ ((to & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); + links[to] = link; + } + } + } +} diff --git a/src/builder/resources/speiger/assets/collections/templates/maps/impl/customHash/LinkedOpenCustomHashMap.template b/src/builder/resources/speiger/assets/collections/templates/maps/impl/customHash/LinkedOpenCustomHashMap.template index 85bcf7d..e154cb6 100644 --- a/src/builder/resources/speiger/assets/collections/templates/maps/impl/customHash/LinkedOpenCustomHashMap.template +++ b/src/builder/resources/speiger/assets/collections/templates/maps/impl/customHash/LinkedOpenCustomHashMap.template @@ -1,1512 +1,1514 @@ -package speiger.src.collections.PACKAGE.maps.impl.customHash; - -import java.util.Arrays; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Objects; -import java.util.function.Consumer; -import java.util.function.BiFunction; -import java.util.function.Predicate; -#if !TYPE_OBJECT && JDK_TYPE -import java.util.function.PREDICATE; -#endif -#if !SAME_TYPE && JDK_VALUE && !VALUE_OBJECT -import java.util.function.VALUE_PREDICATE; -#endif - -import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.functions.CONSUMER; -import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; -#endif -import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER; -#if !TYPE_OBJECT && !VALUE_OBJECT -import speiger.src.collections.ints.functions.consumer.IntObjectConsumer; -#endif -#if !SAME_TYPE -import speiger.src.collections.ints.functions.consumer.VALUE_BI_FROM_INT_CONSUMER; -#endif -#if !TYPE_OBJECT && !JDK_TYPE -import speiger.src.collections.PACKAGE.functions.function.PREDICATE; -#endif -import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; -import speiger.src.collections.PACKAGE.functions.function.SINGLE_UNARY_OPERATOR; -import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP; -import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET; -import speiger.src.collections.PACKAGE.sets.ORDERED_SET; -import speiger.src.collections.PACKAGE.utils.STRATEGY; -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; -#if !SAME_TYPE -import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR; -#endif -#if !VALUE_OBJECT && !SAME_TYPE -import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER; -import speiger.src.collections.VALUE_PACKAGE.lists.VALUE_LIST_ITERATOR; -#endif -#if !TYPE_OBJECT && !VALUE_OBJECT || !VALUE_OBJECT -import speiger.src.collections.objects.functions.consumer.ObjectObjectConsumer; -#endif -#if !SAME_TYPE -#if !TYPE_OBJECT -import speiger.src.collections.objects.functions.consumer.VALUE_BI_FROM_OBJECT_CONSUMER; - -#endif -#if !JDK_VALUE -import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE; -#endif -#endif -#if !TYPE_OBJECT -#if !VALUE_OBJECT -import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator; - -#endif -import speiger.src.collections.objects.collections.ObjectBidirectionalIterator; -import speiger.src.collections.objects.lists.ObjectListIterator; -import speiger.src.collections.objects.sets.AbstractObjectSet; -import speiger.src.collections.objects.sets.ObjectOrderedSet; -#endif -import speiger.src.collections.utils.HashUtil; - -/** - * A Type Specific LinkedHashMap that allows for custom HashControl. That uses arrays to create links between nodes. - * For cases where Objects/primitive do not allow hashcoding this can be really useful and provide a lot of control. - * This implementation of SortedMap does not support SubMaps of any kind. It implements the interface due to sortability and first/last access - * @Type(T) - * @ValueType(V) - */ -public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE implements ORDERED_MAP KEY_VALUE_GENERIC_TYPE -{ - /** The Backing array for links between nodes. Left 32 Bits => Previous Entry, Right 32 Bits => Next Entry */ - protected transient long[] links; - /** The First Index in the Map */ - protected int firstIndex = -1; - /** The Last Index in the Map */ - protected int lastIndex = -1; - - /** - * Default Constructor - * @param strategy the strategy that allows hash control. - * @throws NullPointerException if Strategy is null - */ - public LINKED_CUSTOM_HASH_MAP(STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { - this(HashUtil.DEFAULT_MIN_CAPACITY, HashUtil.DEFAULT_LOAD_FACTOR, strategy); - } - - /** - * Constructor that defines the minimum capacity - * @param minCapacity the minimum capacity the HashMap is allowed to be. - * @param strategy the strategy that allows hash control. - * @throws NullPointerException if Strategy is null - * @throws IllegalStateException if the minimum capacity is negative - */ - public LINKED_CUSTOM_HASH_MAP(int minCapacity, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { - this(minCapacity, HashUtil.DEFAULT_LOAD_FACTOR, strategy); - } - - /** - * Constructor that defines the minimum capacity and load factor - * @param minCapacity the minimum capacity the HashMap is allowed to be. - * @param loadFactor the percentage of how full the backing array can be before they resize - * @param strategy the strategy that allows hash control. - * @throws NullPointerException if Strategy is null - * @throws IllegalStateException if the minimum capacity is negative - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - */ - public LINKED_CUSTOM_HASH_MAP(int minCapacity, float loadFactor, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { - super(minCapacity, loadFactor, strategy); - links = new long[nullIndex + 1]; - } - -#if !TYPE_OBJECT || !VALUE_OBJECT - /** - * Helper constructor that allow to create a map from boxed values (it will unbox them) - * @param keys the keys that should be put into the map - * @param values the values that should be put into the map. - * @param strategy the strategy that allows hash control. - * @throws NullPointerException if Strategy is null - * @throws IllegalStateException if the keys and values do not match in lenght - */ - public LINKED_CUSTOM_HASH_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { - this(keys, values, HashUtil.DEFAULT_LOAD_FACTOR, strategy); - } - - /** - * Helper constructor that allow to create a map from boxed values (it will unbox them) - * @param keys the keys that should be put into the map - * @param values the values that should be put into the map. - * @param loadFactor the percentage of how full the backing array can be before they resize - * @param strategy the strategy that allows hash control. - * @throws NullPointerException if Strategy is null - * @throws IllegalStateException if the keys and values do not match in lenght - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - */ - public LINKED_CUSTOM_HASH_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, float loadFactor, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { - this(keys.length, loadFactor, strategy); - if(keys.length != values.length) throw new IllegalStateException("Input Arrays are not equal size"); - for(int i = 0,m=keys.length;i map, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { - this(map, HashUtil.DEFAULT_LOAD_FACTOR, strategy); - } - - /** - * A Helper constructor that allows to create a Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - * @param loadFactor the percentage of how full the backing array can be before they resize - * @param strategy the strategy that allows hash control. - * @throws NullPointerException if Strategy is null - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - */ - public LINKED_CUSTOM_HASH_MAP(Map map, float loadFactor, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { - this(map.size(), loadFactor, strategy); - putAll(map); - } - - /** - * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - * @param strategy the strategy that allows hash control. - * @throws NullPointerException if Strategy is null - */ - public LINKED_CUSTOM_HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { - this(map, HashUtil.DEFAULT_LOAD_FACTOR, strategy); - } - - /** - * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - * @param loadFactor the percentage of how full the backing array can be before they resize - * @param strategy the strategy that allows hash control. - * @throws NullPointerException if Strategy is null - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - */ - public LINKED_CUSTOM_HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map, float loadFactor, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { - this(map.size(), loadFactor, strategy); - putAll(map); - } - - @Override - public VALUE_TYPE putAndMoveToFirst(KEY_TYPE key, VALUE_TYPE value) { - if(strategy.equals(key, EMPTY_KEY_VALUE)) { - if(containsNull) { - VALUE_TYPE lastValue = values[nullIndex]; - values[nullIndex] = value; - moveToFirstIndex(nullIndex); - return lastValue; - } - values[nullIndex] = value; - containsNull = true; - onNodeAdded(nullIndex); - moveToFirstIndex(nullIndex); - } - else { - int pos = HashUtil.mix(strategy.hashCode(key)) & mask; - while(!strategy.equals(keys[pos], EMPTY_KEY_VALUE)) { - if(strategy.equals(keys[pos], key)) { - VALUE_TYPE lastValue = values[pos]; - values[pos] = value; - moveToFirstIndex(pos); - return lastValue; - } - pos = ++pos & mask; - } - keys[pos] = key; - values[pos] = value; - onNodeAdded(pos); - moveToFirstIndex(pos); - } - if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor)); - return getDefaultReturnValue(); - } - - @Override - public VALUE_TYPE putAndMoveToLast(KEY_TYPE key, VALUE_TYPE value) { - if(strategy.equals(key, EMPTY_KEY_VALUE)) { - if(containsNull) { - VALUE_TYPE lastValue = values[nullIndex]; - values[nullIndex] = value; - moveToLastIndex(nullIndex); - return lastValue; - } - values[nullIndex] = value; - containsNull = true; - onNodeAdded(nullIndex); - moveToLastIndex(nullIndex); - } - else { - int pos = HashUtil.mix(strategy.hashCode(key)) & mask; - while(!strategy.equals(keys[pos], EMPTY_KEY_VALUE)) { - if(strategy.equals(keys[pos], key)) { - VALUE_TYPE lastValue = values[pos]; - values[pos] = value; - moveToLastIndex(pos); - return lastValue; - } - pos = ++pos & mask; - } - keys[pos] = key; - values[pos] = value; - onNodeAdded(pos); - moveToLastIndex(pos); - } - if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor)); - return getDefaultReturnValue(); - } - - @Override - public boolean moveToFirst(KEY_TYPE key) { - if(isEmpty() || strategy.equals(FIRST_ENTRY_KEY(), key)) return false; - if(strategy.equals(key, EMPTY_KEY_VALUE)) { - if(containsNull) { - moveToFirstIndex(nullIndex); - return true; - } - } - else { - int pos = HashUtil.mix(strategy.hashCode(key)) & mask; - while(!strategy.equals(keys[pos], EMPTY_KEY_VALUE)) { - if(strategy.equals(keys[pos], key)) { - moveToFirstIndex(pos); - return true; - } - pos = ++pos & mask; - } - } - return false; - } - - @Override - public boolean moveToLast(KEY_TYPE key) { - if(isEmpty() || strategy.equals(LAST_ENTRY_KEY(), key)) return false; - if(strategy.equals(key, EMPTY_KEY_VALUE)) { - if(containsNull) { - moveToLastIndex(nullIndex); - return true; - } - } - else { - int pos = HashUtil.mix(strategy.hashCode(key)) & mask; - while(!strategy.equals(keys[pos], EMPTY_KEY_VALUE)) { - if(strategy.equals(keys[pos], key)) { - moveToLastIndex(pos); - return true; - } - pos = ++pos & mask; - } - } - return false; - } - - @Override - public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key) { - int index = findIndex(key); - if(index < 0) return getDefaultReturnValue(); - moveToFirstIndex(index); - return values[index]; - } - - @Override - public VALUE_TYPE getAndMoveToLast(KEY_TYPE key) { - int index = findIndex(key); - if(index < 0) return getDefaultReturnValue(); - moveToLastIndex(index); - return values[index]; - } - - @Override - public LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE copy() { - LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE map = new LINKED_CUSTOM_HASH_MAPKV_BRACES(0, loadFactor, strategy); - map.minCapacity = minCapacity; - map.mask = mask; - map.maxFill = maxFill; - map.nullIndex = nullIndex; - map.containsNull = containsNull; - map.size = size; - map.keys = Arrays.copyOf(keys, keys.length); - map.values = Arrays.copyOf(values, values.length); - map.links = Arrays.copyOf(links, links.length); - map.firstIndex = firstIndex; - map.lastIndex = lastIndex; - return map; - } - - @Override - public KEY_TYPE FIRST_ENTRY_KEY() { - if(size == 0) throw new NoSuchElementException(); - return keys[firstIndex]; - } - - @Override - public KEY_TYPE POLL_FIRST_ENTRY_KEY() { - if(size == 0) throw new NoSuchElementException(); - int pos = firstIndex; - onNodeRemoved(pos); - KEY_TYPE result = keys[pos]; - size--; - if(strategy.equals(result, EMPTY_KEY_VALUE)) { - containsNull = false; - keys[nullIndex] = EMPTY_KEY_VALUE; - values[nullIndex] = EMPTY_VALUE; - } - else shiftKeys(pos); - if(nullIndex > minCapacity && size < maxFill / 4 && nullIndex > HashUtil.DEFAULT_MIN_CAPACITY) rehash(nullIndex / 2); - return result; - } - - @Override - public KEY_TYPE LAST_ENTRY_KEY() { - if(size == 0) throw new NoSuchElementException(); - return keys[lastIndex]; - } - - @Override - public KEY_TYPE POLL_LAST_ENTRY_KEY() { - if(size == 0) throw new NoSuchElementException(); - int pos = lastIndex; - onNodeRemoved(pos); - KEY_TYPE result = keys[pos]; - size--; - if(strategy.equals(result, EMPTY_KEY_VALUE)) { - containsNull = false; - keys[nullIndex] = EMPTY_KEY_VALUE; - values[nullIndex] = EMPTY_VALUE; - } - else shiftKeys(pos); - if(nullIndex > minCapacity && size < maxFill / 4 && nullIndex > HashUtil.DEFAULT_MIN_CAPACITY) rehash(nullIndex / 2); - return result; - } - - @Override - public VALUE_TYPE FIRST_ENTRY_VALUE() { - if(size == 0) throw new NoSuchElementException(); - return values[firstIndex]; - } - - @Override - public VALUE_TYPE LAST_ENTRY_VALUE() { - if(size == 0) throw new NoSuchElementException(); - return values[lastIndex]; - } - - @Override - public ObjectOrderedSet ENTRY_SET() { - if(entrySet == null) entrySet = new MapEntrySet(); - return (ObjectOrderedSet)entrySet; - } - - @Override - public ORDERED_SET KEY_GENERIC_TYPE keySet() { - if(keySet == null) keySet = new KeySet(); - return (ORDERED_SET KEY_GENERIC_TYPE)keySet; - } - - @Override - public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { - if(valuesC == null) valuesC = new Values(); - return valuesC; - } - - @Override - public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { - int index = firstIndex; - while(index != -1){ - action.accept(keys[index], values[index]); - index = (int)links[index]; - } - } - - @Override - public void clear() { - super.clear(); - firstIndex = lastIndex = -1; - } - - @Override - public void clearAndTrim(int size) { - int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor))); - if(request >= nullIndex) { - clear(); - return; - } - nullIndex = request; - mask = request-1; - maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1); - keys = NEW_KEY_ARRAY(request + 1); - values = NEW_VALUE_ARRAY(request + 1); - links = new long[request + 1]; - firstIndex = lastIndex = -1; - this.size = 0; - containsNull = false; - } - - protected void moveToFirstIndex(int startPos) { - if(size == 1 || firstIndex == startPos) return; - if(lastIndex == startPos) { - lastIndex = (int)(links[startPos] >>> 32); - links[lastIndex] |= 0xFFFFFFFFL; - } - else { - long link = links[startPos]; - int prev = (int)(link >>> 32); - int next = (int)link; - links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L); - } - links[firstIndex] ^= ((links[firstIndex] ^ ((startPos & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); - links[startPos] = 0xFFFFFFFF00000000L | (firstIndex & 0xFFFFFFFFL); - firstIndex = startPos; - } - - protected void moveToLastIndex(int startPos) { - if(size == 1 || lastIndex == startPos) return; - if(firstIndex == startPos) { - firstIndex = (int)links[startPos]; - links[lastIndex] |= 0xFFFFFFFF00000000L; - } - else { - long link = links[startPos]; - int prev = (int)(link >>> 32); - int next = (int)link; - links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L); - } - links[lastIndex] ^= ((links[lastIndex] ^ (startPos & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - links[startPos] = ((lastIndex & 0xFFFFFFFFL) << 32) | 0xFFFFFFFFL; - lastIndex = startPos; - } - - @Override - protected void onNodeAdded(int pos) { - if(size == 0) { - firstIndex = lastIndex = pos; - links[pos] = -1L; - } - else { - links[lastIndex] ^= ((links[lastIndex] ^ (pos & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - links[pos] = ((lastIndex & 0xFFFFFFFFL) << 32) | 0xFFFFFFFFL; - lastIndex = pos; - } - } - - @Override - protected void onNodeRemoved(int pos) { - if(size == 0) firstIndex = lastIndex = -1; - else if(firstIndex == pos) { - firstIndex = (int)links[pos]; - if(0 <= firstIndex) links[firstIndex] |= 0xFFFFFFFF00000000L; - } - else if(lastIndex == pos) { - lastIndex = (int)(links[pos] >>> 32); - if(0 <= lastIndex) links[lastIndex] |= 0xFFFFFFFFL; - } - else { - long link = links[pos]; - int prev = (int)(link >>> 32); - int next = (int)link; - links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L); - } - } - - @Override - protected void onNodeMoved(int from, int to) { - if(size == 1) { - firstIndex = lastIndex = to; - links[to] = -1L; - } - else if(firstIndex == from) { - firstIndex = to; - links[(int)links[from]] ^= ((links[(int)links[from]] ^ ((to & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); - links[to] = links[from]; - } - else if(lastIndex == from) { - lastIndex = to; - links[(int)(links[from] >>> 32)] ^= ((links[(int)(links[from] >>> 32)] ^ (to & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - links[to] = links[from]; - } - else { - long link = links[from]; - int prev = (int)(link >>> 32); - int next = (int)link; - links[prev] ^= ((links[prev] ^ (to & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - links[next] ^= ((links[next] ^ ((to & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); - links[to] = link; - } - } - - @Override - protected void rehash(int newSize) { - int newMask = newSize - 1; - KEY_TYPE[] newKeys = NEW_KEY_ARRAY(newSize + 1); - VALUE_TYPE[] newValues = NEW_VALUE_ARRAY(newSize + 1); - long[] newLinks = new long[newSize + 1]; - int i = firstIndex, prev = -1, newPrev = -1, pos; - firstIndex = -1; - for(int j = size; j-- != 0;) { - if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) pos = newSize; - else { - pos = HashUtil.mix(strategy.hashCode(keys[i])) & newMask; - while(!strategy.equals(newKeys[pos], EMPTY_KEY_VALUE)) pos = ++pos & newMask; - } - newKeys[pos] = keys[i]; - newValues[pos] = values[i]; - if(prev != -1) { - newLinks[newPrev] ^= ((newLinks[newPrev] ^ (pos & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - newLinks[pos] ^= ((newLinks[pos] ^ ((newPrev & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); - newPrev = pos; - } - else { - newPrev = firstIndex = pos; - newLinks[pos] = -1L; - } - i = (int)links[prev = i]; - } - links = newLinks; - lastIndex = newPrev; - if(newPrev != -1) newLinks[newPrev] |= 0xFFFFFFFFL; - nullIndex = newSize; - mask = newMask; - maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1); - keys = newKeys; - values = newValues; - } - - private class MapEntrySet extends AbstractObjectSet implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE { - @Override - public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } - @Override - public boolean addAndMoveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } - - @Override - public boolean moveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { - return LINKED_CUSTOM_HASH_MAP.this.moveToFirst(o.ENTRY_KEY()); - } - - @Override - public boolean moveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { - return LINKED_CUSTOM_HASH_MAP.this.moveToLast(o.ENTRY_KEY()); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE first() { - return new BasicEntryKV_BRACES(FIRST_ENTRY_KEY(), FIRST_ENTRY_VALUE()); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE last() { - return new BasicEntryKV_BRACES(LAST_ENTRY_KEY(), LAST_ENTRY_VALUE()); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirst() { - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(FIRST_ENTRY_KEY(), FIRST_ENTRY_VALUE()); - POLL_FIRST_ENTRY_KEY(); - return entry; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLast() { - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(LAST_ENTRY_KEY(), LAST_ENTRY_VALUE()); - POLL_LAST_ENTRY_KEY(); - return entry; - } - - @Override - public ObjectBidirectionalIterator iterator() { - return new EntryIterator(); - } - - @Override - public ObjectBidirectionalIterator iterator(MAP.Entry KEY_VALUE_GENERIC_TYPE fromElement) { - return new EntryIterator(fromElement.ENTRY_KEY()); - } - - @Override - public ObjectBidirectionalIterator fastIterator() { - return new FastEntryIterator(); - } - - @Override - public ObjectBidirectionalIterator fastIterator(KEY_TYPE fromElement) { - return new FastEntryIterator(fromElement); - } - - @Override - public MapEntrySet copy() { throw new UnsupportedOperationException(); } - - @Override - public void forEach(Consumer action) { - int index = firstIndex; - while(index != -1) { - action.accept(new BasicEntryKV_BRACES(keys[index], values[index])); - index = (int)links[index]; - } - } - - @Override - public void fastForEach(Consumer action) { - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - int index = firstIndex; - while(index != -1) { - entry.set(keys[index], values[index]); - action.accept(entry); - index = (int)links[index]; - } - } - - @Override - public void forEachIndexed(IntObjectConsumer action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - int count = 0; - int index = firstIndex; - while(index != -1) { - action.accept(count++, new BasicEntryKV_BRACES(keys[index], values[index])); - index = (int)links[index]; - } - } - - @Override - public void forEach(E input, ObjectObjectConsumer action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - int index = firstIndex; - while(index != -1) { - action.accept(input, new BasicEntryKV_BRACES(keys[index], values[index])); - index = (int)links[index]; - } - } - - @Override - public boolean matchesAny(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return false; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - int index = firstIndex; - while(index != -1) { - entry.set(keys[index], values[index]); - if(filter.test(entry)) return true; - index = (int)links[index]; - } - return false; - } - - @Override - public boolean matchesNone(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - int index = firstIndex; - while(index != -1) { - entry.set(keys[index], values[index]); - if(filter.test(entry)) return false; - index = (int)links[index]; - } - return true; - } - - @Override - public boolean matchesAll(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - int index = firstIndex; - while(index != -1) { - entry.set(keys[index], values[index]); - if(!filter.test(entry)) return false; - index = (int)links[index]; - } - return true; - } - - @Override - public E reduce(E identity, BiFunction operator) { - Objects.requireNonNull(operator); - E state = identity; - int index = firstIndex; - while(index != -1) { - state = operator.apply(state, new BasicEntryKV_BRACES(keys[index], values[index])); - index = (int)links[index]; - } - return state; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE reduce(ObjectObjectUnaryOperator operator) { - Objects.requireNonNull(operator); - MAP.Entry KEY_VALUE_GENERIC_TYPE state = null; - boolean empty = true; - int index = firstIndex; - while(index != -1) { - if(empty) { - empty = false; - state = new BasicEntryKV_BRACES(keys[index], values[index]); - index = (int)links[index]; - continue; - } - state = operator.apply(state, new BasicEntryKV_BRACES(keys[index], values[index])); - index = (int)links[index]; - } - return state; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE findFirst(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return null; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - int index = firstIndex; - while(index != -1) { - entry.set(keys[index], values[index]); - if(filter.test(entry)) return entry; - index = (int)links[index]; - } - return null; - } - - @Override - public int count(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return 0; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - int result = 0; - int index = firstIndex; - while(index != -1) { - entry.set(keys[index], values[index]); - if(filter.test(entry)) result++; - index = (int)links[index]; - } - return result; - } - - @Override - @Deprecated - public boolean contains(Object o) { - if(o instanceof Map.Entry) { - if(o instanceof MAP.Entry) { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; - int index = LINKED_CUSTOM_HASH_MAP.this.findIndex(entry.ENTRY_KEY()); - if(index >= 0) return VALUE_EQUALS(entry.ENTRY_VALUE(), LINKED_CUSTOM_HASH_MAP.this.values[index]); - } - else { - Map.Entry entry = (Map.Entry)o; -#if !TYPE_OBJECT - if(!(entry.getKey() instanceof CLASS_TYPE)) return false; -#endif - int index = LINKED_CUSTOM_HASH_MAP.this.findIndex((CLASS_TYPE)entry.getKey()); - if(index >= 0) return Objects.equals(entry.getValue(), VALUE_TO_OBJ(LINKED_CUSTOM_HASH_MAP.this.values[index])); - } - } - return false; - } - - @Override - @Deprecated - public boolean remove(Object o) { - if(o instanceof Map.Entry) { - if(o instanceof MAP.Entry) { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; - return LINKED_CUSTOM_HASH_MAP.this.remove(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); - } - Map.Entry entry = (Map.Entry)o; - return LINKED_CUSTOM_HASH_MAP.this.remove(entry.getKey(), entry.getValue()); - } - return false; - } - - @Override - public int size() { - return LINKED_CUSTOM_HASH_MAP.this.size(); - } - - @Override - public void clear() { - LINKED_CUSTOM_HASH_MAP.this.clear(); - } - } - - private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE { -#if TYPE_OBJECT - @Override - @Deprecated - public boolean contains(Object e) { - return containsKey(e); - } - - @Override - public boolean remove(Object o) { - int oldSize = size; - LINKED_CUSTOM_HASH_MAP.this.remove(o); - return size != oldSize; - } - -#else - @Override - public boolean contains(KEY_TYPE e) { - return containsKey(e); - } - - @Override - public boolean remove(KEY_TYPE o) { - int oldSize = size; - LINKED_CUSTOM_HASH_MAP.this.remove(o); - return size != oldSize; - } - -#endif - @Override - public boolean add(KEY_TYPE o) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); } - - @Override - public boolean addAndMoveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); } - - @Override - public boolean moveToFirst(KEY_TYPE o) { - return LINKED_CUSTOM_HASH_MAP.this.moveToFirst(o); - } - - @Override - public boolean moveToLast(KEY_TYPE o) { - return LINKED_CUSTOM_HASH_MAP.this.moveToLast(o); - } - - @Override - public LIST_ITERATOR KEY_GENERIC_TYPE iterator() { - return new KeyIterator(); - } - - @Override - public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { - return new KeyIterator(fromElement); - } - - @Override - public KeySet copy() { throw new UnsupportedOperationException(); } - - @Override - public int size() { - return LINKED_CUSTOM_HASH_MAP.this.size(); - } - - @Override - public void clear() { - LINKED_CUSTOM_HASH_MAP.this.clear(); - } - - @Override - public KEY_TYPE FIRST_KEY() { - return FIRST_ENTRY_KEY(); - } - - @Override - public KEY_TYPE POLL_FIRST_KEY() { - return POLL_FIRST_ENTRY_KEY(); - } - - @Override - public KEY_TYPE LAST_KEY() { - return LAST_ENTRY_KEY(); - } - - @Override - public KEY_TYPE POLL_LAST_KEY() { - return POLL_LAST_ENTRY_KEY(); - } - - @Override - public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { - int index = firstIndex; - while(index != -1){ - action.accept(keys[index]); - index = (int)links[index]; - } - } - - @Override - public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - int count = 0; - int index = firstIndex; - while(index != -1){ - action.accept(count++, keys[index]); - index = (int)links[index]; - } - } - - @Override - public void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - int index = firstIndex; - while(index != -1){ - action.accept(input, keys[index]); - index = (int)links[index]; - } - } - - @Override - public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return false; - int index = firstIndex; - while(index != -1){ - if(filter.test(keys[index])) return true; - index = (int)links[index]; - } - return false; - } - - @Override - public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - int index = firstIndex; - while(index != -1){ - if(filter.test(keys[index])) return false; - index = (int)links[index]; - } - return true; - } - - @Override - public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - int index = firstIndex; - while(index != -1){ - if(!filter.test(keys[index])) return false; - index = (int)links[index]; - } - return true; - } - -#if !TYPE_OBJECT - @Override - public KEY_TYPE reduce(KEY_TYPE identity, SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - KEY_TYPE state = identity; - int index = firstIndex; - while(index != -1) { - state = operator.APPLY_KEY_VALUE(state, keys[index]); - index = (int)links[index]; - } - return state; - } - -#else - @Override - public KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) { - Objects.requireNonNull(operator); - KEY_SPECIAL_TYPE state = identity; - int index = firstIndex; - while(index != -1) { - state = operator.apply(state, keys[index]); - index = (int)links[index]; - } - return state; - } - -#endif - @Override - public KEY_TYPE reduce(SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - KEY_TYPE state = EMPTY_KEY_VALUE; - boolean empty = true; - int index = firstIndex; - while(index != -1) { - if(empty) { - empty = false; - state = keys[index]; - index = (int)links[index]; - continue; - } - state = operator.APPLY_KEY_VALUE(state, keys[index]); - index = (int)links[index]; - } - return state; - } - - @Override - public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return EMPTY_KEY_VALUE; - int index = firstIndex; - while(index != -1){ - if(filter.test(keys[index])) return keys[index]; - index = (int)links[index]; - } - return EMPTY_KEY_VALUE; - } - - @Override - public int count(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return 0; - int result = 0; - int index = firstIndex; - while(index != -1){ - if(filter.test(keys[index])) result++; - index = (int)links[index]; - } - return result; - } - } - - private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { -#if VALUE_OBJECT - @Override - @Deprecated - public boolean contains(Object e) { - return containsValue(e); - } - -#else - @Override - public boolean contains(VALUE_TYPE e) { - return containsValue(e); - } - -#endif - @Override - public boolean add(VALUE_TYPE o) { - throw new UnsupportedOperationException(); - } - - @Override - public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() { - return new ValueIterator(); - } - - @Override - public int size() { - return LINKED_CUSTOM_HASH_MAP.this.size(); - } - - @Override - public void clear() { - LINKED_CUSTOM_HASH_MAP.this.clear(); - } - - @Override - public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) { - int index = firstIndex; - while(index != -1){ - action.accept(values[index]); - index = (int)links[index]; - } - } - - @Override - public void forEachIndexed(VALUE_BI_FROM_INT_CONSUMER VALUE_GENERIC_TYPE action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - int count = 0; - int index = firstIndex; - while(index != -1){ - action.accept(count++, values[index]); - index = (int)links[index]; - } - } - - @Override - public void forEach(E input, VALUE_BI_FROM_OBJECT_CONSUMER VSV_GENERIC_TYPE action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - int index = firstIndex; - while(index != -1){ - action.accept(input, values[index]); - index = (int)links[index]; - } - } - - @Override - public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return false; - int index = firstIndex; - while(index != -1){ - if(filter.test(values[index])) return true; - index = (int)links[index]; - } - return false; - } - - @Override - public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - int index = firstIndex; - while(index != -1){ - if(filter.test(values[index])) return false; - index = (int)links[index]; - } - return true; - } - - @Override - public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - int index = firstIndex; - while(index != -1){ - if(!filter.test(values[index])) return false; - index = (int)links[index]; - } - return true; - } - -#if !VALUE_OBJECT - @Override - public VALUE_TYPE reduce(VALUE_TYPE identity, VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - VALUE_TYPE state = identity; - int index = firstIndex; - while(index != -1) { - state = operator.APPLY_VALUE(state, values[index]); - index = (int)links[index]; - } - return state; - } - -#else - @Override - public VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction operator) { - Objects.requireNonNull(operator); - VALUE_SPECIAL_TYPE state = identity; - int index = firstIndex; - while(index != -1) { - state = operator.apply(state, values[index]); - index = (int)links[index]; - } - return state; - } - -#endif - @Override - public VALUE_TYPE reduce(VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - VALUE_TYPE state = EMPTY_VALUE; - boolean empty = true; - int index = firstIndex; - while(index != -1) { - if(empty) { - empty = false; - state = values[index]; - index = (int)links[index]; - continue; - } - state = operator.APPLY_VALUE(state, values[index]); - index = (int)links[index]; - } - return state; - } - - @Override - public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return EMPTY_VALUE; - int index = firstIndex; - while(index != -1){ - if(filter.test(values[index])) return values[index]; - index = (int)links[index]; - } - return EMPTY_VALUE; - } - - @Override - public int count(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return 0; - int result = 0; - int index = firstIndex; - while(index != -1){ - if(filter.test(values[index])) result++; - index = (int)links[index]; - } - return result; - } - } - - private class FastEntryIterator extends MapIterator implements ObjectListIterator { - MapEntry entry = new MapEntry(); - - public FastEntryIterator() {} - public FastEntryIterator(KEY_TYPE from) { - super(from); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { - entry.index = nextEntry(); - return entry; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { - entry.index = previousEntry(); - return entry; - } - - @Override - public void set(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } - - @Override - public void add(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } - } - - private class EntryIterator extends MapIterator implements ObjectListIterator { - MapEntry entry; - - public EntryIterator() {} - public EntryIterator(KEY_TYPE from) { - super(from); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { - return entry = new MapEntry(nextEntry()); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { - return entry = new MapEntry(previousEntry()); - } - - @Override - public void remove() { - super.remove(); - entry.index = -1; - } - - @Override - public void set(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } - - @Override - public void add(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } - } - - private class KeyIterator extends MapIterator implements LIST_ITERATOR KEY_GENERIC_TYPE { - - public KeyIterator() {} - public KeyIterator(KEY_TYPE from) { - super(from); - } - - @Override - public KEY_TYPE PREVIOUS() { - return keys[previousEntry()]; - } - - @Override - public KEY_TYPE NEXT() { - return keys[nextEntry()]; - } - - @Override - public void set(KEY_TYPE e) { throw new UnsupportedOperationException(); } - @Override - public void add(KEY_TYPE e) { throw new UnsupportedOperationException(); } - } - - private class ValueIterator extends MapIterator implements VALUE_LIST_ITERATOR VALUE_GENERIC_TYPE { - public ValueIterator() {} - - @Override - public VALUE_TYPE VALUE_PREVIOUS() { - return values[previousEntry()]; - } - - @Override - public VALUE_TYPE VALUE_NEXT() { - return values[nextEntry()]; - } - - @Override - public void set(VALUE_TYPE e) { throw new UnsupportedOperationException(); } - - @Override - public void add(VALUE_TYPE e) { throw new UnsupportedOperationException(); } - - } - - private class MapIterator { - int previous = -1; - int next = -1; - int current = -1; - int index = 0; - - MapIterator() { - next = firstIndex; - } - - MapIterator(KEY_TYPE from) { - if(strategy.equals(from, EMPTY_KEY_VALUE)) { - if(containsNull) { - next = (int) links[nullIndex]; - previous = nullIndex; - } - else throw new NoSuchElementException("The null element is not in the set"); - } - else if(keys[lastIndex] == from) { - previous = lastIndex; - index = size; - } - else { - int pos = HashUtil.mix(strategy.hashCode(from)) & mask; - while(!strategy.equals(keys[pos], EMPTY_KEY_VALUE)) { - if(strategy.equals(keys[pos], from)) { - next = (int)links[pos]; - previous = pos; - break; - } - pos = ++pos & mask; - } - if(previous == -1 && next == -1) - throw new NoSuchElementException("The element was not found"); - } - } - - public boolean hasNext() { - return next != -1; - } - - public boolean hasPrevious() { - return previous != -1; - } - - public int nextIndex() { - ensureIndexKnown(); - return index; - } - - public int previousIndex() { - ensureIndexKnown(); - return index - 1; - } - - public void remove() { - if(current == -1) throw new IllegalStateException(); - ensureIndexKnown(); - if(current == previous) { - index--; - previous = (int)(links[current] >>> 32); - } - else next = (int)links[current]; - size--; - if(previous == -1) firstIndex = next; - else links[previous] ^= ((links[previous] ^ (next & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - - if (next == -1) lastIndex = previous; - else links[next] ^= ((links[next] ^ ((previous & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); - if(current == nullIndex) { - current = -1; - containsNull = false; - keys[nullIndex] = EMPTY_KEY_VALUE; - values[nullIndex] = EMPTY_VALUE; - } - else { - int slot, last, startPos = current; - current = -1; - KEY_TYPE current; - while(true) { - startPos = ((last = startPos) + 1) & mask; - while(true){ - if(strategy.equals((current = keys[startPos]), EMPTY_KEY_VALUE)) { - keys[last] = EMPTY_KEY_VALUE; - values[last] = EMPTY_VALUE; - return; - } - slot = HashUtil.mix(strategy.hashCode(current)) & mask; - if(last <= startPos ? (last >= slot || slot > startPos) : (last >= slot && slot > startPos)) break; - startPos = ++startPos & mask; - } - keys[last] = current; - values[last] = values[startPos]; - if(next == startPos) next = last; - if(previous == startPos) previous = last; - onNodeMoved(startPos, last); - } - } - } - - public int previousEntry() { - if(!hasPrevious()) throw new NoSuchElementException(); - current = previous; - previous = (int)(links[current] >> 32); - next = current; - if(index >= 0) index--; - return current; - } - - public int nextEntry() { - if(!hasNext()) throw new NoSuchElementException(); - current = next; - next = (int)(links[current]); - previous = current; - if(index >= 0) index++; - return current; - } - - private void ensureIndexKnown() { - if(index == -1) { - if(previous == -1) { - index = 0; - } - else if(next == -1) { - index = size; - } - else { - index = 1; - for(int pos = firstIndex;pos != previous;pos = (int)links[pos], index++); - } - } - } - - } +package speiger.src.collections.PACKAGE.maps.impl.customHash; + +import java.util.Arrays; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Objects; +import java.util.function.Consumer; +import java.util.function.BiFunction; +import java.util.function.Predicate; +#if !TYPE_OBJECT && JDK_TYPE +import java.util.function.PREDICATE; +#endif +#if !SAME_TYPE && JDK_VALUE && !VALUE_OBJECT +import java.util.function.VALUE_PREDICATE; +#endif + +import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.functions.CONSUMER; +import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; +#endif +import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER; +#if !TYPE_OBJECT && !VALUE_OBJECT +import speiger.src.collections.ints.functions.consumer.IntObjectConsumer; +#endif +#if !SAME_TYPE && !TYPE_INT +import speiger.src.collections.ints.functions.consumer.VALUE_BI_FROM_INT_CONSUMER; +#endif +#if !TYPE_OBJECT && !JDK_TYPE +import speiger.src.collections.PACKAGE.functions.function.PREDICATE; +#endif +#if !TYPE_INT || !SAME_TYPE +import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; +#endif +import speiger.src.collections.PACKAGE.functions.function.SINGLE_UNARY_OPERATOR; +import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP; +import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET; +import speiger.src.collections.PACKAGE.sets.ORDERED_SET; +import speiger.src.collections.PACKAGE.utils.STRATEGY; +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; +#if !SAME_TYPE +import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR; +#endif +#if !VALUE_OBJECT && !SAME_TYPE +import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER; +import speiger.src.collections.VALUE_PACKAGE.lists.VALUE_LIST_ITERATOR; +#endif +#if !TYPE_OBJECT && !VALUE_OBJECT || !VALUE_OBJECT +import speiger.src.collections.objects.functions.consumer.ObjectObjectConsumer; +#endif +#if !SAME_TYPE +#if !TYPE_OBJECT +import speiger.src.collections.objects.functions.consumer.VALUE_BI_FROM_OBJECT_CONSUMER; + +#endif +#if !JDK_VALUE +import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE; +#endif +#endif +#if !TYPE_OBJECT +#if !VALUE_OBJECT +import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator; + +#endif +import speiger.src.collections.objects.collections.ObjectBidirectionalIterator; +import speiger.src.collections.objects.lists.ObjectListIterator; +import speiger.src.collections.objects.sets.AbstractObjectSet; +import speiger.src.collections.objects.sets.ObjectOrderedSet; +#endif +import speiger.src.collections.utils.HashUtil; + +/** + * A Type Specific LinkedHashMap that allows for custom HashControl. That uses arrays to create links between nodes. + * For cases where Objects/primitive do not allow hashcoding this can be really useful and provide a lot of control. + * This implementation of SortedMap does not support SubMaps of any kind. It implements the interface due to sortability and first/last access + * @Type(T) + * @ValueType(V) + */ +public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE implements ORDERED_MAP KEY_VALUE_GENERIC_TYPE +{ + /** The Backing array for links between nodes. Left 32 Bits => Previous Entry, Right 32 Bits => Next Entry */ + protected transient long[] links; + /** The First Index in the Map */ + protected int firstIndex = -1; + /** The Last Index in the Map */ + protected int lastIndex = -1; + + /** + * Default Constructor + * @param strategy the strategy that allows hash control. + * @throws NullPointerException if Strategy is null + */ + public LINKED_CUSTOM_HASH_MAP(STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { + this(HashUtil.DEFAULT_MIN_CAPACITY, HashUtil.DEFAULT_LOAD_FACTOR, strategy); + } + + /** + * Constructor that defines the minimum capacity + * @param minCapacity the minimum capacity the HashMap is allowed to be. + * @param strategy the strategy that allows hash control. + * @throws NullPointerException if Strategy is null + * @throws IllegalStateException if the minimum capacity is negative + */ + public LINKED_CUSTOM_HASH_MAP(int minCapacity, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { + this(minCapacity, HashUtil.DEFAULT_LOAD_FACTOR, strategy); + } + + /** + * Constructor that defines the minimum capacity and load factor + * @param minCapacity the minimum capacity the HashMap is allowed to be. + * @param loadFactor the percentage of how full the backing array can be before they resize + * @param strategy the strategy that allows hash control. + * @throws NullPointerException if Strategy is null + * @throws IllegalStateException if the minimum capacity is negative + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + */ + public LINKED_CUSTOM_HASH_MAP(int minCapacity, float loadFactor, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { + super(minCapacity, loadFactor, strategy); + links = new long[nullIndex + 1]; + } + +#if !TYPE_OBJECT || !VALUE_OBJECT + /** + * Helper constructor that allow to create a map from boxed values (it will unbox them) + * @param keys the keys that should be put into the map + * @param values the values that should be put into the map. + * @param strategy the strategy that allows hash control. + * @throws NullPointerException if Strategy is null + * @throws IllegalStateException if the keys and values do not match in lenght + */ + public LINKED_CUSTOM_HASH_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { + this(keys, values, HashUtil.DEFAULT_LOAD_FACTOR, strategy); + } + + /** + * Helper constructor that allow to create a map from boxed values (it will unbox them) + * @param keys the keys that should be put into the map + * @param values the values that should be put into the map. + * @param loadFactor the percentage of how full the backing array can be before they resize + * @param strategy the strategy that allows hash control. + * @throws NullPointerException if Strategy is null + * @throws IllegalStateException if the keys and values do not match in lenght + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + */ + public LINKED_CUSTOM_HASH_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, float loadFactor, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { + this(keys.length, loadFactor, strategy); + if(keys.length != values.length) throw new IllegalStateException("Input Arrays are not equal size"); + for(int i = 0,m=keys.length;i map, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { + this(map, HashUtil.DEFAULT_LOAD_FACTOR, strategy); + } + + /** + * A Helper constructor that allows to create a Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + * @param loadFactor the percentage of how full the backing array can be before they resize + * @param strategy the strategy that allows hash control. + * @throws NullPointerException if Strategy is null + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + */ + public LINKED_CUSTOM_HASH_MAP(Map map, float loadFactor, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { + this(map.size(), loadFactor, strategy); + putAll(map); + } + + /** + * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + * @param strategy the strategy that allows hash control. + * @throws NullPointerException if Strategy is null + */ + public LINKED_CUSTOM_HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { + this(map, HashUtil.DEFAULT_LOAD_FACTOR, strategy); + } + + /** + * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + * @param loadFactor the percentage of how full the backing array can be before they resize + * @param strategy the strategy that allows hash control. + * @throws NullPointerException if Strategy is null + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + */ + public LINKED_CUSTOM_HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map, float loadFactor, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { + this(map.size(), loadFactor, strategy); + putAll(map); + } + + @Override + public VALUE_TYPE putAndMoveToFirst(KEY_TYPE key, VALUE_TYPE value) { + if(strategy.equals(key, EMPTY_KEY_VALUE)) { + if(containsNull) { + VALUE_TYPE lastValue = values[nullIndex]; + values[nullIndex] = value; + moveToFirstIndex(nullIndex); + return lastValue; + } + values[nullIndex] = value; + containsNull = true; + onNodeAdded(nullIndex); + moveToFirstIndex(nullIndex); + } + else { + int pos = HashUtil.mix(strategy.hashCode(key)) & mask; + while(!strategy.equals(keys[pos], EMPTY_KEY_VALUE)) { + if(strategy.equals(keys[pos], key)) { + VALUE_TYPE lastValue = values[pos]; + values[pos] = value; + moveToFirstIndex(pos); + return lastValue; + } + pos = ++pos & mask; + } + keys[pos] = key; + values[pos] = value; + onNodeAdded(pos); + moveToFirstIndex(pos); + } + if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor)); + return getDefaultReturnValue(); + } + + @Override + public VALUE_TYPE putAndMoveToLast(KEY_TYPE key, VALUE_TYPE value) { + if(strategy.equals(key, EMPTY_KEY_VALUE)) { + if(containsNull) { + VALUE_TYPE lastValue = values[nullIndex]; + values[nullIndex] = value; + moveToLastIndex(nullIndex); + return lastValue; + } + values[nullIndex] = value; + containsNull = true; + onNodeAdded(nullIndex); + moveToLastIndex(nullIndex); + } + else { + int pos = HashUtil.mix(strategy.hashCode(key)) & mask; + while(!strategy.equals(keys[pos], EMPTY_KEY_VALUE)) { + if(strategy.equals(keys[pos], key)) { + VALUE_TYPE lastValue = values[pos]; + values[pos] = value; + moveToLastIndex(pos); + return lastValue; + } + pos = ++pos & mask; + } + keys[pos] = key; + values[pos] = value; + onNodeAdded(pos); + moveToLastIndex(pos); + } + if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor)); + return getDefaultReturnValue(); + } + + @Override + public boolean moveToFirst(KEY_TYPE key) { + if(isEmpty() || strategy.equals(FIRST_ENTRY_KEY(), key)) return false; + if(strategy.equals(key, EMPTY_KEY_VALUE)) { + if(containsNull) { + moveToFirstIndex(nullIndex); + return true; + } + } + else { + int pos = HashUtil.mix(strategy.hashCode(key)) & mask; + while(!strategy.equals(keys[pos], EMPTY_KEY_VALUE)) { + if(strategy.equals(keys[pos], key)) { + moveToFirstIndex(pos); + return true; + } + pos = ++pos & mask; + } + } + return false; + } + + @Override + public boolean moveToLast(KEY_TYPE key) { + if(isEmpty() || strategy.equals(LAST_ENTRY_KEY(), key)) return false; + if(strategy.equals(key, EMPTY_KEY_VALUE)) { + if(containsNull) { + moveToLastIndex(nullIndex); + return true; + } + } + else { + int pos = HashUtil.mix(strategy.hashCode(key)) & mask; + while(!strategy.equals(keys[pos], EMPTY_KEY_VALUE)) { + if(strategy.equals(keys[pos], key)) { + moveToLastIndex(pos); + return true; + } + pos = ++pos & mask; + } + } + return false; + } + + @Override + public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key) { + int index = findIndex(key); + if(index < 0) return getDefaultReturnValue(); + moveToFirstIndex(index); + return values[index]; + } + + @Override + public VALUE_TYPE getAndMoveToLast(KEY_TYPE key) { + int index = findIndex(key); + if(index < 0) return getDefaultReturnValue(); + moveToLastIndex(index); + return values[index]; + } + + @Override + public LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE copy() { + LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE map = new LINKED_CUSTOM_HASH_MAPKV_BRACES(0, loadFactor, strategy); + map.minCapacity = minCapacity; + map.mask = mask; + map.maxFill = maxFill; + map.nullIndex = nullIndex; + map.containsNull = containsNull; + map.size = size; + map.keys = Arrays.copyOf(keys, keys.length); + map.values = Arrays.copyOf(values, values.length); + map.links = Arrays.copyOf(links, links.length); + map.firstIndex = firstIndex; + map.lastIndex = lastIndex; + return map; + } + + @Override + public KEY_TYPE FIRST_ENTRY_KEY() { + if(size == 0) throw new NoSuchElementException(); + return keys[firstIndex]; + } + + @Override + public KEY_TYPE POLL_FIRST_ENTRY_KEY() { + if(size == 0) throw new NoSuchElementException(); + int pos = firstIndex; + onNodeRemoved(pos); + KEY_TYPE result = keys[pos]; + size--; + if(strategy.equals(result, EMPTY_KEY_VALUE)) { + containsNull = false; + keys[nullIndex] = EMPTY_KEY_VALUE; + values[nullIndex] = EMPTY_VALUE; + } + else shiftKeys(pos); + if(nullIndex > minCapacity && size < maxFill / 4 && nullIndex > HashUtil.DEFAULT_MIN_CAPACITY) rehash(nullIndex / 2); + return result; + } + + @Override + public KEY_TYPE LAST_ENTRY_KEY() { + if(size == 0) throw new NoSuchElementException(); + return keys[lastIndex]; + } + + @Override + public KEY_TYPE POLL_LAST_ENTRY_KEY() { + if(size == 0) throw new NoSuchElementException(); + int pos = lastIndex; + onNodeRemoved(pos); + KEY_TYPE result = keys[pos]; + size--; + if(strategy.equals(result, EMPTY_KEY_VALUE)) { + containsNull = false; + keys[nullIndex] = EMPTY_KEY_VALUE; + values[nullIndex] = EMPTY_VALUE; + } + else shiftKeys(pos); + if(nullIndex > minCapacity && size < maxFill / 4 && nullIndex > HashUtil.DEFAULT_MIN_CAPACITY) rehash(nullIndex / 2); + return result; + } + + @Override + public VALUE_TYPE FIRST_ENTRY_VALUE() { + if(size == 0) throw new NoSuchElementException(); + return values[firstIndex]; + } + + @Override + public VALUE_TYPE LAST_ENTRY_VALUE() { + if(size == 0) throw new NoSuchElementException(); + return values[lastIndex]; + } + + @Override + public ObjectOrderedSet ENTRY_SET() { + if(entrySet == null) entrySet = new MapEntrySet(); + return (ObjectOrderedSet)entrySet; + } + + @Override + public ORDERED_SET KEY_GENERIC_TYPE keySet() { + if(keySet == null) keySet = new KeySet(); + return (ORDERED_SET KEY_GENERIC_TYPE)keySet; + } + + @Override + public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { + if(valuesC == null) valuesC = new Values(); + return valuesC; + } + + @Override + public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { + int index = firstIndex; + while(index != -1){ + action.accept(keys[index], values[index]); + index = (int)links[index]; + } + } + + @Override + public void clear() { + super.clear(); + firstIndex = lastIndex = -1; + } + + @Override + public void clearAndTrim(int size) { + int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor))); + if(request >= nullIndex) { + clear(); + return; + } + nullIndex = request; + mask = request-1; + maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1); + keys = NEW_KEY_ARRAY(request + 1); + values = NEW_VALUE_ARRAY(request + 1); + links = new long[request + 1]; + firstIndex = lastIndex = -1; + this.size = 0; + containsNull = false; + } + + protected void moveToFirstIndex(int startPos) { + if(size == 1 || firstIndex == startPos) return; + if(lastIndex == startPos) { + lastIndex = (int)(links[startPos] >>> 32); + links[lastIndex] |= 0xFFFFFFFFL; + } + else { + long link = links[startPos]; + int prev = (int)(link >>> 32); + int next = (int)link; + links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L); + } + links[firstIndex] ^= ((links[firstIndex] ^ ((startPos & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); + links[startPos] = 0xFFFFFFFF00000000L | (firstIndex & 0xFFFFFFFFL); + firstIndex = startPos; + } + + protected void moveToLastIndex(int startPos) { + if(size == 1 || lastIndex == startPos) return; + if(firstIndex == startPos) { + firstIndex = (int)links[startPos]; + links[lastIndex] |= 0xFFFFFFFF00000000L; + } + else { + long link = links[startPos]; + int prev = (int)(link >>> 32); + int next = (int)link; + links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L); + } + links[lastIndex] ^= ((links[lastIndex] ^ (startPos & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + links[startPos] = ((lastIndex & 0xFFFFFFFFL) << 32) | 0xFFFFFFFFL; + lastIndex = startPos; + } + + @Override + protected void onNodeAdded(int pos) { + if(size == 0) { + firstIndex = lastIndex = pos; + links[pos] = -1L; + } + else { + links[lastIndex] ^= ((links[lastIndex] ^ (pos & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + links[pos] = ((lastIndex & 0xFFFFFFFFL) << 32) | 0xFFFFFFFFL; + lastIndex = pos; + } + } + + @Override + protected void onNodeRemoved(int pos) { + if(size == 0) firstIndex = lastIndex = -1; + else if(firstIndex == pos) { + firstIndex = (int)links[pos]; + if(0 <= firstIndex) links[firstIndex] |= 0xFFFFFFFF00000000L; + } + else if(lastIndex == pos) { + lastIndex = (int)(links[pos] >>> 32); + if(0 <= lastIndex) links[lastIndex] |= 0xFFFFFFFFL; + } + else { + long link = links[pos]; + int prev = (int)(link >>> 32); + int next = (int)link; + links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L); + } + } + + @Override + protected void onNodeMoved(int from, int to) { + if(size == 1) { + firstIndex = lastIndex = to; + links[to] = -1L; + } + else if(firstIndex == from) { + firstIndex = to; + links[(int)links[from]] ^= ((links[(int)links[from]] ^ ((to & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); + links[to] = links[from]; + } + else if(lastIndex == from) { + lastIndex = to; + links[(int)(links[from] >>> 32)] ^= ((links[(int)(links[from] >>> 32)] ^ (to & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + links[to] = links[from]; + } + else { + long link = links[from]; + int prev = (int)(link >>> 32); + int next = (int)link; + links[prev] ^= ((links[prev] ^ (to & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + links[next] ^= ((links[next] ^ ((to & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); + links[to] = link; + } + } + + @Override + protected void rehash(int newSize) { + int newMask = newSize - 1; + KEY_TYPE[] newKeys = NEW_KEY_ARRAY(newSize + 1); + VALUE_TYPE[] newValues = NEW_VALUE_ARRAY(newSize + 1); + long[] newLinks = new long[newSize + 1]; + int i = firstIndex, prev = -1, newPrev = -1, pos; + firstIndex = -1; + for(int j = size; j-- != 0;) { + if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) pos = newSize; + else { + pos = HashUtil.mix(strategy.hashCode(keys[i])) & newMask; + while(!strategy.equals(newKeys[pos], EMPTY_KEY_VALUE)) pos = ++pos & newMask; + } + newKeys[pos] = keys[i]; + newValues[pos] = values[i]; + if(prev != -1) { + newLinks[newPrev] ^= ((newLinks[newPrev] ^ (pos & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + newLinks[pos] ^= ((newLinks[pos] ^ ((newPrev & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); + newPrev = pos; + } + else { + newPrev = firstIndex = pos; + newLinks[pos] = -1L; + } + i = (int)links[prev = i]; + } + links = newLinks; + lastIndex = newPrev; + if(newPrev != -1) newLinks[newPrev] |= 0xFFFFFFFFL; + nullIndex = newSize; + mask = newMask; + maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1); + keys = newKeys; + values = newValues; + } + + private class MapEntrySet extends AbstractObjectSet implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE { + @Override + public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } + @Override + public boolean addAndMoveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } + + @Override + public boolean moveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { + return LINKED_CUSTOM_HASH_MAP.this.moveToFirst(o.ENTRY_KEY()); + } + + @Override + public boolean moveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { + return LINKED_CUSTOM_HASH_MAP.this.moveToLast(o.ENTRY_KEY()); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE first() { + return new BasicEntryKV_BRACES(FIRST_ENTRY_KEY(), FIRST_ENTRY_VALUE()); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE last() { + return new BasicEntryKV_BRACES(LAST_ENTRY_KEY(), LAST_ENTRY_VALUE()); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirst() { + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(FIRST_ENTRY_KEY(), FIRST_ENTRY_VALUE()); + POLL_FIRST_ENTRY_KEY(); + return entry; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLast() { + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(LAST_ENTRY_KEY(), LAST_ENTRY_VALUE()); + POLL_LAST_ENTRY_KEY(); + return entry; + } + + @Override + public ObjectBidirectionalIterator iterator() { + return new EntryIterator(); + } + + @Override + public ObjectBidirectionalIterator iterator(MAP.Entry KEY_VALUE_GENERIC_TYPE fromElement) { + return new EntryIterator(fromElement.ENTRY_KEY()); + } + + @Override + public ObjectBidirectionalIterator fastIterator() { + return new FastEntryIterator(); + } + + @Override + public ObjectBidirectionalIterator fastIterator(KEY_TYPE fromElement) { + return new FastEntryIterator(fromElement); + } + + @Override + public MapEntrySet copy() { throw new UnsupportedOperationException(); } + + @Override + public void forEach(Consumer action) { + int index = firstIndex; + while(index != -1) { + action.accept(new BasicEntryKV_BRACES(keys[index], values[index])); + index = (int)links[index]; + } + } + + @Override + public void fastForEach(Consumer action) { + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + int index = firstIndex; + while(index != -1) { + entry.set(keys[index], values[index]); + action.accept(entry); + index = (int)links[index]; + } + } + + @Override + public void forEachIndexed(IntObjectConsumer action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + int count = 0; + int index = firstIndex; + while(index != -1) { + action.accept(count++, new BasicEntryKV_BRACES(keys[index], values[index])); + index = (int)links[index]; + } + } + + @Override + public void forEach(E input, ObjectObjectConsumer action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + int index = firstIndex; + while(index != -1) { + action.accept(input, new BasicEntryKV_BRACES(keys[index], values[index])); + index = (int)links[index]; + } + } + + @Override + public boolean matchesAny(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return false; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + int index = firstIndex; + while(index != -1) { + entry.set(keys[index], values[index]); + if(filter.test(entry)) return true; + index = (int)links[index]; + } + return false; + } + + @Override + public boolean matchesNone(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + int index = firstIndex; + while(index != -1) { + entry.set(keys[index], values[index]); + if(filter.test(entry)) return false; + index = (int)links[index]; + } + return true; + } + + @Override + public boolean matchesAll(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + int index = firstIndex; + while(index != -1) { + entry.set(keys[index], values[index]); + if(!filter.test(entry)) return false; + index = (int)links[index]; + } + return true; + } + + @Override + public E reduce(E identity, BiFunction operator) { + Objects.requireNonNull(operator); + E state = identity; + int index = firstIndex; + while(index != -1) { + state = operator.apply(state, new BasicEntryKV_BRACES(keys[index], values[index])); + index = (int)links[index]; + } + return state; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE reduce(ObjectObjectUnaryOperator operator) { + Objects.requireNonNull(operator); + MAP.Entry KEY_VALUE_GENERIC_TYPE state = null; + boolean empty = true; + int index = firstIndex; + while(index != -1) { + if(empty) { + empty = false; + state = new BasicEntryKV_BRACES(keys[index], values[index]); + index = (int)links[index]; + continue; + } + state = operator.apply(state, new BasicEntryKV_BRACES(keys[index], values[index])); + index = (int)links[index]; + } + return state; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE findFirst(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return null; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + int index = firstIndex; + while(index != -1) { + entry.set(keys[index], values[index]); + if(filter.test(entry)) return entry; + index = (int)links[index]; + } + return null; + } + + @Override + public int count(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return 0; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + int result = 0; + int index = firstIndex; + while(index != -1) { + entry.set(keys[index], values[index]); + if(filter.test(entry)) result++; + index = (int)links[index]; + } + return result; + } + + @Override + @Deprecated + public boolean contains(Object o) { + if(o instanceof Map.Entry) { + if(o instanceof MAP.Entry) { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; + int index = LINKED_CUSTOM_HASH_MAP.this.findIndex(entry.ENTRY_KEY()); + if(index >= 0) return VALUE_EQUALS(entry.ENTRY_VALUE(), LINKED_CUSTOM_HASH_MAP.this.values[index]); + } + else { + Map.Entry entry = (Map.Entry)o; +#if !TYPE_OBJECT + if(!(entry.getKey() instanceof CLASS_TYPE)) return false; +#endif + int index = LINKED_CUSTOM_HASH_MAP.this.findIndex((CLASS_TYPE)entry.getKey()); + if(index >= 0) return Objects.equals(entry.getValue(), VALUE_TO_OBJ(LINKED_CUSTOM_HASH_MAP.this.values[index])); + } + } + return false; + } + + @Override + @Deprecated + public boolean remove(Object o) { + if(o instanceof Map.Entry) { + if(o instanceof MAP.Entry) { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; + return LINKED_CUSTOM_HASH_MAP.this.remove(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); + } + Map.Entry entry = (Map.Entry)o; + return LINKED_CUSTOM_HASH_MAP.this.remove(entry.getKey(), entry.getValue()); + } + return false; + } + + @Override + public int size() { + return LINKED_CUSTOM_HASH_MAP.this.size(); + } + + @Override + public void clear() { + LINKED_CUSTOM_HASH_MAP.this.clear(); + } + } + + private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE { +#if TYPE_OBJECT + @Override + @Deprecated + public boolean contains(Object e) { + return containsKey(e); + } + + @Override + public boolean remove(Object o) { + int oldSize = size; + LINKED_CUSTOM_HASH_MAP.this.remove(o); + return size != oldSize; + } + +#else + @Override + public boolean contains(KEY_TYPE e) { + return containsKey(e); + } + + @Override + public boolean remove(KEY_TYPE o) { + int oldSize = size; + LINKED_CUSTOM_HASH_MAP.this.remove(o); + return size != oldSize; + } + +#endif + @Override + public boolean add(KEY_TYPE o) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); } + + @Override + public boolean addAndMoveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); } + + @Override + public boolean moveToFirst(KEY_TYPE o) { + return LINKED_CUSTOM_HASH_MAP.this.moveToFirst(o); + } + + @Override + public boolean moveToLast(KEY_TYPE o) { + return LINKED_CUSTOM_HASH_MAP.this.moveToLast(o); + } + + @Override + public LIST_ITERATOR KEY_GENERIC_TYPE iterator() { + return new KeyIterator(); + } + + @Override + public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { + return new KeyIterator(fromElement); + } + + @Override + public KeySet copy() { throw new UnsupportedOperationException(); } + + @Override + public int size() { + return LINKED_CUSTOM_HASH_MAP.this.size(); + } + + @Override + public void clear() { + LINKED_CUSTOM_HASH_MAP.this.clear(); + } + + @Override + public KEY_TYPE FIRST_KEY() { + return FIRST_ENTRY_KEY(); + } + + @Override + public KEY_TYPE POLL_FIRST_KEY() { + return POLL_FIRST_ENTRY_KEY(); + } + + @Override + public KEY_TYPE LAST_KEY() { + return LAST_ENTRY_KEY(); + } + + @Override + public KEY_TYPE POLL_LAST_KEY() { + return POLL_LAST_ENTRY_KEY(); + } + + @Override + public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { + int index = firstIndex; + while(index != -1){ + action.accept(keys[index]); + index = (int)links[index]; + } + } + + @Override + public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + int count = 0; + int index = firstIndex; + while(index != -1){ + action.accept(count++, keys[index]); + index = (int)links[index]; + } + } + + @Override + public void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + int index = firstIndex; + while(index != -1){ + action.accept(input, keys[index]); + index = (int)links[index]; + } + } + + @Override + public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return false; + int index = firstIndex; + while(index != -1){ + if(filter.test(keys[index])) return true; + index = (int)links[index]; + } + return false; + } + + @Override + public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + int index = firstIndex; + while(index != -1){ + if(filter.test(keys[index])) return false; + index = (int)links[index]; + } + return true; + } + + @Override + public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + int index = firstIndex; + while(index != -1){ + if(!filter.test(keys[index])) return false; + index = (int)links[index]; + } + return true; + } + +#if !TYPE_OBJECT + @Override + public KEY_TYPE reduce(KEY_TYPE identity, SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + KEY_TYPE state = identity; + int index = firstIndex; + while(index != -1) { + state = operator.APPLY_KEY_VALUE(state, keys[index]); + index = (int)links[index]; + } + return state; + } + +#else + @Override + public KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) { + Objects.requireNonNull(operator); + KEY_SPECIAL_TYPE state = identity; + int index = firstIndex; + while(index != -1) { + state = operator.apply(state, keys[index]); + index = (int)links[index]; + } + return state; + } + +#endif + @Override + public KEY_TYPE reduce(SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + KEY_TYPE state = EMPTY_KEY_VALUE; + boolean empty = true; + int index = firstIndex; + while(index != -1) { + if(empty) { + empty = false; + state = keys[index]; + index = (int)links[index]; + continue; + } + state = operator.APPLY_KEY_VALUE(state, keys[index]); + index = (int)links[index]; + } + return state; + } + + @Override + public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return EMPTY_KEY_VALUE; + int index = firstIndex; + while(index != -1){ + if(filter.test(keys[index])) return keys[index]; + index = (int)links[index]; + } + return EMPTY_KEY_VALUE; + } + + @Override + public int count(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return 0; + int result = 0; + int index = firstIndex; + while(index != -1){ + if(filter.test(keys[index])) result++; + index = (int)links[index]; + } + return result; + } + } + + private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { +#if VALUE_OBJECT + @Override + @Deprecated + public boolean contains(Object e) { + return containsValue(e); + } + +#else + @Override + public boolean contains(VALUE_TYPE e) { + return containsValue(e); + } + +#endif + @Override + public boolean add(VALUE_TYPE o) { + throw new UnsupportedOperationException(); + } + + @Override + public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() { + return new ValueIterator(); + } + + @Override + public int size() { + return LINKED_CUSTOM_HASH_MAP.this.size(); + } + + @Override + public void clear() { + LINKED_CUSTOM_HASH_MAP.this.clear(); + } + + @Override + public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) { + int index = firstIndex; + while(index != -1){ + action.accept(values[index]); + index = (int)links[index]; + } + } + + @Override + public void forEachIndexed(VALUE_BI_FROM_INT_CONSUMER VALUE_GENERIC_TYPE action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + int count = 0; + int index = firstIndex; + while(index != -1){ + action.accept(count++, values[index]); + index = (int)links[index]; + } + } + + @Override + public void forEach(E input, VALUE_BI_FROM_OBJECT_CONSUMER VSV_GENERIC_TYPE action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + int index = firstIndex; + while(index != -1){ + action.accept(input, values[index]); + index = (int)links[index]; + } + } + + @Override + public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return false; + int index = firstIndex; + while(index != -1){ + if(filter.test(values[index])) return true; + index = (int)links[index]; + } + return false; + } + + @Override + public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + int index = firstIndex; + while(index != -1){ + if(filter.test(values[index])) return false; + index = (int)links[index]; + } + return true; + } + + @Override + public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + int index = firstIndex; + while(index != -1){ + if(!filter.test(values[index])) return false; + index = (int)links[index]; + } + return true; + } + +#if !VALUE_OBJECT + @Override + public VALUE_TYPE reduce(VALUE_TYPE identity, VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + VALUE_TYPE state = identity; + int index = firstIndex; + while(index != -1) { + state = operator.APPLY_VALUE(state, values[index]); + index = (int)links[index]; + } + return state; + } + +#else + @Override + public VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction operator) { + Objects.requireNonNull(operator); + VALUE_SPECIAL_TYPE state = identity; + int index = firstIndex; + while(index != -1) { + state = operator.apply(state, values[index]); + index = (int)links[index]; + } + return state; + } + +#endif + @Override + public VALUE_TYPE reduce(VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + VALUE_TYPE state = EMPTY_VALUE; + boolean empty = true; + int index = firstIndex; + while(index != -1) { + if(empty) { + empty = false; + state = values[index]; + index = (int)links[index]; + continue; + } + state = operator.APPLY_VALUE(state, values[index]); + index = (int)links[index]; + } + return state; + } + + @Override + public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return EMPTY_VALUE; + int index = firstIndex; + while(index != -1){ + if(filter.test(values[index])) return values[index]; + index = (int)links[index]; + } + return EMPTY_VALUE; + } + + @Override + public int count(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return 0; + int result = 0; + int index = firstIndex; + while(index != -1){ + if(filter.test(values[index])) result++; + index = (int)links[index]; + } + return result; + } + } + + private class FastEntryIterator extends MapIterator implements ObjectListIterator { + MapEntry entry = new MapEntry(); + + public FastEntryIterator() {} + public FastEntryIterator(KEY_TYPE from) { + super(from); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { + entry.index = nextEntry(); + return entry; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { + entry.index = previousEntry(); + return entry; + } + + @Override + public void set(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } + + @Override + public void add(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } + } + + private class EntryIterator extends MapIterator implements ObjectListIterator { + MapEntry entry; + + public EntryIterator() {} + public EntryIterator(KEY_TYPE from) { + super(from); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { + return entry = new MapEntry(nextEntry()); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { + return entry = new MapEntry(previousEntry()); + } + + @Override + public void remove() { + super.remove(); + entry.index = -1; + } + + @Override + public void set(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } + + @Override + public void add(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } + } + + private class KeyIterator extends MapIterator implements LIST_ITERATOR KEY_GENERIC_TYPE { + + public KeyIterator() {} + public KeyIterator(KEY_TYPE from) { + super(from); + } + + @Override + public KEY_TYPE PREVIOUS() { + return keys[previousEntry()]; + } + + @Override + public KEY_TYPE NEXT() { + return keys[nextEntry()]; + } + + @Override + public void set(KEY_TYPE e) { throw new UnsupportedOperationException(); } + @Override + public void add(KEY_TYPE e) { throw new UnsupportedOperationException(); } + } + + private class ValueIterator extends MapIterator implements VALUE_LIST_ITERATOR VALUE_GENERIC_TYPE { + public ValueIterator() {} + + @Override + public VALUE_TYPE VALUE_PREVIOUS() { + return values[previousEntry()]; + } + + @Override + public VALUE_TYPE VALUE_NEXT() { + return values[nextEntry()]; + } + + @Override + public void set(VALUE_TYPE e) { throw new UnsupportedOperationException(); } + + @Override + public void add(VALUE_TYPE e) { throw new UnsupportedOperationException(); } + + } + + private class MapIterator { + int previous = -1; + int next = -1; + int current = -1; + int index = 0; + + MapIterator() { + next = firstIndex; + } + + MapIterator(KEY_TYPE from) { + if(strategy.equals(from, EMPTY_KEY_VALUE)) { + if(containsNull) { + next = (int) links[nullIndex]; + previous = nullIndex; + } + else throw new NoSuchElementException("The null element is not in the set"); + } + else if(keys[lastIndex] == from) { + previous = lastIndex; + index = size; + } + else { + int pos = HashUtil.mix(strategy.hashCode(from)) & mask; + while(!strategy.equals(keys[pos], EMPTY_KEY_VALUE)) { + if(strategy.equals(keys[pos], from)) { + next = (int)links[pos]; + previous = pos; + break; + } + pos = ++pos & mask; + } + if(previous == -1 && next == -1) + throw new NoSuchElementException("The element was not found"); + } + } + + public boolean hasNext() { + return next != -1; + } + + public boolean hasPrevious() { + return previous != -1; + } + + public int nextIndex() { + ensureIndexKnown(); + return index; + } + + public int previousIndex() { + ensureIndexKnown(); + return index - 1; + } + + public void remove() { + if(current == -1) throw new IllegalStateException(); + ensureIndexKnown(); + if(current == previous) { + index--; + previous = (int)(links[current] >>> 32); + } + else next = (int)links[current]; + size--; + if(previous == -1) firstIndex = next; + else links[previous] ^= ((links[previous] ^ (next & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + + if (next == -1) lastIndex = previous; + else links[next] ^= ((links[next] ^ ((previous & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); + if(current == nullIndex) { + current = -1; + containsNull = false; + keys[nullIndex] = EMPTY_KEY_VALUE; + values[nullIndex] = EMPTY_VALUE; + } + else { + int slot, last, startPos = current; + current = -1; + KEY_TYPE current; + while(true) { + startPos = ((last = startPos) + 1) & mask; + while(true){ + if(strategy.equals((current = keys[startPos]), EMPTY_KEY_VALUE)) { + keys[last] = EMPTY_KEY_VALUE; + values[last] = EMPTY_VALUE; + return; + } + slot = HashUtil.mix(strategy.hashCode(current)) & mask; + if(last <= startPos ? (last >= slot || slot > startPos) : (last >= slot && slot > startPos)) break; + startPos = ++startPos & mask; + } + keys[last] = current; + values[last] = values[startPos]; + if(next == startPos) next = last; + if(previous == startPos) previous = last; + onNodeMoved(startPos, last); + } + } + } + + public int previousEntry() { + if(!hasPrevious()) throw new NoSuchElementException(); + current = previous; + previous = (int)(links[current] >> 32); + next = current; + if(index >= 0) index--; + return current; + } + + public int nextEntry() { + if(!hasNext()) throw new NoSuchElementException(); + current = next; + next = (int)(links[current]); + previous = current; + if(index >= 0) index++; + return current; + } + + private void ensureIndexKnown() { + if(index == -1) { + if(previous == -1) { + index = 0; + } + else if(next == -1) { + index = size; + } + else { + index = 1; + for(int pos = firstIndex;pos != previous;pos = (int)links[pos], index++); + } + } + } + + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/collections/templates/maps/impl/customHash/OpenCustomHashMap.template b/src/builder/resources/speiger/assets/collections/templates/maps/impl/customHash/OpenCustomHashMap.template index d736385..a362ad9 100644 --- a/src/builder/resources/speiger/assets/collections/templates/maps/impl/customHash/OpenCustomHashMap.template +++ b/src/builder/resources/speiger/assets/collections/templates/maps/impl/customHash/OpenCustomHashMap.template @@ -1,1554 +1,1556 @@ -package speiger.src.collections.PACKAGE.maps.impl.customHash; - -import java.util.Arrays; -import java.util.ConcurrentModificationException; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Objects; -import java.util.function.Consumer; -import java.util.function.BiFunction; -import java.util.function.Predicate; -#if !TYPE_OBJECT && JDK_TYPE -import java.util.function.PREDICATE; -#endif -#if !SAME_TYPE && JDK_VALUE && !VALUE_OBJECT -import java.util.function.VALUE_PREDICATE; -#endif - -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.collections.ITERATOR; -import speiger.src.collections.PACKAGE.functions.CONSUMER; -import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; -#endif -import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER; -#if !TYPE_OBJECT && !VALUE_OBJECT -import speiger.src.collections.ints.functions.consumer.IntObjectConsumer; -#endif -#if !SAME_TYPE -import speiger.src.collections.ints.functions.consumer.VALUE_BI_FROM_INT_CONSUMER; -#endif -import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; -#if !VALUE_BOOLEAN || !JDK_TYPE -import speiger.src.collections.PACKAGE.functions.function.FUNCTION; -#endif -import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; -#if !SAME_TYPE -import speiger.src.collections.PACKAGE.functions.function.SINGLE_UNARY_OPERATOR; -#endif -#if !TYPE_OBJECT && !VALUE_BOOLEAN && !JDK_TYPE -import speiger.src.collections.PACKAGE.functions.function.PREDICATE; -#endif -import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET; -import speiger.src.collections.PACKAGE.sets.SET; -#endif -import speiger.src.collections.PACKAGE.utils.STRATEGY; -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; -import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_SUPPLIER; -#if !SAME_TYPE -import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR; - -#if !VALUE_OBJECT -#if !TYPE_OBJECT -import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator; -#endif - -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; -import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER; -#endif -#else if !VALUE_OBJECT -import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator; - -#endif -#if !TYPE_OBJECT && !VALUE_OBJECT || !VALUE_OBJECT -import speiger.src.collections.objects.functions.consumer.ObjectObjectConsumer; -#endif -#if !SAME_TYPE -#if !TYPE_OBJECT -import speiger.src.collections.objects.functions.consumer.VALUE_BI_FROM_OBJECT_CONSUMER; - -#endif -#if !JDK_VALUE -import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE; -#endif -#endif -import speiger.src.collections.objects.collections.ObjectIterator; -import speiger.src.collections.objects.sets.AbstractObjectSet; -import speiger.src.collections.objects.sets.ObjectSet; -import speiger.src.collections.utils.HashUtil; -import speiger.src.collections.utils.ITrimmable; - -/** - * A Type Specific HashMap that allows for custom HashControl. - * For cases where Objects/primitive do not allow hashcoding this can be really useful and provide a lot of control. - * @Type(T) - * @ValueType(V) - */ -public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements ITrimmable -{ - /** The Backing keys array */ - protected transient KEY_TYPE[] keys; - /** The Backing values array */ - protected transient VALUE_TYPE[] values; - /** If a null value is present */ - protected transient boolean containsNull; - /** Minimum array size the HashMap will be */ - protected transient int minCapacity; - /** Index of the Null Value */ - protected transient int nullIndex; - /** Maximum amount of Values that can be stored before the array gets expanded usually 75% */ - protected transient int maxFill; - /** Max Index that is allowed to be searched through nullIndex - 1 */ - protected transient int mask; - /** EntrySet cache */ - protected transient FastEntrySet KEY_VALUE_GENERIC_TYPE entrySet; - /** KeySet cache */ - protected transient SET KEY_GENERIC_TYPE keySet; - /** Values cache */ - protected transient VALUE_COLLECTION VALUE_GENERIC_TYPE valuesC; - - /** Amount of Elements stored in the HashMap */ - protected int size; - /** How full the Arrays are allowed to get before resize */ - protected final float loadFactor; - /** Strategy that allows to control the Hash Generation and equals comparason */ - protected final STRATEGY KEY_SUPER_GENERIC_TYPE strategy; - - /** - * Default Contstructor - * @param strategy the strategy that allows hash control. - * @throws NullPointerException if Strategy is null - */ - public CUSTOM_HASH_MAP(STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { - this(HashUtil.DEFAULT_MIN_CAPACITY, HashUtil.DEFAULT_LOAD_FACTOR, strategy); - } - - /** - * Constructor that defines the minimum capacity - * @param minCapacity the minimum capacity the HashMap is allowed to be. - * @param strategy the strategy that allows hash control. - * @throws NullPointerException if Strategy is null - * @throws IllegalStateException if the minimum capacity is negative - */ - public CUSTOM_HASH_MAP(int minCapacity, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { - this(minCapacity, HashUtil.DEFAULT_LOAD_FACTOR, strategy); - } - - /** - * Constructor that defines the minimum capacity and load factor - * @param minCapacity the minimum capacity the HashMap is allowed to be. - * @param loadFactor the percentage of how full the backing array can be before they resize - * @param strategy the strategy that allows hash control. - * @throws NullPointerException if Strategy is null - * @throws IllegalStateException if the minimum capacity is negative - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - */ - public CUSTOM_HASH_MAP(int minCapacity, float loadFactor, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { - if(minCapacity < 0) throw new IllegalStateException("Minimum Capacity is negative. This is not allowed"); - if(loadFactor <= 0 || loadFactor >= 1F) throw new IllegalStateException("Load Factor is not between 0 and 1"); - this.loadFactor = loadFactor; - this.minCapacity = nullIndex = HashUtil.arraySize(minCapacity, loadFactor); - this.strategy = strategy; - mask = nullIndex - 1; - maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1); - keys = NEW_KEY_ARRAY(nullIndex + 1); - values = NEW_VALUE_ARRAY(nullIndex + 1); - } - -#if !TYPE_OBJECT || !VALUE_OBJECT - /** - * Helper constructor that allow to create a map from boxed values (it will unbox them) - * @param keys the keys that should be put into the map - * @param values the values that should be put into the map. - * @param strategy the strategy that allows hash control. - * @throws NullPointerException if Strategy is null - * @throws IllegalStateException if the keys and values do not match in lenght - */ - public CUSTOM_HASH_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { - this(keys, values, HashUtil.DEFAULT_LOAD_FACTOR, strategy); - } - - /** - * Helper constructor that allow to create a map from boxed values (it will unbox them) - * @param keys the keys that should be put into the map - * @param values the values that should be put into the map. - * @param loadFactor the percentage of how full the backing array can be before they resize - * @param strategy the strategy that allows hash control. - * @throws NullPointerException if Strategy is null - * @throws IllegalStateException if the keys and values do not match in lenght - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - */ - public CUSTOM_HASH_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, float loadFactor, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { - this(keys.length, loadFactor, strategy); - if(keys.length != values.length) throw new IllegalStateException("Input Arrays are not equal size"); - for(int i = 0,m=keys.length;i map, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { - this(map, HashUtil.DEFAULT_LOAD_FACTOR, strategy); - } - - /** - * A Helper constructor that allows to create a Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - * @param loadFactor the percentage of how full the backing array can be before they resize - * @param strategy the strategy that allows hash control. - * @throws NullPointerException if Strategy is null - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - */ - public CUSTOM_HASH_MAP(Map map, float loadFactor, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { - this(map.size(), loadFactor, strategy); - putAll(map); - } - - /** - * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - * @param strategy the strategy that allows hash control. - * @throws NullPointerException if Strategy is null - */ - public CUSTOM_HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { - this(map, HashUtil.DEFAULT_LOAD_FACTOR, strategy); - } - - /** - * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - * @param loadFactor the percentage of how full the backing array can be before they resize - * @param strategy the strategy that allows hash control. - * @throws NullPointerException if Strategy is null - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - */ - public CUSTOM_HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map, float loadFactor, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { - this(map.size(), loadFactor, strategy); - putAll(map); - } - - @Override - public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { - int slot = findIndex(key); - if(slot < 0) { - insert(-slot-1, key, value); - return getDefaultReturnValue(); - } - VALUE_TYPE oldValue = values[slot]; - values[slot] = value; - return oldValue; - } - - @Override - public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { - int slot = findIndex(key); - if(slot < 0) { - insert(-slot-1, key, value); - return getDefaultReturnValue(); - } - else if(VALUE_EQUALS(values[slot], getDefaultReturnValue())) { - VALUE_TYPE oldValue = values[slot]; - values[slot] = value; - return oldValue; - } - return values[slot]; - } - -#if VALUE_PRIMITIVES - @Override - public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { - int slot = findIndex(key); - if(slot < 0) { - insert(-slot-1, key, value); - return getDefaultReturnValue(); - } - VALUE_TYPE oldValue = values[slot]; - values[slot] += value; - return oldValue; - } - - @Override - public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { - int slot = findIndex(key); - if(slot < 0) return getDefaultReturnValue(); - VALUE_TYPE oldValue = values[slot]; - values[slot] -= value; - if(value < 0 ? (values[slot] >= getDefaultReturnValue()) : (values[slot] <= getDefaultReturnValue())) removeIndex(slot); - return oldValue; - } -#endif -#if !TYPE_OBJECT - @Override - public boolean containsKey(KEY_TYPE key) { - return findIndex(key) >= 0; - } - -#endif - @Override - @Primitive - public boolean containsKey(Object key) { -#if !TYPE_OBJECT - return key instanceof CLASS_TYPE && findIndex(CLASS_TO_KEY(key)) >= 0; -#else - return findIndex(CLASS_TO_KEY(key)) >= 0; -#endif - } - -#if !VALUE_OBJECT - @Override - public boolean containsValue(VALUE_TYPE value) { - if(containsNull && VALUE_EQUALS(values[nullIndex], value)) return true; - for(int i = nullIndex;i >= 0;i--) - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && VALUE_EQUALS(values[i], value)) return true; - return false; - } - -#endif - @Override - @ValuePrimitive - public boolean containsValue(Object value) { -#if VALUE_OBJECT - if(containsNull && VALUE_EQUALS(values[nullIndex], value)) return true; -#else - if(containsNull && ((value == null && values[nullIndex] == getDefaultReturnValue()) || EQUALS_VALUE_TYPE(values[nullIndex], value))) return true; -#endif - for(int i = nullIndex-1;i >= 0;i--) -#if VALUE_OBJECT - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && EQUALS_VALUE_TYPE(values[i], value)) return true; -#else - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && ((value == null && values[i] == getDefaultReturnValue()) || EQUALS_VALUE_TYPE(values[i], value))) return true; -#endif - return false; - } - - @Override - public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { - int slot = findIndex(key); - if(slot < 0) return getDefaultReturnValue(); - return removeIndex(slot); - } - - @Override - public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { - int slot = findIndex(key); - if(slot < 0) return defaultValue; - return removeIndex(slot); - } - - @Override - public CLASS_VALUE_TYPE remove(Object key) { -#if !TYPE_OBJECT - if(!(key instanceof CLASS_TYPE)) return getDefaultReturnValue(); -#endif - int slot = findIndex(CLASS_TO_KEY(key)); - if(slot < 0) return VALUE_TO_OBJ(getDefaultReturnValue()); - return removeIndex(slot); - } - -#if !TYPE_OBJECT || !VALUE_OBJECT - @Override - public boolean remove(KEY_TYPE key, VALUE_TYPE value) { - if(strategy.equals(key, EMPTY_KEY_VALUE)) { - if(containsNull && VALUE_EQUALS(value, values[nullIndex])) { - removeNullIndex(); - return true; - } - return false; - } - int pos = HashUtil.mix(strategy.hashCode(key)) & mask; - KEY_TYPE current = keys[pos]; - if(strategy.equals(current, EMPTY_KEY_VALUE)) return false; - if(strategy.equals(current, key) && VALUE_EQUALS(value, values[pos])) { - removeIndex(pos); - return true; - } - while(true) { - if(strategy.equals((current = keys[pos = (++pos & mask)]), EMPTY_KEY_VALUE)) return false; - else if(strategy.equals(current, key) && VALUE_EQUALS(value, values[pos])) { - removeIndex(pos); - return true; - } - } - } - -#endif - @Override - public boolean remove(Object key, Object value) { - Objects.requireNonNull(value); -#if TYPE_OBJECT - if(key == null) { -#else - if(key == null || (key instanceof CLASS_TYPE && strategy.equals(CLASS_TO_KEY(key), EMPTY_KEY_VALUE))) { -#endif - if(containsNull && EQUALS_VALUE_TYPE(values[nullIndex], value)) { - removeNullIndex(); - return true; - } - return false; - } -#if !TYPE_OBJECT - if(!(key instanceof CLASS_TYPE)) return false; -#endif - KEY_TYPE keyType = CLASS_TO_KEY(key); - int pos = HashUtil.mix(strategy.hashCode(keyType)) & mask; - KEY_TYPE current = keys[pos]; - if(strategy.equals(current, EMPTY_KEY_VALUE)) return false; - if(strategy.equals(current, keyType) && EQUALS_VALUE_TYPE(values[pos], value)) { - removeIndex(pos); - return true; - } - while(true) { - if(strategy.equals((current = keys[pos = (++pos & mask)]), EMPTY_KEY_VALUE)) return false; - else if(strategy.equals(current, keyType) && EQUALS_VALUE_TYPE(values[pos], value)){ - removeIndex(pos); - return true; - } - } - } - - @Override - public VALUE_TYPE GET_VALUE(KEY_TYPE key) { - int slot = findIndex(key); - return slot < 0 ? getDefaultReturnValue() : values[slot]; - } - - @Override - public CLASS_VALUE_TYPE get(Object key) { -#if !TYPE_OBJECT - if(!(key instanceof CLASS_TYPE)) return getDefaultReturnValue(); -#endif - int slot = findIndex(CLASS_TO_KEY(key)); - return VALUE_TO_OBJ(slot < 0 ? getDefaultReturnValue() : values[slot]); - } - -#if TYPE_OBJECT && VALUE_OBJECT - @Override - public VALUE_TYPE getOrDefault(Object key, VALUE_TYPE defaultValue) { - int slot = findIndex(CLASS_TO_KEY(key)); - return slot < 0 ? defaultValue : values[slot]; - } - -#else - @Override - public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { - int slot = findIndex(key); - return slot < 0 ? defaultValue : values[slot]; - } - -#endif - @Override - public CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE copy() { - CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE map = new CUSTOM_HASH_MAPKV_BRACES(0, loadFactor, strategy); - map.minCapacity = minCapacity; - map.mask = mask; - map.maxFill = maxFill; - map.nullIndex = nullIndex; - map.containsNull = containsNull; - map.size = size; - map.keys = Arrays.copyOf(keys, keys.length); - map.values = Arrays.copyOf(values, values.length); - return map; - } - - @Override - public ObjectSet ENTRY_SET() { - if(entrySet == null) entrySet = new MapEntrySet(); - return entrySet; - } - - @Override - public SET KEY_GENERIC_TYPE keySet() { - if(keySet == null) keySet = new KeySet(); - return keySet; - } - - @Override - public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { - if(valuesC == null) valuesC = new Values(); - return valuesC; - } - - @Override - public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { - if(size() <= 0) return; - if(containsNull) action.accept(keys[nullIndex], values[nullIndex]); - for(int i = nullIndex-1;i>=0;i--) { - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(keys[i], values[i]); - } - } - - @Override - public boolean replace(KEY_TYPE key, VALUE_TYPE oldValue, VALUE_TYPE newValue) { - int index = findIndex(key); - if(index < 0 || values[index] != oldValue) return false; - values[index] = newValue; - return true; - } - - @Override - public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value) { - int index = findIndex(key); - if(index < 0) return getDefaultReturnValue(); - VALUE_TYPE oldValue = values[index]; - values[index] = value; - return oldValue; - } - - @Override - public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); - int index = findIndex(key); - if(index < 0) { - VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, getDefaultReturnValue()); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - insert(-index-1, key, newValue); - return newValue; - } - VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, values[index]); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - removeIndex(index); - return newValue; - } - values[index] = newValue; - return newValue; - } - - @Override - public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); - int index = findIndex(key); - if(index < 0) { - VALUE_TYPE newValue = mappingFunction.APPLY(key); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - insert(-index-1, key, newValue); - return newValue; - } - VALUE_TYPE newValue = values[index]; - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - newValue = mappingFunction.APPLY(key); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - values[index] = newValue; - } - return newValue; - } - - @Override - public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) { - Objects.requireNonNull(valueProvider); - int index = findIndex(key); - if(index < 0) { - VALUE_TYPE newValue = valueProvider.VALUE_SUPPLY_GET(); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - insert(-index-1, key, newValue); - return newValue; - } - VALUE_TYPE newValue = values[index]; - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - newValue = valueProvider.VALUE_SUPPLY_GET(); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - values[index] = newValue; - } - return newValue; - } - - @Override - public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); - int index = findIndex(key); - if(index < 0 || VALUE_EQUALS(values[index], getDefaultReturnValue())) return getDefaultReturnValue(); - VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, values[index]); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - removeIndex(index); - return newValue; - } - values[index] = newValue; - return newValue; - } - - @Override - public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); -#if VALUE_OBJECT - Objects.requireNonNull(value); -#endif - int index = findIndex(key); - VALUE_TYPE newValue = index < 0 || VALUE_EQUALS(values[index], getDefaultReturnValue()) ? value : mappingFunction.APPLY_VALUE(values[index], value); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - if(index >= 0) - removeIndex(index); - } - else if(index < 0) insert(-index-1, key, newValue); - else values[index] = newValue; - return newValue; - } - - @Override - public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); - for(MAP.Entry KEY_VALUE_GENERIC_TYPE entry : getFastIterable(m)) { - KEY_TYPE key = entry.ENTRY_KEY(); - int index = findIndex(key); - VALUE_TYPE newValue = index < 0 || VALUE_EQUALS(values[index], getDefaultReturnValue()) ? entry.ENTRY_VALUE() : mappingFunction.APPLY_VALUE(values[index], entry.ENTRY_VALUE()); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - if(index >= 0) - removeIndex(index); - } - else if(index < 0) insert(-index-1, key, newValue); - else values[index] = newValue; - } - } - - @Override - public int size() { return size; } - - @Override - public void clear() { - if(size == 0) return; - size = 0; - containsNull = false; - Arrays.fill(keys, EMPTY_KEY_VALUE); - Arrays.fill(values, EMPTY_VALUE); - } - - @Override - public boolean trim(int size) { - int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor))); - if(request >= nullIndex || this.size > Math.min((int)Math.ceil(request * loadFactor), request - 1)) return false; - try { - rehash(request); - } - catch(OutOfMemoryError noMemory) { return false; } - return true; - } - - @Override - public void clearAndTrim(int size) { - int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor))); - if(request >= nullIndex) { - clear(); - return; - } - nullIndex = request; - mask = request-1; - maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1); - keys = NEW_KEY_ARRAY(request + 1); - values = NEW_VALUE_ARRAY(request + 1); - this.size = 0; - containsNull = false; - } - -#if !TYPE_OBJECT - protected int findIndex(KEY_TYPE key) { - if(strategy.equals(key, EMPTY_KEY_VALUE)) return containsNull ? nullIndex : -(nullIndex + 1); - int pos = HashUtil.mix(strategy.hashCode(key)) & mask; - KEY_TYPE current = keys[pos]; - if(!strategy.equals(current, EMPTY_KEY_VALUE)) { - if(strategy.equals(current, key)) return pos; - while(!strategy.equals((current = keys[pos = (++pos & mask)]), EMPTY_KEY_VALUE)) - if(strategy.equals(current, key)) return pos; - } - return -(pos + 1); - } - -#endif - protected int findIndex(CLASS_TYPE key) { - if(key == null) return containsNull ? nullIndex : -(nullIndex + 1); - KEY_TYPE keyType = CLASS_TO_KEY(key); -#if !TYPE_OBJECT - if(strategy.equals(keyType, EMPTY_KEY_VALUE)) return containsNull ? nullIndex : -(nullIndex + 1); -#endif - int pos = HashUtil.mix(strategy.hashCode(keyType)) & mask; - KEY_TYPE current = keys[pos]; - if(!strategy.equals(current, EMPTY_KEY_VALUE)) { - if(strategy.equals(current, keyType)) return pos; - while(!strategy.equals((current = keys[pos = (++pos & mask)]), EMPTY_KEY_VALUE)) - if(strategy.equals(current, keyType)) return pos; - } - return -(pos + 1); - } - - protected VALUE_TYPE removeIndex(int pos) { - if(pos == nullIndex) return containsNull ? removeNullIndex() : getDefaultReturnValue(); - VALUE_TYPE value = values[pos]; - keys[pos] = EMPTY_KEY_VALUE; - values[pos] = EMPTY_VALUE; - size--; - onNodeRemoved(pos); - shiftKeys(pos); - if(nullIndex > minCapacity && size < maxFill / 4 && nullIndex > HashUtil.DEFAULT_MIN_CAPACITY) rehash(nullIndex / 2); - return value; - } - - protected VALUE_TYPE removeNullIndex() { - VALUE_TYPE value = values[nullIndex]; - containsNull = false; - keys[nullIndex] = EMPTY_KEY_VALUE; - values[nullIndex] = EMPTY_VALUE; - size--; - onNodeRemoved(nullIndex); - if(nullIndex > minCapacity && size < maxFill / 4 && nullIndex > HashUtil.DEFAULT_MIN_CAPACITY) rehash(nullIndex / 2); - return value; - } - - protected void insert(int slot, KEY_TYPE key, VALUE_TYPE value) { - if(slot == nullIndex) containsNull = true; - keys[slot] = key; - values[slot] = value; - onNodeAdded(slot); - if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor)); - } - - protected void rehash(int newSize) { - int newMask = newSize - 1; - KEY_TYPE[] newKeys = NEW_KEY_ARRAY(newSize + 1); - VALUE_TYPE[] newValues = NEW_VALUE_ARRAY(newSize + 1); - for(int i = nullIndex, pos = 0, j = (size - (containsNull ? 1 : 0));j-- != 0;) { - while(true) { - if(--i < 0) throw new ConcurrentModificationException("Map was modified during rehash"); - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) break; - } - if(!strategy.equals(newKeys[pos = HashUtil.mix(strategy.hashCode(keys[i])) & newMask], EMPTY_KEY_VALUE)) - while(!strategy.equals(newKeys[pos = (++pos & newMask)], EMPTY_KEY_VALUE)); - newKeys[pos] = keys[i]; - newValues[pos] = values[i]; - } - newValues[newSize] = values[nullIndex]; - nullIndex = newSize; - mask = newMask; - maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1); - keys = newKeys; - values = newValues; - } - - protected void onNodeAdded(int pos) { - - } - - protected void onNodeRemoved(int pos) { - - } - - protected void onNodeMoved(int from, int to) { - - } - - protected void shiftKeys(int startPos) { - int slot, last; - KEY_TYPE current; - while(true) { - startPos = ((last = startPos) + 1) & mask; - while(true){ - if(strategy.equals((current = keys[startPos]), EMPTY_KEY_VALUE)) { - keys[last] = EMPTY_KEY_VALUE; - values[last] = EMPTY_VALUE; - return; - } - slot = HashUtil.mix(strategy.hashCode(current)) & mask; - if(last <= startPos ? (last >= slot || slot > startPos) : (last >= slot && slot > startPos)) break; - startPos = ++startPos & mask; - } - keys[last] = current; - values[last] = values[startPos]; - onNodeMoved(startPos, last); - } - } - - protected class MapEntry implements MAP.Entry KEY_VALUE_GENERIC_TYPE, Map.Entry { - public int index = -1; - - public MapEntry() {} - public MapEntry(int index) { - this.index = index; - } - - @Override - public KEY_TYPE ENTRY_KEY() { - return keys[index]; - } - - @Override - public VALUE_TYPE ENTRY_VALUE() { - return values[index]; - } - - @Override - public VALUE_TYPE setValue(VALUE_TYPE value) { - VALUE_TYPE oldValue = values[index]; - values[index] = value; - return oldValue; - } - - @Override - public boolean equals(Object obj) { - if(obj instanceof Map.Entry) { - if(obj instanceof MAP.Entry) { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)obj; - return KEY_EQUALS(keys[index], entry.ENTRY_KEY()) && VALUE_EQUALS(values[index], entry.ENTRY_VALUE()); - } - Map.Entry entry = (Map.Entry)obj; - Object key = entry.getKey(); - Object value = entry.getValue(); -#if TYPE_OBJECT && VALUE_OBJECT - return KEY_EQUALS(keys[index], key) && VALUE_EQUALS(values[index], value); -#else if TYPE_OBJECT - return value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(keys[index], key) && VALUE_EQUALS(values[index], CLASS_TO_VALUE(value)); -#else if VALUE_OBJECT - return key instanceof CLASS_TYPE && KEY_EQUALS(keys[index], CLASS_TO_KEY(key)) && VALUE_EQUALS(values[index], value); -#else - return key instanceof CLASS_TYPE && value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(keys[index], CLASS_TO_KEY(key)) && VALUE_EQUALS(values[index], CLASS_TO_VALUE(value)); -#endif - } - return false; - } - - @Override - public int hashCode() { - return strategy.hashCode(keys[index]) ^ VALUE_TO_HASH(values[index]); - } - - @Override - public String toString() { - return KEY_TO_STRING(keys[index]) + "=" + VALUE_TO_STRING(values[index]); - } - } - - private final class MapEntrySet extends AbstractObjectSet implements MAP.FastEntrySet KEY_VALUE_GENERIC_TYPE { - @Override - public ObjectIterator fastIterator() { - return new FastEntryIterator(); - } - - @Override - public ObjectIterator iterator() { - return new EntryIterator(); - } - - @Override - public void forEach(Consumer action) { - if(containsNull) action.accept(new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex])); - for(int i = nullIndex-1;i>=0;i--) - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(new BasicEntryKV_BRACES(keys[i], values[i])); - } - - @Override - public void fastForEach(Consumer action) { - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - if(containsNull) { - entry.set(keys[nullIndex], values[nullIndex]); - action.accept(entry); - } - for(int i = nullIndex-1;i>=0;i--) { - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) { - entry.set(keys[i], values[i]); - action.accept(entry); - } - } - } - - @Override - public void forEachIndexed(IntObjectConsumer action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - if(containsNull) action.accept(0, new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex])); - for(int i = nullIndex-1, index = containsNull ? 1 : 0;i>=0;i--) { - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(index++, new BasicEntryKV_BRACES(keys[i], values[i])); - } - } - - @Override - public void forEach(E input, ObjectObjectConsumer action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - if(containsNull) action.accept(input, new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex])); - for(int i = nullIndex-1;i>=0;i--) { - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(input, new BasicEntryKV_BRACES(keys[i], values[i])); - } - } - - @Override - public boolean matchesAny(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return false; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - if(containsNull) { - entry.set(keys[nullIndex], values[nullIndex]); - if(filter.test(entry)) return true; - } - for(int i = nullIndex-1;i>=0;i--) { - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) { - entry.set(keys[i], values[i]); - if(filter.test(entry)) return true; - } - } - return false; - } - - @Override - public boolean matchesNone(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - if(containsNull) { - entry.set(keys[nullIndex], values[nullIndex]); - if(filter.test(entry)) return false; - } - for(int i = nullIndex-1;i>=0;i--) { - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) { - entry.set(keys[i], values[i]); - if(filter.test(entry)) return false; - } - } - return true; - } - - @Override - public boolean matchesAll(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - if(containsNull) { - entry.set(keys[nullIndex], values[nullIndex]); - if(!filter.test(entry)) return false; - } - for(int i = nullIndex-1;i>=0;i--) { - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) { - entry.set(keys[i], values[i]); - if(!filter.test(entry)) return false; - } - } - return true; - } - - @Override - public E reduce(E identity, BiFunction operator) { - Objects.requireNonNull(operator); - E state = identity; - if(containsNull) state = operator.apply(state, new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex])); - for(int i = nullIndex-1;i>=0;i--) { - if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue; - state = operator.apply(state, new BasicEntryKV_BRACES(keys[i], values[i])); - } - return state; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE reduce(ObjectObjectUnaryOperator operator) { - Objects.requireNonNull(operator); - MAP.Entry KEY_VALUE_GENERIC_TYPE state = null; - boolean empty = true; - if(containsNull) { - state = new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex]); - empty = false; - } - for(int i = nullIndex-1;i>=0;i--) { - if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue; - if(empty) { - empty = false; - state = new BasicEntryKV_BRACES(keys[i], values[i]); - continue; - } - state = operator.apply(state, new BasicEntryKV_BRACES(keys[i], values[i])); - } - return state; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE findFirst(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return null; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - if(containsNull) { - entry.set(keys[nullIndex], values[nullIndex]); - if(filter.test(entry)) return entry; - } - for(int i = nullIndex-1;i>=0;i--) { - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) { - entry.set(keys[i], values[i]); - if(filter.test(entry)) return entry; - } - } - return null; - } - - @Override - public int count(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return 0; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - int result = 0; - if(containsNull) { - entry.set(keys[nullIndex], values[nullIndex]); - if(filter.test(entry)) result++; - } - for(int i = nullIndex-1;i>=0;i--) { - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) { - entry.set(keys[i], values[i]); - if(filter.test(entry)) result++; - } - } - return result; - } - - @Override - public int size() { - return CUSTOM_HASH_MAP.this.size(); - } - - @Override - public void clear() { - CUSTOM_HASH_MAP.this.clear(); - } - - @Override - public boolean contains(Object o) { - if(o instanceof Map.Entry) { - if(o instanceof MAP.Entry) { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; - int index = CUSTOM_HASH_MAP.this.findIndex(entry.ENTRY_KEY()); - if(index >= 0) return VALUE_EQUALS(entry.ENTRY_VALUE(), CUSTOM_HASH_MAP.this.values[index]); - } - else { - Map.Entry entry = (Map.Entry)o; -#if !TYPE_OBJECT - if(!(entry.getKey() instanceof CLASS_TYPE)) return false; -#endif - int index = CUSTOM_HASH_MAP.this.findIndex((CLASS_TYPE)entry.getKey()); - if(index >= 0) return Objects.equals(entry.getValue(), VALUE_TO_OBJ(CUSTOM_HASH_MAP.this.values[index])); - } - } - return false; - } - - @Override - public boolean remove(Object o) { - if(o instanceof Map.Entry) { - if(o instanceof MAP.Entry) { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; - return CUSTOM_HASH_MAP.this.remove(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); - } - Map.Entry entry = (Map.Entry)o; - return CUSTOM_HASH_MAP.this.remove(entry.getKey(), entry.getValue()); - } - return false; - } - } - - private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE { -#if TYPE_OBJECT - @Override - public boolean contains(Object e) { - return containsKey(e); - } - - @Override - public boolean remove(Object o) { - int oldSize = size; - CUSTOM_HASH_MAP.this.remove(o); - return size != oldSize; - } - -#else - @Override - public boolean contains(KEY_TYPE e) { - return containsKey(e); - } - - @Override - public boolean remove(KEY_TYPE o) { - int oldSize = size; - CUSTOM_HASH_MAP.this.remove(o); - return size != oldSize; - } - -#endif - @Override - public boolean add(KEY_TYPE o) { - throw new UnsupportedOperationException(); - } - - @Override - public ITERATOR KEY_GENERIC_TYPE iterator() { - return new KeyIterator(); - } - - @Override - public KeySet copy() { throw new UnsupportedOperationException(); } - - @Override - public int size() { - return CUSTOM_HASH_MAP.this.size(); - } - - @Override - public void clear() { - CUSTOM_HASH_MAP.this.clear(); - } - - @Override - public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { - Objects.requireNonNull(action); - if(containsNull) action.accept(keys[nullIndex]); - for(int i = nullIndex-1;i>=0;i--) - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(keys[i]); - } - - @Override - public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - if(containsNull) action.accept(0, keys[nullIndex]); - for(int i = nullIndex-1, index = containsNull ? 1 : 0;i>=0;i--) { - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(index++, keys[i]); - } - } - - @Override - public void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - if(containsNull) action.accept(input, keys[nullIndex]); - for(int i = nullIndex-1;i>=0;i--) { - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(input, keys[i]); - } - } - - @Override - public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return false; - if(containsNull && filter.test(keys[nullIndex])) return true; - for(int i = nullIndex-1;i>=0;i--) { - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.test(keys[i])) return true; - } - return false; - } - - @Override - public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - if(containsNull && filter.test(keys[nullIndex])) return false; - for(int i = nullIndex-1;i>=0;i--) { - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.test(keys[i])) return false; - } - return true; - } - - @Override - public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - if(containsNull && !filter.test(keys[nullIndex])) return false; - for(int i = nullIndex-1;i>=0;i--) { - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && !filter.test(keys[i])) return false; - } - return true; - } - -#if !TYPE_OBJECT - @Override - public KEY_TYPE reduce(KEY_TYPE identity, SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - KEY_TYPE state = identity; - if(containsNull) state = operator.APPLY_KEY_VALUE(state, keys[nullIndex]); - for(int i = nullIndex-1;i>=0;i--) { - if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue; - state = operator.APPLY_KEY_VALUE(state, keys[i]); - } - return state; - } - -#else - @Override - public KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) { - Objects.requireNonNull(operator); - KEY_SPECIAL_TYPE state = identity; - if(containsNull) state = operator.apply(state, keys[nullIndex]); - for(int i = nullIndex-1;i>=0;i--) { - if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue; - state = operator.apply(state, keys[i]); - } - return state; - } - -#endif - @Override - public KEY_TYPE reduce(SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - KEY_TYPE state = EMPTY_KEY_VALUE; - boolean empty = true; - if(containsNull) { - state = keys[nullIndex]; - empty = false; - } - for(int i = nullIndex-1;i>=0;i--) { - if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue; - if(empty) { - empty = false; - state = keys[i]; - continue; - } - state = operator.APPLY_KEY_VALUE(state, keys[i]); - } - return state; - } - - @Override - public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return EMPTY_KEY_VALUE; - if(containsNull && filter.test(keys[nullIndex])) return keys[nullIndex]; - for(int i = nullIndex-1;i>=0;i--) { - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.test(keys[i])) return keys[i]; - } - return EMPTY_KEY_VALUE; - } - - @Override - public int count(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return 0; - int result = 0; - if(containsNull && filter.test(keys[nullIndex])) result++; - for(int i = nullIndex-1;i>=0;i--) { - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.test(keys[i])) result++; - } - return result; - } - } - - private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { -#if VALUE_OBJECT - @Override - public boolean contains(Object e) { - return containsValue(e); - } - -#else - @Override - public boolean contains(VALUE_TYPE e) { - return containsValue(e); - } - -#endif - @Override - public boolean add(VALUE_TYPE o) { - throw new UnsupportedOperationException(); - } - - @Override - public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() { - return new ValueIterator(); - } - - @Override - public int size() { - return CUSTOM_HASH_MAP.this.size(); - } - - @Override - public void clear() { - CUSTOM_HASH_MAP.this.clear(); - } - - @Override - public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) { - if(containsNull) action.accept(values[nullIndex]); - for(int i = nullIndex-1;i>=0;i--) - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(values[i]); - } - - @Override - public void forEachIndexed(VALUE_BI_FROM_INT_CONSUMER VALUE_GENERIC_TYPE action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - if(containsNull) action.accept(0, values[nullIndex]); - for(int i = nullIndex-1, index = containsNull ? 1 : 0;i>=0;i--) { - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(index++, values[i]); - } - } - - @Override - public void forEach(E input, VALUE_BI_FROM_OBJECT_CONSUMER VSV_GENERIC_TYPE action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - if(containsNull) action.accept(input, values[nullIndex]); - for(int i = nullIndex-1;i>=0;i--) { - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(input, values[i]); - } - } - - @Override - public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return false; - if(containsNull && filter.test(values[nullIndex])) return true; - for(int i = nullIndex-1;i>=0;i--) { - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.test(values[i])) return true; - } - return false; - } - - @Override - public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - if(containsNull && filter.test(values[nullIndex])) return false; - for(int i = nullIndex-1;i>=0;i--) { - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.test(values[i])) return false; - } - return true; - } - - @Override - public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - if(containsNull && !filter.test(values[nullIndex])) return false; - for(int i = nullIndex-1;i>=0;i--) { - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && !filter.test(values[i])) return false; - } - return true; - } - -#if !VALUE_OBJECT - @Override - public VALUE_TYPE reduce(VALUE_TYPE identity, VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - VALUE_TYPE state = identity; - if(containsNull) state = operator.APPLY_VALUE(state, values[nullIndex]); - for(int i = nullIndex-1;i>=0;i--) { - if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue; - state = operator.APPLY_VALUE(state, values[i]); - } - return state; - } - -#else - @Override - public VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction operator) { - Objects.requireNonNull(operator); - VALUE_SPECIAL_TYPE state = identity; - if(containsNull) state = operator.APPLY_VALUE(state, values[nullIndex]); - for(int i = nullIndex-1;i>=0;i--) { - if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue; - state = operator.APPLY_VALUE(state, values[i]); - } - return state; - } - -#endif - @Override - public VALUE_TYPE reduce(VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - VALUE_TYPE state = EMPTY_VALUE; - boolean empty = true; - if(containsNull) { - state = values[nullIndex]; - empty = false; - } - for(int i = nullIndex-1;i>=0;i--) { - if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue; - if(empty) { - empty = false; - state = values[i]; - continue; - } - state = operator.APPLY_VALUE(state, values[i]); - } - return state; - } - - @Override - public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return EMPTY_VALUE; - if(containsNull && filter.test(values[nullIndex])) return values[nullIndex]; - for(int i = nullIndex-1;i>=0;i--) { - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.test(values[i])) return values[i]; - } - return EMPTY_VALUE; - } - - @Override - public int count(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return 0; - int result = 0; - if(containsNull && filter.test(values[nullIndex])) result++; - for(int i = nullIndex-1;i>=0;i--) { - if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.test(values[i])) result++; - } - return result; - } - } - - private class FastEntryIterator extends MapIterator implements ObjectIterator { - MapEntry entry = new MapEntry(); - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { - entry.index = nextEntry(); - return entry; - } - } - - private class EntryIterator extends MapIterator implements ObjectIterator { - MapEntry entry; - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { - return entry = new MapEntry(nextEntry()); - } - - @Override - public void remove() { - super.remove(); - entry.index = -1; - } - } - - private class KeyIterator extends MapIterator implements ITERATOR KEY_GENERIC_TYPE { - @Override - public KEY_TYPE NEXT() { - return keys[nextEntry()]; - } - } - - private class ValueIterator extends MapIterator implements VALUE_ITERATOR VALUE_GENERIC_TYPE { - @Override - public VALUE_TYPE VALUE_NEXT() { - return values[nextEntry()]; - } - } - - private class MapIterator { - int pos = nullIndex; - int returnedPos = -1; - int lastReturned = -1; - int nextIndex = Integer.MIN_VALUE; - boolean returnNull = containsNull; - KEY_TYPE[] wrapped = null; - int wrappedIndex = 0; - - public boolean hasNext() { - if(nextIndex == Integer.MIN_VALUE) { - if(returnNull) { - returnNull = false; - nextIndex = nullIndex; - } - else - { - while(true) { - if(--pos < 0) { - if(wrapped == null || wrappedIndex <= -pos - 1) break; - nextIndex = -pos - 1; - break; - } - if(!strategy.equals(keys[pos], EMPTY_KEY_VALUE)){ - nextIndex = pos; - break; - } - } - } - } - return nextIndex != Integer.MIN_VALUE; - } - - public int nextEntry() { - if(!hasNext()) throw new NoSuchElementException(); - returnedPos = pos; - if(nextIndex < 0){ - lastReturned = Integer.MAX_VALUE; - int value = findIndex(wrapped[nextIndex]); - if(value < 0) throw new IllegalStateException("Entry ["+nextIndex+"] was removed during Iteration"); - nextIndex = Integer.MIN_VALUE; - return value; - } - int value = (lastReturned = nextIndex); - nextIndex = Integer.MIN_VALUE; - return value; - } - - public void remove() { - if(lastReturned == -1) throw new IllegalStateException(); - if(lastReturned == nullIndex) { - containsNull = false; - keys[nullIndex] = EMPTY_KEY_VALUE; - values[nullIndex] = EMPTY_VALUE; - } - else if(returnedPos >= 0) shiftKeys(returnedPos); - else { - CUSTOM_HASH_MAP.this.remove(wrapped[-returnedPos - 1]); - lastReturned = -1; - return; - } - size--; - lastReturned = -1; - } - - private void shiftKeys(int startPos) { - int slot, last; - KEY_TYPE current; - while(true) { - startPos = ((last = startPos) + 1) & mask; - while(true){ - if(strategy.equals((current = keys[startPos]), EMPTY_KEY_VALUE)) { - keys[last] = EMPTY_KEY_VALUE; - values[last] = EMPTY_VALUE; - return; - } - slot = HashUtil.mix(strategy.hashCode(current)) & mask; - if(last <= startPos ? (last >= slot || slot > startPos) : (last >= slot && slot > startPos)) break; - startPos = ++startPos & mask; - } - if(startPos < last) addWrapper(keys[startPos]); - keys[last] = current; - values[last] = values[startPos]; - } - } - - private void addWrapper(KEY_TYPE value) { - if(wrapped == null) wrapped = NEW_KEY_ARRAY(2); - else if(wrappedIndex >= wrapped.length) { - KEY_TYPE[] newArray = NEW_KEY_ARRAY(wrapped.length * 2); - System.arraycopy(wrapped, 0, newArray, 0, wrapped.length); - wrapped = newArray; - } - wrapped[wrappedIndex++] = value; - } - } +package speiger.src.collections.PACKAGE.maps.impl.customHash; + +import java.util.Arrays; +import java.util.ConcurrentModificationException; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Objects; +import java.util.function.Consumer; +import java.util.function.BiFunction; +import java.util.function.Predicate; +#if !TYPE_OBJECT && JDK_TYPE +import java.util.function.PREDICATE; +#endif +#if !SAME_TYPE && JDK_VALUE && !VALUE_OBJECT +import java.util.function.VALUE_PREDICATE; +#endif + +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.collections.ITERATOR; +import speiger.src.collections.PACKAGE.functions.CONSUMER; +import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; +#endif +import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER; +#if !TYPE_OBJECT && !VALUE_OBJECT +import speiger.src.collections.ints.functions.consumer.IntObjectConsumer; +#endif +#if !SAME_TYPE && !TYPE_INT +import speiger.src.collections.ints.functions.consumer.VALUE_BI_FROM_INT_CONSUMER; +#endif +#if !TYPE_INT || !SAME_TYPE +import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; +#endif +#if !VALUE_BOOLEAN || !JDK_TYPE +import speiger.src.collections.PACKAGE.functions.function.FUNCTION; +#endif +import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; +#if !SAME_TYPE +import speiger.src.collections.PACKAGE.functions.function.SINGLE_UNARY_OPERATOR; +#endif +#if !TYPE_OBJECT && !VALUE_BOOLEAN && !JDK_TYPE +import speiger.src.collections.PACKAGE.functions.function.PREDICATE; +#endif +import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET; +import speiger.src.collections.PACKAGE.sets.SET; +#endif +import speiger.src.collections.PACKAGE.utils.STRATEGY; +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; +import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_SUPPLIER; +#if !SAME_TYPE +import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR; + +#if !VALUE_OBJECT +#if !TYPE_OBJECT +import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator; +#endif + +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; +import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER; +#endif +#else if !VALUE_OBJECT +import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator; + +#endif +#if !TYPE_OBJECT && !VALUE_OBJECT || !VALUE_OBJECT +import speiger.src.collections.objects.functions.consumer.ObjectObjectConsumer; +#endif +#if !SAME_TYPE +#if !TYPE_OBJECT +import speiger.src.collections.objects.functions.consumer.VALUE_BI_FROM_OBJECT_CONSUMER; + +#endif +#if !JDK_VALUE +import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE; +#endif +#endif +import speiger.src.collections.objects.collections.ObjectIterator; +import speiger.src.collections.objects.sets.AbstractObjectSet; +import speiger.src.collections.objects.sets.ObjectSet; +import speiger.src.collections.utils.HashUtil; +import speiger.src.collections.utils.ITrimmable; + +/** + * A Type Specific HashMap that allows for custom HashControl. + * For cases where Objects/primitive do not allow hashcoding this can be really useful and provide a lot of control. + * @Type(T) + * @ValueType(V) + */ +public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements ITrimmable +{ + /** The Backing keys array */ + protected transient KEY_TYPE[] keys; + /** The Backing values array */ + protected transient VALUE_TYPE[] values; + /** If a null value is present */ + protected transient boolean containsNull; + /** Minimum array size the HashMap will be */ + protected transient int minCapacity; + /** Index of the Null Value */ + protected transient int nullIndex; + /** Maximum amount of Values that can be stored before the array gets expanded usually 75% */ + protected transient int maxFill; + /** Max Index that is allowed to be searched through nullIndex - 1 */ + protected transient int mask; + /** EntrySet cache */ + protected transient FastEntrySet KEY_VALUE_GENERIC_TYPE entrySet; + /** KeySet cache */ + protected transient SET KEY_GENERIC_TYPE keySet; + /** Values cache */ + protected transient VALUE_COLLECTION VALUE_GENERIC_TYPE valuesC; + + /** Amount of Elements stored in the HashMap */ + protected int size; + /** How full the Arrays are allowed to get before resize */ + protected final float loadFactor; + /** Strategy that allows to control the Hash Generation and equals comparason */ + protected final STRATEGY KEY_SUPER_GENERIC_TYPE strategy; + + /** + * Default Contstructor + * @param strategy the strategy that allows hash control. + * @throws NullPointerException if Strategy is null + */ + public CUSTOM_HASH_MAP(STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { + this(HashUtil.DEFAULT_MIN_CAPACITY, HashUtil.DEFAULT_LOAD_FACTOR, strategy); + } + + /** + * Constructor that defines the minimum capacity + * @param minCapacity the minimum capacity the HashMap is allowed to be. + * @param strategy the strategy that allows hash control. + * @throws NullPointerException if Strategy is null + * @throws IllegalStateException if the minimum capacity is negative + */ + public CUSTOM_HASH_MAP(int minCapacity, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { + this(minCapacity, HashUtil.DEFAULT_LOAD_FACTOR, strategy); + } + + /** + * Constructor that defines the minimum capacity and load factor + * @param minCapacity the minimum capacity the HashMap is allowed to be. + * @param loadFactor the percentage of how full the backing array can be before they resize + * @param strategy the strategy that allows hash control. + * @throws NullPointerException if Strategy is null + * @throws IllegalStateException if the minimum capacity is negative + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + */ + public CUSTOM_HASH_MAP(int minCapacity, float loadFactor, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { + if(minCapacity < 0) throw new IllegalStateException("Minimum Capacity is negative. This is not allowed"); + if(loadFactor <= 0 || loadFactor >= 1F) throw new IllegalStateException("Load Factor is not between 0 and 1"); + this.loadFactor = loadFactor; + this.minCapacity = nullIndex = HashUtil.arraySize(minCapacity, loadFactor); + this.strategy = strategy; + mask = nullIndex - 1; + maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1); + keys = NEW_KEY_ARRAY(nullIndex + 1); + values = NEW_VALUE_ARRAY(nullIndex + 1); + } + +#if !TYPE_OBJECT || !VALUE_OBJECT + /** + * Helper constructor that allow to create a map from boxed values (it will unbox them) + * @param keys the keys that should be put into the map + * @param values the values that should be put into the map. + * @param strategy the strategy that allows hash control. + * @throws NullPointerException if Strategy is null + * @throws IllegalStateException if the keys and values do not match in lenght + */ + public CUSTOM_HASH_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { + this(keys, values, HashUtil.DEFAULT_LOAD_FACTOR, strategy); + } + + /** + * Helper constructor that allow to create a map from boxed values (it will unbox them) + * @param keys the keys that should be put into the map + * @param values the values that should be put into the map. + * @param loadFactor the percentage of how full the backing array can be before they resize + * @param strategy the strategy that allows hash control. + * @throws NullPointerException if Strategy is null + * @throws IllegalStateException if the keys and values do not match in lenght + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + */ + public CUSTOM_HASH_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, float loadFactor, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { + this(keys.length, loadFactor, strategy); + if(keys.length != values.length) throw new IllegalStateException("Input Arrays are not equal size"); + for(int i = 0,m=keys.length;i map, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { + this(map, HashUtil.DEFAULT_LOAD_FACTOR, strategy); + } + + /** + * A Helper constructor that allows to create a Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + * @param loadFactor the percentage of how full the backing array can be before they resize + * @param strategy the strategy that allows hash control. + * @throws NullPointerException if Strategy is null + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + */ + public CUSTOM_HASH_MAP(Map map, float loadFactor, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { + this(map.size(), loadFactor, strategy); + putAll(map); + } + + /** + * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + * @param strategy the strategy that allows hash control. + * @throws NullPointerException if Strategy is null + */ + public CUSTOM_HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { + this(map, HashUtil.DEFAULT_LOAD_FACTOR, strategy); + } + + /** + * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + * @param loadFactor the percentage of how full the backing array can be before they resize + * @param strategy the strategy that allows hash control. + * @throws NullPointerException if Strategy is null + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + */ + public CUSTOM_HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map, float loadFactor, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { + this(map.size(), loadFactor, strategy); + putAll(map); + } + + @Override + public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { + int slot = findIndex(key); + if(slot < 0) { + insert(-slot-1, key, value); + return getDefaultReturnValue(); + } + VALUE_TYPE oldValue = values[slot]; + values[slot] = value; + return oldValue; + } + + @Override + public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { + int slot = findIndex(key); + if(slot < 0) { + insert(-slot-1, key, value); + return getDefaultReturnValue(); + } + else if(VALUE_EQUALS(values[slot], getDefaultReturnValue())) { + VALUE_TYPE oldValue = values[slot]; + values[slot] = value; + return oldValue; + } + return values[slot]; + } + +#if VALUE_PRIMITIVES + @Override + public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { + int slot = findIndex(key); + if(slot < 0) { + insert(-slot-1, key, value); + return getDefaultReturnValue(); + } + VALUE_TYPE oldValue = values[slot]; + values[slot] += value; + return oldValue; + } + + @Override + public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { + int slot = findIndex(key); + if(slot < 0) return getDefaultReturnValue(); + VALUE_TYPE oldValue = values[slot]; + values[slot] -= value; + if(value < 0 ? (values[slot] >= getDefaultReturnValue()) : (values[slot] <= getDefaultReturnValue())) removeIndex(slot); + return oldValue; + } +#endif +#if !TYPE_OBJECT + @Override + public boolean containsKey(KEY_TYPE key) { + return findIndex(key) >= 0; + } + +#endif + @Override + @Primitive + public boolean containsKey(Object key) { +#if !TYPE_OBJECT + return key instanceof CLASS_TYPE && findIndex(CLASS_TO_KEY(key)) >= 0; +#else + return findIndex(CLASS_TO_KEY(key)) >= 0; +#endif + } + +#if !VALUE_OBJECT + @Override + public boolean containsValue(VALUE_TYPE value) { + if(containsNull && VALUE_EQUALS(values[nullIndex], value)) return true; + for(int i = nullIndex;i >= 0;i--) + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && VALUE_EQUALS(values[i], value)) return true; + return false; + } + +#endif + @Override + @ValuePrimitive + public boolean containsValue(Object value) { +#if VALUE_OBJECT + if(containsNull && VALUE_EQUALS(values[nullIndex], value)) return true; +#else + if(containsNull && ((value == null && values[nullIndex] == getDefaultReturnValue()) || EQUALS_VALUE_TYPE(values[nullIndex], value))) return true; +#endif + for(int i = nullIndex-1;i >= 0;i--) +#if VALUE_OBJECT + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && EQUALS_VALUE_TYPE(values[i], value)) return true; +#else + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && ((value == null && values[i] == getDefaultReturnValue()) || EQUALS_VALUE_TYPE(values[i], value))) return true; +#endif + return false; + } + + @Override + public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { + int slot = findIndex(key); + if(slot < 0) return getDefaultReturnValue(); + return removeIndex(slot); + } + + @Override + public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { + int slot = findIndex(key); + if(slot < 0) return defaultValue; + return removeIndex(slot); + } + + @Override + public CLASS_VALUE_TYPE remove(Object key) { +#if !TYPE_OBJECT + if(!(key instanceof CLASS_TYPE)) return getDefaultReturnValue(); +#endif + int slot = findIndex(CLASS_TO_KEY(key)); + if(slot < 0) return VALUE_TO_OBJ(getDefaultReturnValue()); + return removeIndex(slot); + } + +#if !TYPE_OBJECT || !VALUE_OBJECT + @Override + public boolean remove(KEY_TYPE key, VALUE_TYPE value) { + if(strategy.equals(key, EMPTY_KEY_VALUE)) { + if(containsNull && VALUE_EQUALS(value, values[nullIndex])) { + removeNullIndex(); + return true; + } + return false; + } + int pos = HashUtil.mix(strategy.hashCode(key)) & mask; + KEY_TYPE current = keys[pos]; + if(strategy.equals(current, EMPTY_KEY_VALUE)) return false; + if(strategy.equals(current, key) && VALUE_EQUALS(value, values[pos])) { + removeIndex(pos); + return true; + } + while(true) { + if(strategy.equals((current = keys[pos = (++pos & mask)]), EMPTY_KEY_VALUE)) return false; + else if(strategy.equals(current, key) && VALUE_EQUALS(value, values[pos])) { + removeIndex(pos); + return true; + } + } + } + +#endif + @Override + public boolean remove(Object key, Object value) { + Objects.requireNonNull(value); +#if TYPE_OBJECT + if(key == null) { +#else + if(key == null || (key instanceof CLASS_TYPE && strategy.equals(CLASS_TO_KEY(key), EMPTY_KEY_VALUE))) { +#endif + if(containsNull && EQUALS_VALUE_TYPE(values[nullIndex], value)) { + removeNullIndex(); + return true; + } + return false; + } +#if !TYPE_OBJECT + if(!(key instanceof CLASS_TYPE)) return false; +#endif + KEY_TYPE keyType = CLASS_TO_KEY(key); + int pos = HashUtil.mix(strategy.hashCode(keyType)) & mask; + KEY_TYPE current = keys[pos]; + if(strategy.equals(current, EMPTY_KEY_VALUE)) return false; + if(strategy.equals(current, keyType) && EQUALS_VALUE_TYPE(values[pos], value)) { + removeIndex(pos); + return true; + } + while(true) { + if(strategy.equals((current = keys[pos = (++pos & mask)]), EMPTY_KEY_VALUE)) return false; + else if(strategy.equals(current, keyType) && EQUALS_VALUE_TYPE(values[pos], value)){ + removeIndex(pos); + return true; + } + } + } + + @Override + public VALUE_TYPE GET_VALUE(KEY_TYPE key) { + int slot = findIndex(key); + return slot < 0 ? getDefaultReturnValue() : values[slot]; + } + + @Override + public CLASS_VALUE_TYPE get(Object key) { +#if !TYPE_OBJECT + if(!(key instanceof CLASS_TYPE)) return getDefaultReturnValue(); +#endif + int slot = findIndex(CLASS_TO_KEY(key)); + return VALUE_TO_OBJ(slot < 0 ? getDefaultReturnValue() : values[slot]); + } + +#if TYPE_OBJECT && VALUE_OBJECT + @Override + public VALUE_TYPE getOrDefault(Object key, VALUE_TYPE defaultValue) { + int slot = findIndex(CLASS_TO_KEY(key)); + return slot < 0 ? defaultValue : values[slot]; + } + +#else + @Override + public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { + int slot = findIndex(key); + return slot < 0 ? defaultValue : values[slot]; + } + +#endif + @Override + public CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE copy() { + CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE map = new CUSTOM_HASH_MAPKV_BRACES(0, loadFactor, strategy); + map.minCapacity = minCapacity; + map.mask = mask; + map.maxFill = maxFill; + map.nullIndex = nullIndex; + map.containsNull = containsNull; + map.size = size; + map.keys = Arrays.copyOf(keys, keys.length); + map.values = Arrays.copyOf(values, values.length); + return map; + } + + @Override + public ObjectSet ENTRY_SET() { + if(entrySet == null) entrySet = new MapEntrySet(); + return entrySet; + } + + @Override + public SET KEY_GENERIC_TYPE keySet() { + if(keySet == null) keySet = new KeySet(); + return keySet; + } + + @Override + public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { + if(valuesC == null) valuesC = new Values(); + return valuesC; + } + + @Override + public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { + if(size() <= 0) return; + if(containsNull) action.accept(keys[nullIndex], values[nullIndex]); + for(int i = nullIndex-1;i>=0;i--) { + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(keys[i], values[i]); + } + } + + @Override + public boolean replace(KEY_TYPE key, VALUE_TYPE oldValue, VALUE_TYPE newValue) { + int index = findIndex(key); + if(index < 0 || values[index] != oldValue) return false; + values[index] = newValue; + return true; + } + + @Override + public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value) { + int index = findIndex(key); + if(index < 0) return getDefaultReturnValue(); + VALUE_TYPE oldValue = values[index]; + values[index] = value; + return oldValue; + } + + @Override + public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); + int index = findIndex(key); + if(index < 0) { + VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, getDefaultReturnValue()); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + insert(-index-1, key, newValue); + return newValue; + } + VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, values[index]); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + removeIndex(index); + return newValue; + } + values[index] = newValue; + return newValue; + } + + @Override + public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); + int index = findIndex(key); + if(index < 0) { + VALUE_TYPE newValue = mappingFunction.APPLY(key); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + insert(-index-1, key, newValue); + return newValue; + } + VALUE_TYPE newValue = values[index]; + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + newValue = mappingFunction.APPLY(key); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + values[index] = newValue; + } + return newValue; + } + + @Override + public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) { + Objects.requireNonNull(valueProvider); + int index = findIndex(key); + if(index < 0) { + VALUE_TYPE newValue = valueProvider.VALUE_SUPPLY_GET(); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + insert(-index-1, key, newValue); + return newValue; + } + VALUE_TYPE newValue = values[index]; + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + newValue = valueProvider.VALUE_SUPPLY_GET(); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + values[index] = newValue; + } + return newValue; + } + + @Override + public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); + int index = findIndex(key); + if(index < 0 || VALUE_EQUALS(values[index], getDefaultReturnValue())) return getDefaultReturnValue(); + VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, values[index]); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + removeIndex(index); + return newValue; + } + values[index] = newValue; + return newValue; + } + + @Override + public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); +#if VALUE_OBJECT + Objects.requireNonNull(value); +#endif + int index = findIndex(key); + VALUE_TYPE newValue = index < 0 || VALUE_EQUALS(values[index], getDefaultReturnValue()) ? value : mappingFunction.APPLY_VALUE(values[index], value); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + if(index >= 0) + removeIndex(index); + } + else if(index < 0) insert(-index-1, key, newValue); + else values[index] = newValue; + return newValue; + } + + @Override + public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); + for(MAP.Entry KEY_VALUE_GENERIC_TYPE entry : getFastIterable(m)) { + KEY_TYPE key = entry.ENTRY_KEY(); + int index = findIndex(key); + VALUE_TYPE newValue = index < 0 || VALUE_EQUALS(values[index], getDefaultReturnValue()) ? entry.ENTRY_VALUE() : mappingFunction.APPLY_VALUE(values[index], entry.ENTRY_VALUE()); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + if(index >= 0) + removeIndex(index); + } + else if(index < 0) insert(-index-1, key, newValue); + else values[index] = newValue; + } + } + + @Override + public int size() { return size; } + + @Override + public void clear() { + if(size == 0) return; + size = 0; + containsNull = false; + Arrays.fill(keys, EMPTY_KEY_VALUE); + Arrays.fill(values, EMPTY_VALUE); + } + + @Override + public boolean trim(int size) { + int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor))); + if(request >= nullIndex || this.size > Math.min((int)Math.ceil(request * loadFactor), request - 1)) return false; + try { + rehash(request); + } + catch(OutOfMemoryError noMemory) { return false; } + return true; + } + + @Override + public void clearAndTrim(int size) { + int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor))); + if(request >= nullIndex) { + clear(); + return; + } + nullIndex = request; + mask = request-1; + maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1); + keys = NEW_KEY_ARRAY(request + 1); + values = NEW_VALUE_ARRAY(request + 1); + this.size = 0; + containsNull = false; + } + +#if !TYPE_OBJECT + protected int findIndex(KEY_TYPE key) { + if(strategy.equals(key, EMPTY_KEY_VALUE)) return containsNull ? nullIndex : -(nullIndex + 1); + int pos = HashUtil.mix(strategy.hashCode(key)) & mask; + KEY_TYPE current = keys[pos]; + if(!strategy.equals(current, EMPTY_KEY_VALUE)) { + if(strategy.equals(current, key)) return pos; + while(!strategy.equals((current = keys[pos = (++pos & mask)]), EMPTY_KEY_VALUE)) + if(strategy.equals(current, key)) return pos; + } + return -(pos + 1); + } + +#endif + protected int findIndex(CLASS_TYPE key) { + if(key == null) return containsNull ? nullIndex : -(nullIndex + 1); + KEY_TYPE keyType = CLASS_TO_KEY(key); +#if !TYPE_OBJECT + if(strategy.equals(keyType, EMPTY_KEY_VALUE)) return containsNull ? nullIndex : -(nullIndex + 1); +#endif + int pos = HashUtil.mix(strategy.hashCode(keyType)) & mask; + KEY_TYPE current = keys[pos]; + if(!strategy.equals(current, EMPTY_KEY_VALUE)) { + if(strategy.equals(current, keyType)) return pos; + while(!strategy.equals((current = keys[pos = (++pos & mask)]), EMPTY_KEY_VALUE)) + if(strategy.equals(current, keyType)) return pos; + } + return -(pos + 1); + } + + protected VALUE_TYPE removeIndex(int pos) { + if(pos == nullIndex) return containsNull ? removeNullIndex() : getDefaultReturnValue(); + VALUE_TYPE value = values[pos]; + keys[pos] = EMPTY_KEY_VALUE; + values[pos] = EMPTY_VALUE; + size--; + onNodeRemoved(pos); + shiftKeys(pos); + if(nullIndex > minCapacity && size < maxFill / 4 && nullIndex > HashUtil.DEFAULT_MIN_CAPACITY) rehash(nullIndex / 2); + return value; + } + + protected VALUE_TYPE removeNullIndex() { + VALUE_TYPE value = values[nullIndex]; + containsNull = false; + keys[nullIndex] = EMPTY_KEY_VALUE; + values[nullIndex] = EMPTY_VALUE; + size--; + onNodeRemoved(nullIndex); + if(nullIndex > minCapacity && size < maxFill / 4 && nullIndex > HashUtil.DEFAULT_MIN_CAPACITY) rehash(nullIndex / 2); + return value; + } + + protected void insert(int slot, KEY_TYPE key, VALUE_TYPE value) { + if(slot == nullIndex) containsNull = true; + keys[slot] = key; + values[slot] = value; + onNodeAdded(slot); + if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor)); + } + + protected void rehash(int newSize) { + int newMask = newSize - 1; + KEY_TYPE[] newKeys = NEW_KEY_ARRAY(newSize + 1); + VALUE_TYPE[] newValues = NEW_VALUE_ARRAY(newSize + 1); + for(int i = nullIndex, pos = 0, j = (size - (containsNull ? 1 : 0));j-- != 0;) { + while(true) { + if(--i < 0) throw new ConcurrentModificationException("Map was modified during rehash"); + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) break; + } + if(!strategy.equals(newKeys[pos = HashUtil.mix(strategy.hashCode(keys[i])) & newMask], EMPTY_KEY_VALUE)) + while(!strategy.equals(newKeys[pos = (++pos & newMask)], EMPTY_KEY_VALUE)); + newKeys[pos] = keys[i]; + newValues[pos] = values[i]; + } + newValues[newSize] = values[nullIndex]; + nullIndex = newSize; + mask = newMask; + maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1); + keys = newKeys; + values = newValues; + } + + protected void onNodeAdded(int pos) { + + } + + protected void onNodeRemoved(int pos) { + + } + + protected void onNodeMoved(int from, int to) { + + } + + protected void shiftKeys(int startPos) { + int slot, last; + KEY_TYPE current; + while(true) { + startPos = ((last = startPos) + 1) & mask; + while(true){ + if(strategy.equals((current = keys[startPos]), EMPTY_KEY_VALUE)) { + keys[last] = EMPTY_KEY_VALUE; + values[last] = EMPTY_VALUE; + return; + } + slot = HashUtil.mix(strategy.hashCode(current)) & mask; + if(last <= startPos ? (last >= slot || slot > startPos) : (last >= slot && slot > startPos)) break; + startPos = ++startPos & mask; + } + keys[last] = current; + values[last] = values[startPos]; + onNodeMoved(startPos, last); + } + } + + protected class MapEntry implements MAP.Entry KEY_VALUE_GENERIC_TYPE, Map.Entry { + public int index = -1; + + public MapEntry() {} + public MapEntry(int index) { + this.index = index; + } + + @Override + public KEY_TYPE ENTRY_KEY() { + return keys[index]; + } + + @Override + public VALUE_TYPE ENTRY_VALUE() { + return values[index]; + } + + @Override + public VALUE_TYPE setValue(VALUE_TYPE value) { + VALUE_TYPE oldValue = values[index]; + values[index] = value; + return oldValue; + } + + @Override + public boolean equals(Object obj) { + if(obj instanceof Map.Entry) { + if(obj instanceof MAP.Entry) { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)obj; + return KEY_EQUALS(keys[index], entry.ENTRY_KEY()) && VALUE_EQUALS(values[index], entry.ENTRY_VALUE()); + } + Map.Entry entry = (Map.Entry)obj; + Object key = entry.getKey(); + Object value = entry.getValue(); +#if TYPE_OBJECT && VALUE_OBJECT + return KEY_EQUALS(keys[index], key) && VALUE_EQUALS(values[index], value); +#else if TYPE_OBJECT + return value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(keys[index], key) && VALUE_EQUALS(values[index], CLASS_TO_VALUE(value)); +#else if VALUE_OBJECT + return key instanceof CLASS_TYPE && KEY_EQUALS(keys[index], CLASS_TO_KEY(key)) && VALUE_EQUALS(values[index], value); +#else + return key instanceof CLASS_TYPE && value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(keys[index], CLASS_TO_KEY(key)) && VALUE_EQUALS(values[index], CLASS_TO_VALUE(value)); +#endif + } + return false; + } + + @Override + public int hashCode() { + return strategy.hashCode(keys[index]) ^ VALUE_TO_HASH(values[index]); + } + + @Override + public String toString() { + return KEY_TO_STRING(keys[index]) + "=" + VALUE_TO_STRING(values[index]); + } + } + + private final class MapEntrySet extends AbstractObjectSet implements MAP.FastEntrySet KEY_VALUE_GENERIC_TYPE { + @Override + public ObjectIterator fastIterator() { + return new FastEntryIterator(); + } + + @Override + public ObjectIterator iterator() { + return new EntryIterator(); + } + + @Override + public void forEach(Consumer action) { + if(containsNull) action.accept(new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex])); + for(int i = nullIndex-1;i>=0;i--) + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(new BasicEntryKV_BRACES(keys[i], values[i])); + } + + @Override + public void fastForEach(Consumer action) { + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + if(containsNull) { + entry.set(keys[nullIndex], values[nullIndex]); + action.accept(entry); + } + for(int i = nullIndex-1;i>=0;i--) { + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) { + entry.set(keys[i], values[i]); + action.accept(entry); + } + } + } + + @Override + public void forEachIndexed(IntObjectConsumer action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + if(containsNull) action.accept(0, new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex])); + for(int i = nullIndex-1, index = containsNull ? 1 : 0;i>=0;i--) { + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(index++, new BasicEntryKV_BRACES(keys[i], values[i])); + } + } + + @Override + public void forEach(E input, ObjectObjectConsumer action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + if(containsNull) action.accept(input, new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex])); + for(int i = nullIndex-1;i>=0;i--) { + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(input, new BasicEntryKV_BRACES(keys[i], values[i])); + } + } + + @Override + public boolean matchesAny(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return false; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + if(containsNull) { + entry.set(keys[nullIndex], values[nullIndex]); + if(filter.test(entry)) return true; + } + for(int i = nullIndex-1;i>=0;i--) { + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) { + entry.set(keys[i], values[i]); + if(filter.test(entry)) return true; + } + } + return false; + } + + @Override + public boolean matchesNone(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + if(containsNull) { + entry.set(keys[nullIndex], values[nullIndex]); + if(filter.test(entry)) return false; + } + for(int i = nullIndex-1;i>=0;i--) { + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) { + entry.set(keys[i], values[i]); + if(filter.test(entry)) return false; + } + } + return true; + } + + @Override + public boolean matchesAll(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + if(containsNull) { + entry.set(keys[nullIndex], values[nullIndex]); + if(!filter.test(entry)) return false; + } + for(int i = nullIndex-1;i>=0;i--) { + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) { + entry.set(keys[i], values[i]); + if(!filter.test(entry)) return false; + } + } + return true; + } + + @Override + public E reduce(E identity, BiFunction operator) { + Objects.requireNonNull(operator); + E state = identity; + if(containsNull) state = operator.apply(state, new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex])); + for(int i = nullIndex-1;i>=0;i--) { + if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue; + state = operator.apply(state, new BasicEntryKV_BRACES(keys[i], values[i])); + } + return state; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE reduce(ObjectObjectUnaryOperator operator) { + Objects.requireNonNull(operator); + MAP.Entry KEY_VALUE_GENERIC_TYPE state = null; + boolean empty = true; + if(containsNull) { + state = new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex]); + empty = false; + } + for(int i = nullIndex-1;i>=0;i--) { + if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue; + if(empty) { + empty = false; + state = new BasicEntryKV_BRACES(keys[i], values[i]); + continue; + } + state = operator.apply(state, new BasicEntryKV_BRACES(keys[i], values[i])); + } + return state; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE findFirst(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return null; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + if(containsNull) { + entry.set(keys[nullIndex], values[nullIndex]); + if(filter.test(entry)) return entry; + } + for(int i = nullIndex-1;i>=0;i--) { + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) { + entry.set(keys[i], values[i]); + if(filter.test(entry)) return entry; + } + } + return null; + } + + @Override + public int count(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return 0; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + int result = 0; + if(containsNull) { + entry.set(keys[nullIndex], values[nullIndex]); + if(filter.test(entry)) result++; + } + for(int i = nullIndex-1;i>=0;i--) { + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) { + entry.set(keys[i], values[i]); + if(filter.test(entry)) result++; + } + } + return result; + } + + @Override + public int size() { + return CUSTOM_HASH_MAP.this.size(); + } + + @Override + public void clear() { + CUSTOM_HASH_MAP.this.clear(); + } + + @Override + public boolean contains(Object o) { + if(o instanceof Map.Entry) { + if(o instanceof MAP.Entry) { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; + int index = CUSTOM_HASH_MAP.this.findIndex(entry.ENTRY_KEY()); + if(index >= 0) return VALUE_EQUALS(entry.ENTRY_VALUE(), CUSTOM_HASH_MAP.this.values[index]); + } + else { + Map.Entry entry = (Map.Entry)o; +#if !TYPE_OBJECT + if(!(entry.getKey() instanceof CLASS_TYPE)) return false; +#endif + int index = CUSTOM_HASH_MAP.this.findIndex((CLASS_TYPE)entry.getKey()); + if(index >= 0) return Objects.equals(entry.getValue(), VALUE_TO_OBJ(CUSTOM_HASH_MAP.this.values[index])); + } + } + return false; + } + + @Override + public boolean remove(Object o) { + if(o instanceof Map.Entry) { + if(o instanceof MAP.Entry) { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; + return CUSTOM_HASH_MAP.this.remove(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); + } + Map.Entry entry = (Map.Entry)o; + return CUSTOM_HASH_MAP.this.remove(entry.getKey(), entry.getValue()); + } + return false; + } + } + + private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE { +#if TYPE_OBJECT + @Override + public boolean contains(Object e) { + return containsKey(e); + } + + @Override + public boolean remove(Object o) { + int oldSize = size; + CUSTOM_HASH_MAP.this.remove(o); + return size != oldSize; + } + +#else + @Override + public boolean contains(KEY_TYPE e) { + return containsKey(e); + } + + @Override + public boolean remove(KEY_TYPE o) { + int oldSize = size; + CUSTOM_HASH_MAP.this.remove(o); + return size != oldSize; + } + +#endif + @Override + public boolean add(KEY_TYPE o) { + throw new UnsupportedOperationException(); + } + + @Override + public ITERATOR KEY_GENERIC_TYPE iterator() { + return new KeyIterator(); + } + + @Override + public KeySet copy() { throw new UnsupportedOperationException(); } + + @Override + public int size() { + return CUSTOM_HASH_MAP.this.size(); + } + + @Override + public void clear() { + CUSTOM_HASH_MAP.this.clear(); + } + + @Override + public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { + Objects.requireNonNull(action); + if(containsNull) action.accept(keys[nullIndex]); + for(int i = nullIndex-1;i>=0;i--) + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(keys[i]); + } + + @Override + public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + if(containsNull) action.accept(0, keys[nullIndex]); + for(int i = nullIndex-1, index = containsNull ? 1 : 0;i>=0;i--) { + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(index++, keys[i]); + } + } + + @Override + public void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + if(containsNull) action.accept(input, keys[nullIndex]); + for(int i = nullIndex-1;i>=0;i--) { + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(input, keys[i]); + } + } + + @Override + public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return false; + if(containsNull && filter.test(keys[nullIndex])) return true; + for(int i = nullIndex-1;i>=0;i--) { + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.test(keys[i])) return true; + } + return false; + } + + @Override + public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + if(containsNull && filter.test(keys[nullIndex])) return false; + for(int i = nullIndex-1;i>=0;i--) { + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.test(keys[i])) return false; + } + return true; + } + + @Override + public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + if(containsNull && !filter.test(keys[nullIndex])) return false; + for(int i = nullIndex-1;i>=0;i--) { + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && !filter.test(keys[i])) return false; + } + return true; + } + +#if !TYPE_OBJECT + @Override + public KEY_TYPE reduce(KEY_TYPE identity, SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + KEY_TYPE state = identity; + if(containsNull) state = operator.APPLY_KEY_VALUE(state, keys[nullIndex]); + for(int i = nullIndex-1;i>=0;i--) { + if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue; + state = operator.APPLY_KEY_VALUE(state, keys[i]); + } + return state; + } + +#else + @Override + public KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) { + Objects.requireNonNull(operator); + KEY_SPECIAL_TYPE state = identity; + if(containsNull) state = operator.apply(state, keys[nullIndex]); + for(int i = nullIndex-1;i>=0;i--) { + if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue; + state = operator.apply(state, keys[i]); + } + return state; + } + +#endif + @Override + public KEY_TYPE reduce(SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + KEY_TYPE state = EMPTY_KEY_VALUE; + boolean empty = true; + if(containsNull) { + state = keys[nullIndex]; + empty = false; + } + for(int i = nullIndex-1;i>=0;i--) { + if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue; + if(empty) { + empty = false; + state = keys[i]; + continue; + } + state = operator.APPLY_KEY_VALUE(state, keys[i]); + } + return state; + } + + @Override + public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return EMPTY_KEY_VALUE; + if(containsNull && filter.test(keys[nullIndex])) return keys[nullIndex]; + for(int i = nullIndex-1;i>=0;i--) { + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.test(keys[i])) return keys[i]; + } + return EMPTY_KEY_VALUE; + } + + @Override + public int count(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return 0; + int result = 0; + if(containsNull && filter.test(keys[nullIndex])) result++; + for(int i = nullIndex-1;i>=0;i--) { + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.test(keys[i])) result++; + } + return result; + } + } + + private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { +#if VALUE_OBJECT + @Override + public boolean contains(Object e) { + return containsValue(e); + } + +#else + @Override + public boolean contains(VALUE_TYPE e) { + return containsValue(e); + } + +#endif + @Override + public boolean add(VALUE_TYPE o) { + throw new UnsupportedOperationException(); + } + + @Override + public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() { + return new ValueIterator(); + } + + @Override + public int size() { + return CUSTOM_HASH_MAP.this.size(); + } + + @Override + public void clear() { + CUSTOM_HASH_MAP.this.clear(); + } + + @Override + public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) { + if(containsNull) action.accept(values[nullIndex]); + for(int i = nullIndex-1;i>=0;i--) + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(values[i]); + } + + @Override + public void forEachIndexed(VALUE_BI_FROM_INT_CONSUMER VALUE_GENERIC_TYPE action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + if(containsNull) action.accept(0, values[nullIndex]); + for(int i = nullIndex-1, index = containsNull ? 1 : 0;i>=0;i--) { + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(index++, values[i]); + } + } + + @Override + public void forEach(E input, VALUE_BI_FROM_OBJECT_CONSUMER VSV_GENERIC_TYPE action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + if(containsNull) action.accept(input, values[nullIndex]); + for(int i = nullIndex-1;i>=0;i--) { + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(input, values[i]); + } + } + + @Override + public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return false; + if(containsNull && filter.test(values[nullIndex])) return true; + for(int i = nullIndex-1;i>=0;i--) { + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.test(values[i])) return true; + } + return false; + } + + @Override + public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + if(containsNull && filter.test(values[nullIndex])) return false; + for(int i = nullIndex-1;i>=0;i--) { + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.test(values[i])) return false; + } + return true; + } + + @Override + public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + if(containsNull && !filter.test(values[nullIndex])) return false; + for(int i = nullIndex-1;i>=0;i--) { + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && !filter.test(values[i])) return false; + } + return true; + } + +#if !VALUE_OBJECT + @Override + public VALUE_TYPE reduce(VALUE_TYPE identity, VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + VALUE_TYPE state = identity; + if(containsNull) state = operator.APPLY_VALUE(state, values[nullIndex]); + for(int i = nullIndex-1;i>=0;i--) { + if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue; + state = operator.APPLY_VALUE(state, values[i]); + } + return state; + } + +#else + @Override + public VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction operator) { + Objects.requireNonNull(operator); + VALUE_SPECIAL_TYPE state = identity; + if(containsNull) state = operator.APPLY_VALUE(state, values[nullIndex]); + for(int i = nullIndex-1;i>=0;i--) { + if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue; + state = operator.APPLY_VALUE(state, values[i]); + } + return state; + } + +#endif + @Override + public VALUE_TYPE reduce(VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + VALUE_TYPE state = EMPTY_VALUE; + boolean empty = true; + if(containsNull) { + state = values[nullIndex]; + empty = false; + } + for(int i = nullIndex-1;i>=0;i--) { + if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue; + if(empty) { + empty = false; + state = values[i]; + continue; + } + state = operator.APPLY_VALUE(state, values[i]); + } + return state; + } + + @Override + public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return EMPTY_VALUE; + if(containsNull && filter.test(values[nullIndex])) return values[nullIndex]; + for(int i = nullIndex-1;i>=0;i--) { + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.test(values[i])) return values[i]; + } + return EMPTY_VALUE; + } + + @Override + public int count(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return 0; + int result = 0; + if(containsNull && filter.test(values[nullIndex])) result++; + for(int i = nullIndex-1;i>=0;i--) { + if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.test(values[i])) result++; + } + return result; + } + } + + private class FastEntryIterator extends MapIterator implements ObjectIterator { + MapEntry entry = new MapEntry(); + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { + entry.index = nextEntry(); + return entry; + } + } + + private class EntryIterator extends MapIterator implements ObjectIterator { + MapEntry entry; + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { + return entry = new MapEntry(nextEntry()); + } + + @Override + public void remove() { + super.remove(); + entry.index = -1; + } + } + + private class KeyIterator extends MapIterator implements ITERATOR KEY_GENERIC_TYPE { + @Override + public KEY_TYPE NEXT() { + return keys[nextEntry()]; + } + } + + private class ValueIterator extends MapIterator implements VALUE_ITERATOR VALUE_GENERIC_TYPE { + @Override + public VALUE_TYPE VALUE_NEXT() { + return values[nextEntry()]; + } + } + + private class MapIterator { + int pos = nullIndex; + int returnedPos = -1; + int lastReturned = -1; + int nextIndex = Integer.MIN_VALUE; + boolean returnNull = containsNull; + KEY_TYPE[] wrapped = null; + int wrappedIndex = 0; + + public boolean hasNext() { + if(nextIndex == Integer.MIN_VALUE) { + if(returnNull) { + returnNull = false; + nextIndex = nullIndex; + } + else + { + while(true) { + if(--pos < 0) { + if(wrapped == null || wrappedIndex <= -pos - 1) break; + nextIndex = -pos - 1; + break; + } + if(!strategy.equals(keys[pos], EMPTY_KEY_VALUE)){ + nextIndex = pos; + break; + } + } + } + } + return nextIndex != Integer.MIN_VALUE; + } + + public int nextEntry() { + if(!hasNext()) throw new NoSuchElementException(); + returnedPos = pos; + if(nextIndex < 0){ + lastReturned = Integer.MAX_VALUE; + int value = findIndex(wrapped[nextIndex]); + if(value < 0) throw new IllegalStateException("Entry ["+nextIndex+"] was removed during Iteration"); + nextIndex = Integer.MIN_VALUE; + return value; + } + int value = (lastReturned = nextIndex); + nextIndex = Integer.MIN_VALUE; + return value; + } + + public void remove() { + if(lastReturned == -1) throw new IllegalStateException(); + if(lastReturned == nullIndex) { + containsNull = false; + keys[nullIndex] = EMPTY_KEY_VALUE; + values[nullIndex] = EMPTY_VALUE; + } + else if(returnedPos >= 0) shiftKeys(returnedPos); + else { + CUSTOM_HASH_MAP.this.remove(wrapped[-returnedPos - 1]); + lastReturned = -1; + return; + } + size--; + lastReturned = -1; + } + + private void shiftKeys(int startPos) { + int slot, last; + KEY_TYPE current; + while(true) { + startPos = ((last = startPos) + 1) & mask; + while(true){ + if(strategy.equals((current = keys[startPos]), EMPTY_KEY_VALUE)) { + keys[last] = EMPTY_KEY_VALUE; + values[last] = EMPTY_VALUE; + return; + } + slot = HashUtil.mix(strategy.hashCode(current)) & mask; + if(last <= startPos ? (last >= slot || slot > startPos) : (last >= slot && slot > startPos)) break; + startPos = ++startPos & mask; + } + if(startPos < last) addWrapper(keys[startPos]); + keys[last] = current; + values[last] = values[startPos]; + } + } + + private void addWrapper(KEY_TYPE value) { + if(wrapped == null) wrapped = NEW_KEY_ARRAY(2); + else if(wrappedIndex >= wrapped.length) { + KEY_TYPE[] newArray = NEW_KEY_ARRAY(wrapped.length * 2); + System.arraycopy(wrapped, 0, newArray, 0, wrapped.length); + wrapped = newArray; + } + wrapped[wrappedIndex++] = value; + } + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/collections/templates/maps/impl/hash/LinkedOpenHashMap.template b/src/builder/resources/speiger/assets/collections/templates/maps/impl/hash/LinkedOpenHashMap.template index 32a4e4b..48ebf78 100644 --- a/src/builder/resources/speiger/assets/collections/templates/maps/impl/hash/LinkedOpenHashMap.template +++ b/src/builder/resources/speiger/assets/collections/templates/maps/impl/hash/LinkedOpenHashMap.template @@ -1,1511 +1,1513 @@ -package speiger.src.collections.PACKAGE.maps.impl.hash; - -import java.util.Arrays; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Objects; -import java.util.function.Consumer; -import java.util.function.BiFunction; -import java.util.function.Predicate; -#if !TYPE_OBJECT && JDK_TYPE -import java.util.function.PREDICATE; -#endif -#if !SAME_TYPE && JDK_VALUE && !VALUE_OBJECT -import java.util.function.VALUE_PREDICATE; -#endif - -import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.functions.CONSUMER; -import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; -#endif -import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER; -#if !TYPE_OBJECT && !VALUE_OBJECT -import speiger.src.collections.ints.functions.consumer.IntObjectConsumer; -#endif -#if !SAME_TYPE -import speiger.src.collections.ints.functions.consumer.VALUE_BI_FROM_INT_CONSUMER; -#endif -#if !TYPE_OBJECT && !JDK_TYPE -import speiger.src.collections.PACKAGE.functions.function.PREDICATE; -#endif -import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; -import speiger.src.collections.PACKAGE.functions.function.SINGLE_UNARY_OPERATOR; -import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP; -import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET; -import speiger.src.collections.PACKAGE.sets.ORDERED_SET; -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; -#if !SAME_TYPE -import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR; -#endif -#if !VALUE_OBJECT && !SAME_TYPE -import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER; -import speiger.src.collections.VALUE_PACKAGE.lists.VALUE_LIST_ITERATOR; -#endif -#if !TYPE_OBJECT && !VALUE_OBJECT || !VALUE_OBJECT -import speiger.src.collections.objects.functions.consumer.ObjectObjectConsumer; -#endif -#if !SAME_TYPE -#if !TYPE_OBJECT -import speiger.src.collections.objects.functions.consumer.VALUE_BI_FROM_OBJECT_CONSUMER; - -#endif -#if !JDK_VALUE -import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE; -#endif -#endif -#if !TYPE_OBJECT -#if !VALUE_OBJECT -import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator; - -#endif -import speiger.src.collections.objects.collections.ObjectBidirectionalIterator; -import speiger.src.collections.objects.lists.ObjectListIterator; -import speiger.src.collections.objects.sets.AbstractObjectSet; -import speiger.src.collections.objects.sets.ObjectOrderedSet; -#endif -import speiger.src.collections.utils.HashUtil; - -/** - * A Type Specific LinkedHashMap implementation that uses specific arrays to create links between nodes to remove the wrapping of elements - * to greatly reduce memory usage. In Addition adding some helper methods to move around elements. - * This implementation of SortedMap does not support SubMaps of any kind. It implements the interface due to sortability and first/last access - * @Type(T) - * @ValueType(V) - */ -public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_GENERIC_TYPE implements ORDERED_MAP KEY_VALUE_GENERIC_TYPE -{ - /** The Backing array for links between nodes. Left 32 Bits => Previous Entry, Right 32 Bits => Next Entry */ - protected transient long[] links; - /** The First Index in the Map */ - protected int firstIndex = -1; - /** The Last Index in the Map */ - protected int lastIndex = -1; - - /** - * Default Constructor - */ - public LINKED_HASH_MAP() { - this(HashUtil.DEFAULT_MIN_CAPACITY, HashUtil.DEFAULT_LOAD_FACTOR); - } - - /** - * Constructor that defines the minimum capacity - * @param minCapacity the minimum capacity the HashMap is allowed to be. - * @throws IllegalStateException if the minimum capacity is negative - */ - public LINKED_HASH_MAP(int minCapacity) { - this(minCapacity, HashUtil.DEFAULT_LOAD_FACTOR); - } - - /** - * Constructor that defines the minimum capacity and load factor - * @param minCapacity the minimum capacity the HashMap is allowed to be. - * @param loadFactor the percentage of how full the backing array can be before they resize - * @throws IllegalStateException if the minimum capacity is negative - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - */ - public LINKED_HASH_MAP(int minCapacity, float loadFactor) { - super(minCapacity, loadFactor); - links = new long[nullIndex + 1]; - } - -#if !TYPE_OBJECT || !VALUE_OBJECT - /** - * Helper constructor that allow to create a map from boxed values (it will unbox them) - * @param keys the keys that should be put into the map - * @param values the values that should be put into the map. - * @throws IllegalStateException if the keys and values do not match in lenght - */ - public LINKED_HASH_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values) { - this(keys, values, HashUtil.DEFAULT_LOAD_FACTOR); - } - - /** - * Helper constructor that allow to create a map from boxed values (it will unbox them) - * @param keys the keys that should be put into the map - * @param values the values that should be put into the map. - * @param loadFactor the percentage of how full the backing array can be before they resize - * @throws IllegalStateException if the keys and values do not match in lenght - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - */ - public LINKED_HASH_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, float loadFactor) { - this(keys.length, loadFactor); - if(keys.length != values.length) throw new IllegalStateException("Input Arrays are not equal size"); - for(int i = 0,m=keys.length;i map) { - this(map, HashUtil.DEFAULT_LOAD_FACTOR); - } - - /** - * A Helper constructor that allows to create a Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - * @param loadFactor the percentage of how full the backing array can be before they resize - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - */ - public LINKED_HASH_MAP(Map map, float loadFactor) { - this(map.size(), loadFactor); - putAll(map); - } - - /** - * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - */ - public LINKED_HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map) { - this(map, HashUtil.DEFAULT_LOAD_FACTOR); - } - - /** - * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - * @param loadFactor the percentage of how full the backing array can be before they resize - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - */ - public LINKED_HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map, float loadFactor) { - this(map.size(), loadFactor); - putAll(map); - } - - @Override - public VALUE_TYPE putAndMoveToFirst(KEY_TYPE key, VALUE_TYPE value) { - if(KEY_EQUALS_NULL(key)) { - if(containsNull) { - VALUE_TYPE lastValue = values[nullIndex]; - values[nullIndex] = value; - moveToFirstIndex(nullIndex); - return lastValue; - } - values[nullIndex] = value; - containsNull = true; - onNodeAdded(nullIndex); - moveToFirstIndex(nullIndex); - } - else { - int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask; - while(KEY_EQUALS_NOT_NULL(keys[pos])) { - if(KEY_EQUALS(keys[pos], key)) { - VALUE_TYPE lastValue = values[pos]; - values[pos] = value; - moveToFirstIndex(pos); - return lastValue; - } - pos = ++pos & mask; - } - keys[pos] = key; - values[pos] = value; - onNodeAdded(pos); - moveToFirstIndex(pos); - } - if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor)); - return getDefaultReturnValue(); - } - - @Override - public VALUE_TYPE putAndMoveToLast(KEY_TYPE key, VALUE_TYPE value) { - if(KEY_EQUALS_NULL(key)) { - if(containsNull) { - VALUE_TYPE lastValue = values[nullIndex]; - values[nullIndex] = value; - moveToLastIndex(nullIndex); - return lastValue; - } - values[nullIndex] = value; - containsNull = true; - onNodeAdded(nullIndex); - moveToLastIndex(nullIndex); - } - else { - int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask; - while(KEY_EQUALS_NOT_NULL(keys[pos])) { - if(KEY_EQUALS(keys[pos], key)) { - VALUE_TYPE lastValue = values[pos]; - values[pos] = value; - moveToLastIndex(pos); - return lastValue; - } - pos = ++pos & mask; - } - keys[pos] = key; - values[pos] = value; - onNodeAdded(pos); - moveToLastIndex(pos); - } - if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor)); - return getDefaultReturnValue(); - } - - @Override - public boolean moveToFirst(KEY_TYPE key) { - if(isEmpty() || KEY_EQUALS(FIRST_ENTRY_KEY(), key)) return false; - if(KEY_EQUALS_NULL(key)) { - if(containsNull) { - moveToFirstIndex(nullIndex); - return true; - } - } - else { - int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask; - while(KEY_EQUALS_NOT_NULL(keys[pos])) { - if(KEY_EQUALS(keys[pos], key)) { - moveToFirstIndex(pos); - return true; - } - pos = ++pos & mask; - } - } - return false; - } - - @Override - public boolean moveToLast(KEY_TYPE key) { - if(isEmpty() || KEY_EQUALS(LAST_ENTRY_KEY(), key)) return false; - if(KEY_EQUALS_NULL(key)) { - if(containsNull) { - moveToLastIndex(nullIndex); - return true; - } - } - else { - int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask; - while(KEY_EQUALS_NOT_NULL(keys[pos])) { - if(KEY_EQUALS(keys[pos], key)) { - moveToLastIndex(pos); - return true; - } - pos = ++pos & mask; - } - } - return false; - } - - @Override - public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key) { - int index = findIndex(key); - if(index < 0) return getDefaultReturnValue(); - moveToFirstIndex(index); - return values[index]; - } - - @Override - public VALUE_TYPE getAndMoveToLast(KEY_TYPE key) { - int index = findIndex(key); - if(index < 0) return getDefaultReturnValue(); - moveToLastIndex(index); - return values[index]; - } - -#if !VALUE_OBJECT - @Override - public boolean containsValue(VALUE_TYPE value) { - int index = firstIndex; - while(index != -1) { - if(VALUE_EQUALS(values[index], value)) return true; - index = (int)links[index]; - } - return false; - } - -#endif - @Override - @ValuePrimitive - public boolean containsValue(Object value) { - int index = firstIndex; - while(index != -1) { -#if VALUE_OBJECT - if(VALUE_EQUALS(values[index], value)) return true; -#else - if((value == null && values[index] == getDefaultReturnValue()) || EQUALS_VALUE_TYPE(values[index], value)) return true; -#endif - index = (int)links[index]; - } - return false; - } - - @Override - public LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE copy() { - LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE map = new LINKED_HASH_MAPKV_BRACES(0, loadFactor); - map.minCapacity = minCapacity; - map.mask = mask; - map.maxFill = maxFill; - map.nullIndex = nullIndex; - map.containsNull = containsNull; - map.size = size; - map.keys = Arrays.copyOf(keys, keys.length); - map.values = Arrays.copyOf(values, values.length); - map.links = Arrays.copyOf(links, links.length); - map.firstIndex = firstIndex; - map.lastIndex = lastIndex; - return map; - } - - @Override - public KEY_TYPE FIRST_ENTRY_KEY() { - if(size == 0) throw new NoSuchElementException(); - return keys[firstIndex]; - } - - @Override - public KEY_TYPE POLL_FIRST_ENTRY_KEY() { - if(size == 0) throw new NoSuchElementException(); - int pos = firstIndex; - onNodeRemoved(pos); - KEY_TYPE result = keys[pos]; - size--; - if(KEY_EQUALS_NULL(result)) { - containsNull = false; - keys[nullIndex] = EMPTY_KEY_VALUE; - values[nullIndex] = EMPTY_VALUE; - } - else shiftKeys(pos); - if(nullIndex > minCapacity && size < maxFill / 4 && nullIndex > HashUtil.DEFAULT_MIN_CAPACITY) rehash(nullIndex / 2); - return result; - } - - @Override - public KEY_TYPE LAST_ENTRY_KEY() { - if(size == 0) throw new NoSuchElementException(); - return keys[lastIndex]; - } - - @Override - public KEY_TYPE POLL_LAST_ENTRY_KEY() { - if(size == 0) throw new NoSuchElementException(); - int pos = lastIndex; - onNodeRemoved(pos); - KEY_TYPE result = keys[pos]; - size--; - if(KEY_EQUALS_NULL(result)) { - containsNull = false; - keys[nullIndex] = EMPTY_KEY_VALUE; - values[nullIndex] = EMPTY_VALUE; - } - else shiftKeys(pos); - if(nullIndex > minCapacity && size < maxFill / 4 && nullIndex > HashUtil.DEFAULT_MIN_CAPACITY) rehash(nullIndex / 2); - return result; - } - - @Override - public VALUE_TYPE FIRST_ENTRY_VALUE() { - if(size == 0) throw new NoSuchElementException(); - return values[firstIndex]; - } - - @Override - public VALUE_TYPE LAST_ENTRY_VALUE() { - if(size == 0) throw new NoSuchElementException(); - return values[lastIndex]; - } - - @Override - public ObjectOrderedSet ENTRY_SET() { - if(entrySet == null) entrySet = new MapEntrySet(); - return (ObjectOrderedSet)entrySet; - } - - @Override - public ORDERED_SET KEY_GENERIC_TYPE keySet() { - if(keySet == null) keySet = new KeySet(); - return (ORDERED_SET KEY_GENERIC_TYPE)keySet; - } - - @Override - public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { - if(valuesC == null) valuesC = new Values(); - return valuesC; - } - - @Override - public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { - int index = firstIndex; - while(index != -1){ - action.accept(keys[index], values[index]); - index = (int)links[index]; - } - } - - @Override - public void clear() { - super.clear(); - firstIndex = lastIndex = -1; - } - - @Override - public void clearAndTrim(int size) { - int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor))); - if(request >= nullIndex) { - clear(); - return; - } - nullIndex = request; - mask = request-1; - maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1); - keys = NEW_KEY_ARRAY(request + 1); - values = NEW_VALUE_ARRAY(request + 1); - links = new long[request + 1]; - firstIndex = lastIndex = -1; - this.size = 0; - containsNull = false; - } - - protected void moveToFirstIndex(int startPos) { - if(size == 1 || firstIndex == startPos) return; - if(lastIndex == startPos) { - lastIndex = (int)(links[startPos] >>> 32); - links[lastIndex] |= 0xFFFFFFFFL; - } - else { - long link = links[startPos]; - int prev = (int)(link >>> 32); - int next = (int)link; - links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L); - } - links[firstIndex] ^= ((links[firstIndex] ^ ((startPos & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); - links[startPos] = 0xFFFFFFFF00000000L | (firstIndex & 0xFFFFFFFFL); - firstIndex = startPos; - } - - protected void moveToLastIndex(int startPos) { - if(size == 1 || lastIndex == startPos) return; - if(firstIndex == startPos) { - firstIndex = (int)links[startPos]; - links[lastIndex] |= 0xFFFFFFFF00000000L; - } - else { - long link = links[startPos]; - int prev = (int)(link >>> 32); - int next = (int)link; - links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L); - } - links[lastIndex] ^= ((links[lastIndex] ^ (startPos & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - links[startPos] = ((lastIndex & 0xFFFFFFFFL) << 32) | 0xFFFFFFFFL; - lastIndex = startPos; - } - - @Override - protected void onNodeAdded(int pos) { - if(size == 0) { - firstIndex = lastIndex = pos; - links[pos] = -1L; - } - else { - links[lastIndex] ^= ((links[lastIndex] ^ (pos & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - links[pos] = ((lastIndex & 0xFFFFFFFFL) << 32) | 0xFFFFFFFFL; - lastIndex = pos; - } - } - - @Override - protected void onNodeRemoved(int pos) { - if(size == 0) firstIndex = lastIndex = -1; - else if(firstIndex == pos) { - firstIndex = (int)links[pos]; - if(0 <= firstIndex) links[firstIndex] |= 0xFFFFFFFF00000000L; - } - else if(lastIndex == pos) { - lastIndex = (int)(links[pos] >>> 32); - if(0 <= lastIndex) links[lastIndex] |= 0xFFFFFFFFL; - } - else { - long link = links[pos]; - int prev = (int)(link >>> 32); - int next = (int)link; - links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L); - } - } - - @Override - protected void onNodeMoved(int from, int to) { - if(size == 1) { - firstIndex = lastIndex = to; - links[to] = -1L; - } - else if(firstIndex == from) { - firstIndex = to; - links[(int)links[from]] ^= ((links[(int)links[from]] ^ ((to & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); - links[to] = links[from]; - } - else if(lastIndex == from) { - lastIndex = to; - links[(int)(links[from] >>> 32)] ^= ((links[(int)(links[from] >>> 32)] ^ (to & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - links[to] = links[from]; - } - else { - long link = links[from]; - int prev = (int)(link >>> 32); - int next = (int)link; - links[prev] ^= ((links[prev] ^ (to & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - links[next] ^= ((links[next] ^ ((to & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); - links[to] = link; - } - } - - @Override - protected void rehash(int newSize) { - int newMask = newSize - 1; - KEY_TYPE[] newKeys = NEW_KEY_ARRAY(newSize + 1); - VALUE_TYPE[] newValues = NEW_VALUE_ARRAY(newSize + 1); - long[] newLinks = new long[newSize + 1]; - int i = firstIndex, prev = -1, newPrev = -1, pos; - firstIndex = -1; - for(int j = size; j-- != 0;) { - if(KEY_EQUALS_NULL(keys[i])) pos = newSize; - else { - pos = HashUtil.mix(KEY_TO_HASH(keys[i])) & newMask; - while(KEY_EQUALS_NOT_NULL(newKeys[pos])) pos = ++pos & newMask; - } - newKeys[pos] = keys[i]; - newValues[pos] = values[i]; - if(prev != -1) { - newLinks[newPrev] ^= ((newLinks[newPrev] ^ (pos & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - newLinks[pos] ^= ((newLinks[pos] ^ ((newPrev & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); - newPrev = pos; - } - else { - newPrev = firstIndex = pos; - newLinks[pos] = -1L; - } - i = (int)links[prev = i]; - } - links = newLinks; - lastIndex = newPrev; - if(newPrev != -1) newLinks[newPrev] |= 0xFFFFFFFFL; - nullIndex = newSize; - mask = newMask; - maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1); - keys = newKeys; - values = newValues; - } - - private class MapEntrySet extends AbstractObjectSet implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE { - @Override - public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } - @Override - public boolean addAndMoveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } - - @Override - public boolean moveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { - return LINKED_HASH_MAP.this.moveToFirst(o.ENTRY_KEY()); - } - - @Override - public boolean moveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { - return LINKED_HASH_MAP.this.moveToLast(o.ENTRY_KEY()); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE first() { - return new BasicEntryKV_BRACES(FIRST_ENTRY_KEY(), FIRST_ENTRY_VALUE()); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE last() { - return new BasicEntryKV_BRACES(LAST_ENTRY_KEY(), LAST_ENTRY_VALUE()); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirst() { - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(FIRST_ENTRY_KEY(), FIRST_ENTRY_VALUE()); - POLL_FIRST_ENTRY_KEY(); - return entry; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLast() { - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(LAST_ENTRY_KEY(), LAST_ENTRY_VALUE()); - POLL_LAST_ENTRY_KEY(); - return entry; - } - - @Override - public ObjectBidirectionalIterator iterator() { - return new EntryIterator(); - } - - @Override - public ObjectBidirectionalIterator iterator(MAP.Entry KEY_VALUE_GENERIC_TYPE fromElement) { - return new EntryIterator(fromElement.ENTRY_KEY()); - } - - @Override - public ObjectBidirectionalIterator fastIterator() { - return new FastEntryIterator(); - } - - @Override - public ObjectBidirectionalIterator fastIterator(KEY_TYPE fromElement) { - return new FastEntryIterator(fromElement); - } - - @Override - public MapEntrySet copy() { throw new UnsupportedOperationException(); } - - @Override - public void forEach(Consumer action) { - int index = firstIndex; - while(index != -1){ - action.accept(new BasicEntryKV_BRACES(keys[index], values[index])); - index = (int)links[index]; - } - } - - @Override - public void fastForEach(Consumer action) { - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - int index = firstIndex; - while(index != -1){ - entry.set(keys[index], values[index]); - action.accept(entry); - index = (int)links[index]; - } - } - - @Override - public void forEachIndexed(IntObjectConsumer action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - int count = 0; - int index = firstIndex; - while(index != -1) { - action.accept(count++, new BasicEntryKV_BRACES(keys[index], values[index])); - index = (int)links[index]; - } - } - - @Override - public void forEach(E input, ObjectObjectConsumer action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - int index = firstIndex; - while(index != -1) { - action.accept(input, new BasicEntryKV_BRACES(keys[index], values[index])); - index = (int)links[index]; - } - } - - @Override - public boolean matchesAny(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return false; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - int index = firstIndex; - while(index != -1) { - entry.set(keys[index], values[index]); - if(filter.test(entry)) return true; - index = (int)links[index]; - } - return false; - } - - @Override - public boolean matchesNone(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - int index = firstIndex; - while(index != -1) { - entry.set(keys[index], values[index]); - if(filter.test(entry)) return false; - index = (int)links[index]; - } - return true; - } - - @Override - public boolean matchesAll(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - int index = firstIndex; - while(index != -1) { - entry.set(keys[index], values[index]); - if(!filter.test(entry)) return false; - index = (int)links[index]; - } - return true; - } - - @Override - public E reduce(E identity, BiFunction operator) { - Objects.requireNonNull(operator); - E state = identity; - int index = firstIndex; - while(index != -1) { - state = operator.apply(state, new BasicEntryKV_BRACES(keys[index], values[index])); - index = (int)links[index]; - } - return state; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE reduce(ObjectObjectUnaryOperator operator) { - Objects.requireNonNull(operator); - MAP.Entry KEY_VALUE_GENERIC_TYPE state = null; - boolean empty = true; - int index = firstIndex; - while(index != -1) { - if(empty) { - empty = false; - state = new BasicEntryKV_BRACES(keys[index], values[index]); - index = (int)links[index]; - continue; - } - state = operator.apply(state, new BasicEntryKV_BRACES(keys[index], values[index])); - index = (int)links[index]; - } - return state; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE findFirst(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return null; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - int index = firstIndex; - while(index != -1) { - entry.set(keys[index], values[index]); - if(filter.test(entry)) return entry; - index = (int)links[index]; - } - return null; - } - - @Override - public int count(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return 0; - int result = 0; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - int index = firstIndex; - while(index != -1) { - entry.set(keys[index], values[index]); - if(filter.test(entry)) result++; - index = (int)links[index]; - } - return result; - } - - @Override - @Deprecated - public boolean contains(Object o) { - if(o instanceof Map.Entry) { - if(o instanceof MAP.Entry) { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; - int index = LINKED_HASH_MAP.this.findIndex(entry.ENTRY_KEY()); - if(index >= 0) return VALUE_EQUALS(entry.ENTRY_VALUE(), LINKED_HASH_MAP.this.values[index]); - } - else { - Map.Entry entry = (Map.Entry)o; - int index = LINKED_HASH_MAP.this.findIndex(entry.getKey()); - if(index >= 0) return Objects.equals(entry.getValue(), VALUE_TO_OBJ(LINKED_HASH_MAP.this.values[index])); - } - } - return false; - } - - @Override - @Deprecated - public boolean remove(Object o) { - if(o instanceof Map.Entry) { - if(o instanceof MAP.Entry) { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; - return LINKED_HASH_MAP.this.remove(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); - } - Map.Entry entry = (Map.Entry)o; - return LINKED_HASH_MAP.this.remove(entry.getKey(), entry.getValue()); - } - return false; - } - - @Override - public int size() { - return LINKED_HASH_MAP.this.size(); - } - - @Override - public void clear() { - LINKED_HASH_MAP.this.clear(); - } - } - - private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE { -#if TYPE_OBJECT - @Override - @Deprecated - public boolean contains(Object e) { - return containsKey(e); - } - - @Override - public boolean remove(Object o) { - int oldSize = size; - LINKED_HASH_MAP.this.remove(o); - return size != oldSize; - } - -#else - @Override - public boolean contains(KEY_TYPE e) { - return containsKey(e); - } - - @Override - public boolean remove(KEY_TYPE o) { - int oldSize = size; - LINKED_HASH_MAP.this.remove(o); - return size != oldSize; - } - -#endif - @Override - public boolean add(KEY_TYPE o) { throw new UnsupportedOperationException(); } - - @Override - public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); } - - @Override - public boolean addAndMoveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); } - - @Override - public boolean moveToFirst(KEY_TYPE o) { - return LINKED_HASH_MAP.this.moveToFirst(o); - } - - @Override - public boolean moveToLast(KEY_TYPE o) { - return LINKED_HASH_MAP.this.moveToLast(o); - } - - @Override - public LIST_ITERATOR KEY_GENERIC_TYPE iterator() { - return new KeyIterator(); - } - - @Override - public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { - return new KeyIterator(fromElement); - } - - @Override - public KeySet copy() { throw new UnsupportedOperationException(); } - - @Override - public int size() { - return LINKED_HASH_MAP.this.size(); - } - - @Override - public void clear() { - LINKED_HASH_MAP.this.clear(); - } - - @Override - public KEY_TYPE FIRST_KEY() { - return FIRST_ENTRY_KEY(); - } - - @Override - public KEY_TYPE POLL_FIRST_KEY() { - return POLL_FIRST_ENTRY_KEY(); - } - - @Override - public KEY_TYPE LAST_KEY() { - return LAST_ENTRY_KEY(); - } - - @Override - public KEY_TYPE POLL_LAST_KEY() { - return POLL_LAST_ENTRY_KEY(); - } - - @Override - public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { - int index = firstIndex; - while(index != -1){ - action.accept(keys[index]); - index = (int)links[index]; - } - } - - @Override - public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - int count = 0; - int index = firstIndex; - while(index != -1){ - action.accept(count++, keys[index]); - index = (int)links[index]; - } - } - - @Override - public void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - int index = firstIndex; - while(index != -1){ - action.accept(input, keys[index]); - index = (int)links[index]; - } - } - - @Override - public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return false; - int index = firstIndex; - while(index != -1){ - if(filter.test(keys[index])) return true; - index = (int)links[index]; - } - return false; - } - - @Override - public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - int index = firstIndex; - while(index != -1){ - if(filter.test(keys[index])) return false; - index = (int)links[index]; - } - return true; - } - - @Override - public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - int index = firstIndex; - while(index != -1) { - if(!filter.test(keys[index])) return false; - index = (int)links[index]; - } - return true; - } - -#if !TYPE_OBJECT - @Override - public KEY_TYPE reduce(KEY_TYPE identity, SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - KEY_TYPE state = identity; - int index = firstIndex; - while(index != -1) { - state = operator.APPLY_KEY_VALUE(state, keys[index]); - index = (int)links[index]; - } - return state; - } - -#else - @Override - public KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) { - Objects.requireNonNull(operator); - KEY_SPECIAL_TYPE state = identity; - int index = firstIndex; - while(index != -1) { - state = operator.apply(state, keys[index]); - index = (int)links[index]; - } - return state; - } - -#endif - @Override - public KEY_TYPE reduce(SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - KEY_TYPE state = EMPTY_KEY_VALUE; - boolean empty = true; - int index = firstIndex; - while(index != -1) { - if(empty) { - empty = false; - state = keys[index]; - index = (int)links[index]; - continue; - } - state = operator.APPLY_KEY_VALUE(state, keys[index]); - index = (int)links[index]; - } - return state; - } - - @Override - public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return EMPTY_KEY_VALUE; - int index = firstIndex; - while(index != -1){ - if(filter.test(keys[index])) return keys[index]; - index = (int)links[index]; - } - return EMPTY_KEY_VALUE; - } - - @Override - public int count(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return 0; - int result = 0; - int index = firstIndex; - while(index != -1){ - if(filter.test(keys[index])) result++; - index = (int)links[index]; - } - return result; - } - } - - private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { -#if VALUE_OBJECT - @Override - @Deprecated - public boolean contains(Object e) { - return containsValue(e); - } - -#else - @Override - public boolean contains(VALUE_TYPE e) { - return containsValue(e); - } - -#endif - @Override - public boolean add(VALUE_TYPE o) { - throw new UnsupportedOperationException(); - } - - @Override - public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() { - return new ValueIterator(); - } - - @Override - public int size() { - return LINKED_HASH_MAP.this.size(); - } - - @Override - public void clear() { - LINKED_HASH_MAP.this.clear(); - } - - @Override - public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) { - Objects.requireNonNull(action); - int index = firstIndex; - while(index != -1){ - action.accept(values[index]); - index = (int)links[index]; - } - } - - @Override - public void forEachIndexed(VALUE_BI_FROM_INT_CONSUMER VALUE_GENERIC_TYPE action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - int count = 0; - int index = firstIndex; - while(index != -1){ - action.accept(count++, values[index]); - index = (int)links[index]; - } - } - - @Override - public void forEach(E input, VALUE_BI_FROM_OBJECT_CONSUMER VSV_GENERIC_TYPE action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - int index = firstIndex; - while(index != -1){ - action.accept(input, values[index]); - index = (int)links[index]; - } - } - - @Override - public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return false; - int index = firstIndex; - while(index != -1){ - if(filter.test(values[index])) return true; - index = (int)links[index]; - } - return false; - } - - @Override - public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - int index = firstIndex; - while(index != -1) { - if(filter.test(values[index])) return false; - index = (int)links[index]; - } - return true; - } - - @Override - public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - int index = firstIndex; - while(index != -1) { - if(!filter.test(values[index])) return false; - index = (int)links[index]; - } - return true; - } - -#if !VALUE_OBJECT - @Override - public VALUE_TYPE reduce(VALUE_TYPE identity, VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - VALUE_TYPE state = identity; - int index = firstIndex; - while(index != -1) { - state = operator.APPLY_VALUE(state, values[index]); - index = (int)links[index]; - } - return state; - } - -#else - @Override - public VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction operator) { - Objects.requireNonNull(operator); - VALUE_SPECIAL_TYPE state = identity; - int index = firstIndex; - while(index != -1) { - state = operator.apply(state, values[index]); - index = (int)links[index]; - } - return state; - } - -#endif - @Override - public VALUE_TYPE reduce(VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - VALUE_TYPE state = EMPTY_VALUE; - boolean empty = true; - int index = firstIndex; - while(index != -1) { - if(empty) { - empty = false; - state = values[index]; - index = (int)links[index]; - continue; - } - state = operator.APPLY_VALUE(state, values[index]); - index = (int)links[index]; - } - return state; - } - - @Override - public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return EMPTY_VALUE; - int index = firstIndex; - while(index != -1){ - if(filter.test(values[index])) return values[index]; - index = (int)links[index]; - } - return EMPTY_VALUE; - } - - @Override - public int count(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return 0; - int result = 0; - int index = firstIndex; - while(index != -1){ - if(filter.test(values[index])) result++; - index = (int)links[index]; - } - return result; - } - } - - private class FastEntryIterator extends MapIterator implements ObjectListIterator { - MapEntry entry = new MapEntry(); - - public FastEntryIterator() {} - public FastEntryIterator(KEY_TYPE from) { - super(from); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { - entry.index = nextEntry(); - return entry; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { - entry.index = previousEntry(); - return entry; - } - - @Override - public void set(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } - - @Override - public void add(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } - } - - private class EntryIterator extends MapIterator implements ObjectListIterator { - MapEntry entry; - - public EntryIterator() {} - public EntryIterator(KEY_TYPE from) { - super(from); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { - return entry = new MapEntry(nextEntry()); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { - return entry = new MapEntry(previousEntry()); - } - - @Override - public void remove() { - super.remove(); - entry.index = -1; - } - - @Override - public void set(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } - - @Override - public void add(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } - } - - private class KeyIterator extends MapIterator implements LIST_ITERATOR KEY_GENERIC_TYPE { - - public KeyIterator() {} - public KeyIterator(KEY_TYPE from) { - super(from); - } - - @Override - public KEY_TYPE PREVIOUS() { - return keys[previousEntry()]; - } - - @Override - public KEY_TYPE NEXT() { - return keys[nextEntry()]; - } - - @Override - public void set(KEY_TYPE e) { throw new UnsupportedOperationException(); } - @Override - public void add(KEY_TYPE e) { throw new UnsupportedOperationException(); } - } - - private class ValueIterator extends MapIterator implements VALUE_LIST_ITERATOR VALUE_GENERIC_TYPE { - public ValueIterator() {} - - @Override - public VALUE_TYPE VALUE_PREVIOUS() { - return values[previousEntry()]; - } - - @Override - public VALUE_TYPE VALUE_NEXT() { - return values[nextEntry()]; - } - - @Override - public void set(VALUE_TYPE e) { throw new UnsupportedOperationException(); } - - @Override - public void add(VALUE_TYPE e) { throw new UnsupportedOperationException(); } - } - - private class MapIterator { - int previous = -1; - int next = -1; - int current = -1; - int index = 0; - - MapIterator() { - next = firstIndex; - } - - MapIterator(KEY_TYPE from) { - if(KEY_EQUALS_NULL(from)) { - if(containsNull) { - next = (int) links[nullIndex]; - previous = nullIndex; - } - else throw new NoSuchElementException("The null element is not in the set"); - } - else if(keys[lastIndex] == from) { - previous = lastIndex; - index = size; - } - else { - int pos = HashUtil.mix(KEY_TO_HASH(from)) & mask; - while(KEY_EQUALS_NOT_NULL(keys[pos])) { - if(KEY_EQUALS(keys[pos], from)) { - next = (int)links[pos]; - previous = pos; - break; - } - pos = ++pos & mask; - } - if(previous == -1 && next == -1) - throw new NoSuchElementException("The element was not found"); - } - } - - public boolean hasNext() { - return next != -1; - } - - public boolean hasPrevious() { - return previous != -1; - } - - public int nextIndex() { - ensureIndexKnown(); - return index; - } - - public int previousIndex() { - ensureIndexKnown(); - return index - 1; - } - - public void remove() { - if(current == -1) throw new IllegalStateException(); - ensureIndexKnown(); - if(current == previous) { - index--; - previous = (int)(links[current] >>> 32); - } - else next = (int)links[current]; - size--; - if(previous == -1) firstIndex = next; - else links[previous] ^= ((links[previous] ^ (next & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - - if(next == -1) lastIndex = previous; - else links[next] ^= ((links[next] ^ ((previous & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); - if(current == nullIndex) { - current = -1; - containsNull = false; - keys[nullIndex] = EMPTY_KEY_VALUE; - values[nullIndex] = EMPTY_VALUE; - } - else { - int slot, last, startPos = current; - current = -1; - KEY_TYPE current; - while(true) { - startPos = ((last = startPos) + 1) & mask; - while(true){ - if(KEY_EQUALS_NULL((current = keys[startPos]))) { - keys[last] = EMPTY_KEY_VALUE; - values[last] = EMPTY_VALUE; - return; - } - slot = HashUtil.mix(KEY_TO_HASH(current)) & mask; - if(last <= startPos ? (last >= slot || slot > startPos) : (last >= slot && slot > startPos)) break; - startPos = ++startPos & mask; - } - keys[last] = current; - values[last] = values[startPos]; - if(next == startPos) next = last; - if(previous == startPos) previous = last; - onNodeMoved(startPos, last); - } - } - } - - public int previousEntry() { - if(!hasPrevious()) throw new NoSuchElementException(); - current = previous; - previous = (int)(links[current] >> 32); - next = current; - if(index >= 0) index--; - return current; - } - - public int nextEntry() { - if(!hasNext()) throw new NoSuchElementException(); - current = next; - next = (int)(links[current]); - previous = current; - if(index >= 0) index++; - return current; - } - - private void ensureIndexKnown() { - if(index == -1) { - if(previous == -1) { - index = 0; - } - else if(next == -1) { - index = size; - } - else { - index = 1; - for(int pos = firstIndex;pos != previous;pos = (int)links[pos], index++); - } - } - } - - } +package speiger.src.collections.PACKAGE.maps.impl.hash; + +import java.util.Arrays; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Objects; +import java.util.function.Consumer; +import java.util.function.BiFunction; +import java.util.function.Predicate; +#if !TYPE_OBJECT && JDK_TYPE +import java.util.function.PREDICATE; +#endif +#if !SAME_TYPE && JDK_VALUE && !VALUE_OBJECT +import java.util.function.VALUE_PREDICATE; +#endif + +import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.functions.CONSUMER; +import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; +#endif +import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER; +#if !TYPE_OBJECT && !VALUE_OBJECT +import speiger.src.collections.ints.functions.consumer.IntObjectConsumer; +#endif +#if !SAME_TYPE && !TYPE_INT +import speiger.src.collections.ints.functions.consumer.VALUE_BI_FROM_INT_CONSUMER; +#endif +#if !TYPE_OBJECT && !JDK_TYPE +import speiger.src.collections.PACKAGE.functions.function.PREDICATE; +#endif +#if !TYPE_INT || !SAME_TYPE +import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; +#endif +import speiger.src.collections.PACKAGE.functions.function.SINGLE_UNARY_OPERATOR; +import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP; +import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET; +import speiger.src.collections.PACKAGE.sets.ORDERED_SET; +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; +#if !SAME_TYPE +import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR; +#endif +#if !VALUE_OBJECT && !SAME_TYPE +import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER; +import speiger.src.collections.VALUE_PACKAGE.lists.VALUE_LIST_ITERATOR; +#endif +#if !TYPE_OBJECT && !VALUE_OBJECT || !VALUE_OBJECT +import speiger.src.collections.objects.functions.consumer.ObjectObjectConsumer; +#endif +#if !SAME_TYPE +#if !TYPE_OBJECT +import speiger.src.collections.objects.functions.consumer.VALUE_BI_FROM_OBJECT_CONSUMER; + +#endif +#if !JDK_VALUE +import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE; +#endif +#endif +#if !TYPE_OBJECT +#if !VALUE_OBJECT +import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator; + +#endif +import speiger.src.collections.objects.collections.ObjectBidirectionalIterator; +import speiger.src.collections.objects.lists.ObjectListIterator; +import speiger.src.collections.objects.sets.AbstractObjectSet; +import speiger.src.collections.objects.sets.ObjectOrderedSet; +#endif +import speiger.src.collections.utils.HashUtil; + +/** + * A Type Specific LinkedHashMap implementation that uses specific arrays to create links between nodes to remove the wrapping of elements + * to greatly reduce memory usage. In Addition adding some helper methods to move around elements. + * This implementation of SortedMap does not support SubMaps of any kind. It implements the interface due to sortability and first/last access + * @Type(T) + * @ValueType(V) + */ +public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_GENERIC_TYPE implements ORDERED_MAP KEY_VALUE_GENERIC_TYPE +{ + /** The Backing array for links between nodes. Left 32 Bits => Previous Entry, Right 32 Bits => Next Entry */ + protected transient long[] links; + /** The First Index in the Map */ + protected int firstIndex = -1; + /** The Last Index in the Map */ + protected int lastIndex = -1; + + /** + * Default Constructor + */ + public LINKED_HASH_MAP() { + this(HashUtil.DEFAULT_MIN_CAPACITY, HashUtil.DEFAULT_LOAD_FACTOR); + } + + /** + * Constructor that defines the minimum capacity + * @param minCapacity the minimum capacity the HashMap is allowed to be. + * @throws IllegalStateException if the minimum capacity is negative + */ + public LINKED_HASH_MAP(int minCapacity) { + this(minCapacity, HashUtil.DEFAULT_LOAD_FACTOR); + } + + /** + * Constructor that defines the minimum capacity and load factor + * @param minCapacity the minimum capacity the HashMap is allowed to be. + * @param loadFactor the percentage of how full the backing array can be before they resize + * @throws IllegalStateException if the minimum capacity is negative + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + */ + public LINKED_HASH_MAP(int minCapacity, float loadFactor) { + super(minCapacity, loadFactor); + links = new long[nullIndex + 1]; + } + +#if !TYPE_OBJECT || !VALUE_OBJECT + /** + * Helper constructor that allow to create a map from boxed values (it will unbox them) + * @param keys the keys that should be put into the map + * @param values the values that should be put into the map. + * @throws IllegalStateException if the keys and values do not match in lenght + */ + public LINKED_HASH_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values) { + this(keys, values, HashUtil.DEFAULT_LOAD_FACTOR); + } + + /** + * Helper constructor that allow to create a map from boxed values (it will unbox them) + * @param keys the keys that should be put into the map + * @param values the values that should be put into the map. + * @param loadFactor the percentage of how full the backing array can be before they resize + * @throws IllegalStateException if the keys and values do not match in lenght + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + */ + public LINKED_HASH_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, float loadFactor) { + this(keys.length, loadFactor); + if(keys.length != values.length) throw new IllegalStateException("Input Arrays are not equal size"); + for(int i = 0,m=keys.length;i map) { + this(map, HashUtil.DEFAULT_LOAD_FACTOR); + } + + /** + * A Helper constructor that allows to create a Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + * @param loadFactor the percentage of how full the backing array can be before they resize + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + */ + public LINKED_HASH_MAP(Map map, float loadFactor) { + this(map.size(), loadFactor); + putAll(map); + } + + /** + * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + */ + public LINKED_HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map) { + this(map, HashUtil.DEFAULT_LOAD_FACTOR); + } + + /** + * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + * @param loadFactor the percentage of how full the backing array can be before they resize + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + */ + public LINKED_HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map, float loadFactor) { + this(map.size(), loadFactor); + putAll(map); + } + + @Override + public VALUE_TYPE putAndMoveToFirst(KEY_TYPE key, VALUE_TYPE value) { + if(KEY_EQUALS_NULL(key)) { + if(containsNull) { + VALUE_TYPE lastValue = values[nullIndex]; + values[nullIndex] = value; + moveToFirstIndex(nullIndex); + return lastValue; + } + values[nullIndex] = value; + containsNull = true; + onNodeAdded(nullIndex); + moveToFirstIndex(nullIndex); + } + else { + int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask; + while(KEY_EQUALS_NOT_NULL(keys[pos])) { + if(KEY_EQUALS(keys[pos], key)) { + VALUE_TYPE lastValue = values[pos]; + values[pos] = value; + moveToFirstIndex(pos); + return lastValue; + } + pos = ++pos & mask; + } + keys[pos] = key; + values[pos] = value; + onNodeAdded(pos); + moveToFirstIndex(pos); + } + if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor)); + return getDefaultReturnValue(); + } + + @Override + public VALUE_TYPE putAndMoveToLast(KEY_TYPE key, VALUE_TYPE value) { + if(KEY_EQUALS_NULL(key)) { + if(containsNull) { + VALUE_TYPE lastValue = values[nullIndex]; + values[nullIndex] = value; + moveToLastIndex(nullIndex); + return lastValue; + } + values[nullIndex] = value; + containsNull = true; + onNodeAdded(nullIndex); + moveToLastIndex(nullIndex); + } + else { + int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask; + while(KEY_EQUALS_NOT_NULL(keys[pos])) { + if(KEY_EQUALS(keys[pos], key)) { + VALUE_TYPE lastValue = values[pos]; + values[pos] = value; + moveToLastIndex(pos); + return lastValue; + } + pos = ++pos & mask; + } + keys[pos] = key; + values[pos] = value; + onNodeAdded(pos); + moveToLastIndex(pos); + } + if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor)); + return getDefaultReturnValue(); + } + + @Override + public boolean moveToFirst(KEY_TYPE key) { + if(isEmpty() || KEY_EQUALS(FIRST_ENTRY_KEY(), key)) return false; + if(KEY_EQUALS_NULL(key)) { + if(containsNull) { + moveToFirstIndex(nullIndex); + return true; + } + } + else { + int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask; + while(KEY_EQUALS_NOT_NULL(keys[pos])) { + if(KEY_EQUALS(keys[pos], key)) { + moveToFirstIndex(pos); + return true; + } + pos = ++pos & mask; + } + } + return false; + } + + @Override + public boolean moveToLast(KEY_TYPE key) { + if(isEmpty() || KEY_EQUALS(LAST_ENTRY_KEY(), key)) return false; + if(KEY_EQUALS_NULL(key)) { + if(containsNull) { + moveToLastIndex(nullIndex); + return true; + } + } + else { + int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask; + while(KEY_EQUALS_NOT_NULL(keys[pos])) { + if(KEY_EQUALS(keys[pos], key)) { + moveToLastIndex(pos); + return true; + } + pos = ++pos & mask; + } + } + return false; + } + + @Override + public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key) { + int index = findIndex(key); + if(index < 0) return getDefaultReturnValue(); + moveToFirstIndex(index); + return values[index]; + } + + @Override + public VALUE_TYPE getAndMoveToLast(KEY_TYPE key) { + int index = findIndex(key); + if(index < 0) return getDefaultReturnValue(); + moveToLastIndex(index); + return values[index]; + } + +#if !VALUE_OBJECT + @Override + public boolean containsValue(VALUE_TYPE value) { + int index = firstIndex; + while(index != -1) { + if(VALUE_EQUALS(values[index], value)) return true; + index = (int)links[index]; + } + return false; + } + +#endif + @Override + @ValuePrimitive + public boolean containsValue(Object value) { + int index = firstIndex; + while(index != -1) { +#if VALUE_OBJECT + if(VALUE_EQUALS(values[index], value)) return true; +#else + if((value == null && values[index] == getDefaultReturnValue()) || EQUALS_VALUE_TYPE(values[index], value)) return true; +#endif + index = (int)links[index]; + } + return false; + } + + @Override + public LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE copy() { + LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE map = new LINKED_HASH_MAPKV_BRACES(0, loadFactor); + map.minCapacity = minCapacity; + map.mask = mask; + map.maxFill = maxFill; + map.nullIndex = nullIndex; + map.containsNull = containsNull; + map.size = size; + map.keys = Arrays.copyOf(keys, keys.length); + map.values = Arrays.copyOf(values, values.length); + map.links = Arrays.copyOf(links, links.length); + map.firstIndex = firstIndex; + map.lastIndex = lastIndex; + return map; + } + + @Override + public KEY_TYPE FIRST_ENTRY_KEY() { + if(size == 0) throw new NoSuchElementException(); + return keys[firstIndex]; + } + + @Override + public KEY_TYPE POLL_FIRST_ENTRY_KEY() { + if(size == 0) throw new NoSuchElementException(); + int pos = firstIndex; + onNodeRemoved(pos); + KEY_TYPE result = keys[pos]; + size--; + if(KEY_EQUALS_NULL(result)) { + containsNull = false; + keys[nullIndex] = EMPTY_KEY_VALUE; + values[nullIndex] = EMPTY_VALUE; + } + else shiftKeys(pos); + if(nullIndex > minCapacity && size < maxFill / 4 && nullIndex > HashUtil.DEFAULT_MIN_CAPACITY) rehash(nullIndex / 2); + return result; + } + + @Override + public KEY_TYPE LAST_ENTRY_KEY() { + if(size == 0) throw new NoSuchElementException(); + return keys[lastIndex]; + } + + @Override + public KEY_TYPE POLL_LAST_ENTRY_KEY() { + if(size == 0) throw new NoSuchElementException(); + int pos = lastIndex; + onNodeRemoved(pos); + KEY_TYPE result = keys[pos]; + size--; + if(KEY_EQUALS_NULL(result)) { + containsNull = false; + keys[nullIndex] = EMPTY_KEY_VALUE; + values[nullIndex] = EMPTY_VALUE; + } + else shiftKeys(pos); + if(nullIndex > minCapacity && size < maxFill / 4 && nullIndex > HashUtil.DEFAULT_MIN_CAPACITY) rehash(nullIndex / 2); + return result; + } + + @Override + public VALUE_TYPE FIRST_ENTRY_VALUE() { + if(size == 0) throw new NoSuchElementException(); + return values[firstIndex]; + } + + @Override + public VALUE_TYPE LAST_ENTRY_VALUE() { + if(size == 0) throw new NoSuchElementException(); + return values[lastIndex]; + } + + @Override + public ObjectOrderedSet ENTRY_SET() { + if(entrySet == null) entrySet = new MapEntrySet(); + return (ObjectOrderedSet)entrySet; + } + + @Override + public ORDERED_SET KEY_GENERIC_TYPE keySet() { + if(keySet == null) keySet = new KeySet(); + return (ORDERED_SET KEY_GENERIC_TYPE)keySet; + } + + @Override + public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { + if(valuesC == null) valuesC = new Values(); + return valuesC; + } + + @Override + public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { + int index = firstIndex; + while(index != -1){ + action.accept(keys[index], values[index]); + index = (int)links[index]; + } + } + + @Override + public void clear() { + super.clear(); + firstIndex = lastIndex = -1; + } + + @Override + public void clearAndTrim(int size) { + int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor))); + if(request >= nullIndex) { + clear(); + return; + } + nullIndex = request; + mask = request-1; + maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1); + keys = NEW_KEY_ARRAY(request + 1); + values = NEW_VALUE_ARRAY(request + 1); + links = new long[request + 1]; + firstIndex = lastIndex = -1; + this.size = 0; + containsNull = false; + } + + protected void moveToFirstIndex(int startPos) { + if(size == 1 || firstIndex == startPos) return; + if(lastIndex == startPos) { + lastIndex = (int)(links[startPos] >>> 32); + links[lastIndex] |= 0xFFFFFFFFL; + } + else { + long link = links[startPos]; + int prev = (int)(link >>> 32); + int next = (int)link; + links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L); + } + links[firstIndex] ^= ((links[firstIndex] ^ ((startPos & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); + links[startPos] = 0xFFFFFFFF00000000L | (firstIndex & 0xFFFFFFFFL); + firstIndex = startPos; + } + + protected void moveToLastIndex(int startPos) { + if(size == 1 || lastIndex == startPos) return; + if(firstIndex == startPos) { + firstIndex = (int)links[startPos]; + links[lastIndex] |= 0xFFFFFFFF00000000L; + } + else { + long link = links[startPos]; + int prev = (int)(link >>> 32); + int next = (int)link; + links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L); + } + links[lastIndex] ^= ((links[lastIndex] ^ (startPos & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + links[startPos] = ((lastIndex & 0xFFFFFFFFL) << 32) | 0xFFFFFFFFL; + lastIndex = startPos; + } + + @Override + protected void onNodeAdded(int pos) { + if(size == 0) { + firstIndex = lastIndex = pos; + links[pos] = -1L; + } + else { + links[lastIndex] ^= ((links[lastIndex] ^ (pos & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + links[pos] = ((lastIndex & 0xFFFFFFFFL) << 32) | 0xFFFFFFFFL; + lastIndex = pos; + } + } + + @Override + protected void onNodeRemoved(int pos) { + if(size == 0) firstIndex = lastIndex = -1; + else if(firstIndex == pos) { + firstIndex = (int)links[pos]; + if(0 <= firstIndex) links[firstIndex] |= 0xFFFFFFFF00000000L; + } + else if(lastIndex == pos) { + lastIndex = (int)(links[pos] >>> 32); + if(0 <= lastIndex) links[lastIndex] |= 0xFFFFFFFFL; + } + else { + long link = links[pos]; + int prev = (int)(link >>> 32); + int next = (int)link; + links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L); + } + } + + @Override + protected void onNodeMoved(int from, int to) { + if(size == 1) { + firstIndex = lastIndex = to; + links[to] = -1L; + } + else if(firstIndex == from) { + firstIndex = to; + links[(int)links[from]] ^= ((links[(int)links[from]] ^ ((to & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); + links[to] = links[from]; + } + else if(lastIndex == from) { + lastIndex = to; + links[(int)(links[from] >>> 32)] ^= ((links[(int)(links[from] >>> 32)] ^ (to & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + links[to] = links[from]; + } + else { + long link = links[from]; + int prev = (int)(link >>> 32); + int next = (int)link; + links[prev] ^= ((links[prev] ^ (to & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + links[next] ^= ((links[next] ^ ((to & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); + links[to] = link; + } + } + + @Override + protected void rehash(int newSize) { + int newMask = newSize - 1; + KEY_TYPE[] newKeys = NEW_KEY_ARRAY(newSize + 1); + VALUE_TYPE[] newValues = NEW_VALUE_ARRAY(newSize + 1); + long[] newLinks = new long[newSize + 1]; + int i = firstIndex, prev = -1, newPrev = -1, pos; + firstIndex = -1; + for(int j = size; j-- != 0;) { + if(KEY_EQUALS_NULL(keys[i])) pos = newSize; + else { + pos = HashUtil.mix(KEY_TO_HASH(keys[i])) & newMask; + while(KEY_EQUALS_NOT_NULL(newKeys[pos])) pos = ++pos & newMask; + } + newKeys[pos] = keys[i]; + newValues[pos] = values[i]; + if(prev != -1) { + newLinks[newPrev] ^= ((newLinks[newPrev] ^ (pos & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + newLinks[pos] ^= ((newLinks[pos] ^ ((newPrev & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); + newPrev = pos; + } + else { + newPrev = firstIndex = pos; + newLinks[pos] = -1L; + } + i = (int)links[prev = i]; + } + links = newLinks; + lastIndex = newPrev; + if(newPrev != -1) newLinks[newPrev] |= 0xFFFFFFFFL; + nullIndex = newSize; + mask = newMask; + maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1); + keys = newKeys; + values = newValues; + } + + private class MapEntrySet extends AbstractObjectSet implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE { + @Override + public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } + @Override + public boolean addAndMoveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } + + @Override + public boolean moveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { + return LINKED_HASH_MAP.this.moveToFirst(o.ENTRY_KEY()); + } + + @Override + public boolean moveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { + return LINKED_HASH_MAP.this.moveToLast(o.ENTRY_KEY()); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE first() { + return new BasicEntryKV_BRACES(FIRST_ENTRY_KEY(), FIRST_ENTRY_VALUE()); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE last() { + return new BasicEntryKV_BRACES(LAST_ENTRY_KEY(), LAST_ENTRY_VALUE()); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirst() { + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(FIRST_ENTRY_KEY(), FIRST_ENTRY_VALUE()); + POLL_FIRST_ENTRY_KEY(); + return entry; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLast() { + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(LAST_ENTRY_KEY(), LAST_ENTRY_VALUE()); + POLL_LAST_ENTRY_KEY(); + return entry; + } + + @Override + public ObjectBidirectionalIterator iterator() { + return new EntryIterator(); + } + + @Override + public ObjectBidirectionalIterator iterator(MAP.Entry KEY_VALUE_GENERIC_TYPE fromElement) { + return new EntryIterator(fromElement.ENTRY_KEY()); + } + + @Override + public ObjectBidirectionalIterator fastIterator() { + return new FastEntryIterator(); + } + + @Override + public ObjectBidirectionalIterator fastIterator(KEY_TYPE fromElement) { + return new FastEntryIterator(fromElement); + } + + @Override + public MapEntrySet copy() { throw new UnsupportedOperationException(); } + + @Override + public void forEach(Consumer action) { + int index = firstIndex; + while(index != -1){ + action.accept(new BasicEntryKV_BRACES(keys[index], values[index])); + index = (int)links[index]; + } + } + + @Override + public void fastForEach(Consumer action) { + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + int index = firstIndex; + while(index != -1){ + entry.set(keys[index], values[index]); + action.accept(entry); + index = (int)links[index]; + } + } + + @Override + public void forEachIndexed(IntObjectConsumer action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + int count = 0; + int index = firstIndex; + while(index != -1) { + action.accept(count++, new BasicEntryKV_BRACES(keys[index], values[index])); + index = (int)links[index]; + } + } + + @Override + public void forEach(E input, ObjectObjectConsumer action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + int index = firstIndex; + while(index != -1) { + action.accept(input, new BasicEntryKV_BRACES(keys[index], values[index])); + index = (int)links[index]; + } + } + + @Override + public boolean matchesAny(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return false; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + int index = firstIndex; + while(index != -1) { + entry.set(keys[index], values[index]); + if(filter.test(entry)) return true; + index = (int)links[index]; + } + return false; + } + + @Override + public boolean matchesNone(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + int index = firstIndex; + while(index != -1) { + entry.set(keys[index], values[index]); + if(filter.test(entry)) return false; + index = (int)links[index]; + } + return true; + } + + @Override + public boolean matchesAll(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + int index = firstIndex; + while(index != -1) { + entry.set(keys[index], values[index]); + if(!filter.test(entry)) return false; + index = (int)links[index]; + } + return true; + } + + @Override + public E reduce(E identity, BiFunction operator) { + Objects.requireNonNull(operator); + E state = identity; + int index = firstIndex; + while(index != -1) { + state = operator.apply(state, new BasicEntryKV_BRACES(keys[index], values[index])); + index = (int)links[index]; + } + return state; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE reduce(ObjectObjectUnaryOperator operator) { + Objects.requireNonNull(operator); + MAP.Entry KEY_VALUE_GENERIC_TYPE state = null; + boolean empty = true; + int index = firstIndex; + while(index != -1) { + if(empty) { + empty = false; + state = new BasicEntryKV_BRACES(keys[index], values[index]); + index = (int)links[index]; + continue; + } + state = operator.apply(state, new BasicEntryKV_BRACES(keys[index], values[index])); + index = (int)links[index]; + } + return state; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE findFirst(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return null; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + int index = firstIndex; + while(index != -1) { + entry.set(keys[index], values[index]); + if(filter.test(entry)) return entry; + index = (int)links[index]; + } + return null; + } + + @Override + public int count(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return 0; + int result = 0; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + int index = firstIndex; + while(index != -1) { + entry.set(keys[index], values[index]); + if(filter.test(entry)) result++; + index = (int)links[index]; + } + return result; + } + + @Override + @Deprecated + public boolean contains(Object o) { + if(o instanceof Map.Entry) { + if(o instanceof MAP.Entry) { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; + int index = LINKED_HASH_MAP.this.findIndex(entry.ENTRY_KEY()); + if(index >= 0) return VALUE_EQUALS(entry.ENTRY_VALUE(), LINKED_HASH_MAP.this.values[index]); + } + else { + Map.Entry entry = (Map.Entry)o; + int index = LINKED_HASH_MAP.this.findIndex(entry.getKey()); + if(index >= 0) return Objects.equals(entry.getValue(), VALUE_TO_OBJ(LINKED_HASH_MAP.this.values[index])); + } + } + return false; + } + + @Override + @Deprecated + public boolean remove(Object o) { + if(o instanceof Map.Entry) { + if(o instanceof MAP.Entry) { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; + return LINKED_HASH_MAP.this.remove(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); + } + Map.Entry entry = (Map.Entry)o; + return LINKED_HASH_MAP.this.remove(entry.getKey(), entry.getValue()); + } + return false; + } + + @Override + public int size() { + return LINKED_HASH_MAP.this.size(); + } + + @Override + public void clear() { + LINKED_HASH_MAP.this.clear(); + } + } + + private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE { +#if TYPE_OBJECT + @Override + @Deprecated + public boolean contains(Object e) { + return containsKey(e); + } + + @Override + public boolean remove(Object o) { + int oldSize = size; + LINKED_HASH_MAP.this.remove(o); + return size != oldSize; + } + +#else + @Override + public boolean contains(KEY_TYPE e) { + return containsKey(e); + } + + @Override + public boolean remove(KEY_TYPE o) { + int oldSize = size; + LINKED_HASH_MAP.this.remove(o); + return size != oldSize; + } + +#endif + @Override + public boolean add(KEY_TYPE o) { throw new UnsupportedOperationException(); } + + @Override + public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); } + + @Override + public boolean addAndMoveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); } + + @Override + public boolean moveToFirst(KEY_TYPE o) { + return LINKED_HASH_MAP.this.moveToFirst(o); + } + + @Override + public boolean moveToLast(KEY_TYPE o) { + return LINKED_HASH_MAP.this.moveToLast(o); + } + + @Override + public LIST_ITERATOR KEY_GENERIC_TYPE iterator() { + return new KeyIterator(); + } + + @Override + public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { + return new KeyIterator(fromElement); + } + + @Override + public KeySet copy() { throw new UnsupportedOperationException(); } + + @Override + public int size() { + return LINKED_HASH_MAP.this.size(); + } + + @Override + public void clear() { + LINKED_HASH_MAP.this.clear(); + } + + @Override + public KEY_TYPE FIRST_KEY() { + return FIRST_ENTRY_KEY(); + } + + @Override + public KEY_TYPE POLL_FIRST_KEY() { + return POLL_FIRST_ENTRY_KEY(); + } + + @Override + public KEY_TYPE LAST_KEY() { + return LAST_ENTRY_KEY(); + } + + @Override + public KEY_TYPE POLL_LAST_KEY() { + return POLL_LAST_ENTRY_KEY(); + } + + @Override + public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { + int index = firstIndex; + while(index != -1){ + action.accept(keys[index]); + index = (int)links[index]; + } + } + + @Override + public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + int count = 0; + int index = firstIndex; + while(index != -1){ + action.accept(count++, keys[index]); + index = (int)links[index]; + } + } + + @Override + public void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + int index = firstIndex; + while(index != -1){ + action.accept(input, keys[index]); + index = (int)links[index]; + } + } + + @Override + public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return false; + int index = firstIndex; + while(index != -1){ + if(filter.test(keys[index])) return true; + index = (int)links[index]; + } + return false; + } + + @Override + public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + int index = firstIndex; + while(index != -1){ + if(filter.test(keys[index])) return false; + index = (int)links[index]; + } + return true; + } + + @Override + public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + int index = firstIndex; + while(index != -1) { + if(!filter.test(keys[index])) return false; + index = (int)links[index]; + } + return true; + } + +#if !TYPE_OBJECT + @Override + public KEY_TYPE reduce(KEY_TYPE identity, SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + KEY_TYPE state = identity; + int index = firstIndex; + while(index != -1) { + state = operator.APPLY_KEY_VALUE(state, keys[index]); + index = (int)links[index]; + } + return state; + } + +#else + @Override + public KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) { + Objects.requireNonNull(operator); + KEY_SPECIAL_TYPE state = identity; + int index = firstIndex; + while(index != -1) { + state = operator.apply(state, keys[index]); + index = (int)links[index]; + } + return state; + } + +#endif + @Override + public KEY_TYPE reduce(SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + KEY_TYPE state = EMPTY_KEY_VALUE; + boolean empty = true; + int index = firstIndex; + while(index != -1) { + if(empty) { + empty = false; + state = keys[index]; + index = (int)links[index]; + continue; + } + state = operator.APPLY_KEY_VALUE(state, keys[index]); + index = (int)links[index]; + } + return state; + } + + @Override + public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return EMPTY_KEY_VALUE; + int index = firstIndex; + while(index != -1){ + if(filter.test(keys[index])) return keys[index]; + index = (int)links[index]; + } + return EMPTY_KEY_VALUE; + } + + @Override + public int count(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return 0; + int result = 0; + int index = firstIndex; + while(index != -1){ + if(filter.test(keys[index])) result++; + index = (int)links[index]; + } + return result; + } + } + + private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { +#if VALUE_OBJECT + @Override + @Deprecated + public boolean contains(Object e) { + return containsValue(e); + } + +#else + @Override + public boolean contains(VALUE_TYPE e) { + return containsValue(e); + } + +#endif + @Override + public boolean add(VALUE_TYPE o) { + throw new UnsupportedOperationException(); + } + + @Override + public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() { + return new ValueIterator(); + } + + @Override + public int size() { + return LINKED_HASH_MAP.this.size(); + } + + @Override + public void clear() { + LINKED_HASH_MAP.this.clear(); + } + + @Override + public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) { + Objects.requireNonNull(action); + int index = firstIndex; + while(index != -1){ + action.accept(values[index]); + index = (int)links[index]; + } + } + + @Override + public void forEachIndexed(VALUE_BI_FROM_INT_CONSUMER VALUE_GENERIC_TYPE action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + int count = 0; + int index = firstIndex; + while(index != -1){ + action.accept(count++, values[index]); + index = (int)links[index]; + } + } + + @Override + public void forEach(E input, VALUE_BI_FROM_OBJECT_CONSUMER VSV_GENERIC_TYPE action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + int index = firstIndex; + while(index != -1){ + action.accept(input, values[index]); + index = (int)links[index]; + } + } + + @Override + public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return false; + int index = firstIndex; + while(index != -1){ + if(filter.test(values[index])) return true; + index = (int)links[index]; + } + return false; + } + + @Override + public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + int index = firstIndex; + while(index != -1) { + if(filter.test(values[index])) return false; + index = (int)links[index]; + } + return true; + } + + @Override + public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + int index = firstIndex; + while(index != -1) { + if(!filter.test(values[index])) return false; + index = (int)links[index]; + } + return true; + } + +#if !VALUE_OBJECT + @Override + public VALUE_TYPE reduce(VALUE_TYPE identity, VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + VALUE_TYPE state = identity; + int index = firstIndex; + while(index != -1) { + state = operator.APPLY_VALUE(state, values[index]); + index = (int)links[index]; + } + return state; + } + +#else + @Override + public VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction operator) { + Objects.requireNonNull(operator); + VALUE_SPECIAL_TYPE state = identity; + int index = firstIndex; + while(index != -1) { + state = operator.apply(state, values[index]); + index = (int)links[index]; + } + return state; + } + +#endif + @Override + public VALUE_TYPE reduce(VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + VALUE_TYPE state = EMPTY_VALUE; + boolean empty = true; + int index = firstIndex; + while(index != -1) { + if(empty) { + empty = false; + state = values[index]; + index = (int)links[index]; + continue; + } + state = operator.APPLY_VALUE(state, values[index]); + index = (int)links[index]; + } + return state; + } + + @Override + public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return EMPTY_VALUE; + int index = firstIndex; + while(index != -1){ + if(filter.test(values[index])) return values[index]; + index = (int)links[index]; + } + return EMPTY_VALUE; + } + + @Override + public int count(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return 0; + int result = 0; + int index = firstIndex; + while(index != -1){ + if(filter.test(values[index])) result++; + index = (int)links[index]; + } + return result; + } + } + + private class FastEntryIterator extends MapIterator implements ObjectListIterator { + MapEntry entry = new MapEntry(); + + public FastEntryIterator() {} + public FastEntryIterator(KEY_TYPE from) { + super(from); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { + entry.index = nextEntry(); + return entry; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { + entry.index = previousEntry(); + return entry; + } + + @Override + public void set(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } + + @Override + public void add(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } + } + + private class EntryIterator extends MapIterator implements ObjectListIterator { + MapEntry entry; + + public EntryIterator() {} + public EntryIterator(KEY_TYPE from) { + super(from); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { + return entry = new MapEntry(nextEntry()); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { + return entry = new MapEntry(previousEntry()); + } + + @Override + public void remove() { + super.remove(); + entry.index = -1; + } + + @Override + public void set(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } + + @Override + public void add(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } + } + + private class KeyIterator extends MapIterator implements LIST_ITERATOR KEY_GENERIC_TYPE { + + public KeyIterator() {} + public KeyIterator(KEY_TYPE from) { + super(from); + } + + @Override + public KEY_TYPE PREVIOUS() { + return keys[previousEntry()]; + } + + @Override + public KEY_TYPE NEXT() { + return keys[nextEntry()]; + } + + @Override + public void set(KEY_TYPE e) { throw new UnsupportedOperationException(); } + @Override + public void add(KEY_TYPE e) { throw new UnsupportedOperationException(); } + } + + private class ValueIterator extends MapIterator implements VALUE_LIST_ITERATOR VALUE_GENERIC_TYPE { + public ValueIterator() {} + + @Override + public VALUE_TYPE VALUE_PREVIOUS() { + return values[previousEntry()]; + } + + @Override + public VALUE_TYPE VALUE_NEXT() { + return values[nextEntry()]; + } + + @Override + public void set(VALUE_TYPE e) { throw new UnsupportedOperationException(); } + + @Override + public void add(VALUE_TYPE e) { throw new UnsupportedOperationException(); } + } + + private class MapIterator { + int previous = -1; + int next = -1; + int current = -1; + int index = 0; + + MapIterator() { + next = firstIndex; + } + + MapIterator(KEY_TYPE from) { + if(KEY_EQUALS_NULL(from)) { + if(containsNull) { + next = (int) links[nullIndex]; + previous = nullIndex; + } + else throw new NoSuchElementException("The null element is not in the set"); + } + else if(keys[lastIndex] == from) { + previous = lastIndex; + index = size; + } + else { + int pos = HashUtil.mix(KEY_TO_HASH(from)) & mask; + while(KEY_EQUALS_NOT_NULL(keys[pos])) { + if(KEY_EQUALS(keys[pos], from)) { + next = (int)links[pos]; + previous = pos; + break; + } + pos = ++pos & mask; + } + if(previous == -1 && next == -1) + throw new NoSuchElementException("The element was not found"); + } + } + + public boolean hasNext() { + return next != -1; + } + + public boolean hasPrevious() { + return previous != -1; + } + + public int nextIndex() { + ensureIndexKnown(); + return index; + } + + public int previousIndex() { + ensureIndexKnown(); + return index - 1; + } + + public void remove() { + if(current == -1) throw new IllegalStateException(); + ensureIndexKnown(); + if(current == previous) { + index--; + previous = (int)(links[current] >>> 32); + } + else next = (int)links[current]; + size--; + if(previous == -1) firstIndex = next; + else links[previous] ^= ((links[previous] ^ (next & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + + if(next == -1) lastIndex = previous; + else links[next] ^= ((links[next] ^ ((previous & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); + if(current == nullIndex) { + current = -1; + containsNull = false; + keys[nullIndex] = EMPTY_KEY_VALUE; + values[nullIndex] = EMPTY_VALUE; + } + else { + int slot, last, startPos = current; + current = -1; + KEY_TYPE current; + while(true) { + startPos = ((last = startPos) + 1) & mask; + while(true){ + if(KEY_EQUALS_NULL((current = keys[startPos]))) { + keys[last] = EMPTY_KEY_VALUE; + values[last] = EMPTY_VALUE; + return; + } + slot = HashUtil.mix(KEY_TO_HASH(current)) & mask; + if(last <= startPos ? (last >= slot || slot > startPos) : (last >= slot && slot > startPos)) break; + startPos = ++startPos & mask; + } + keys[last] = current; + values[last] = values[startPos]; + if(next == startPos) next = last; + if(previous == startPos) previous = last; + onNodeMoved(startPos, last); + } + } + } + + public int previousEntry() { + if(!hasPrevious()) throw new NoSuchElementException(); + current = previous; + previous = (int)(links[current] >> 32); + next = current; + if(index >= 0) index--; + return current; + } + + public int nextEntry() { + if(!hasNext()) throw new NoSuchElementException(); + current = next; + next = (int)(links[current]); + previous = current; + if(index >= 0) index++; + return current; + } + + private void ensureIndexKnown() { + if(index == -1) { + if(previous == -1) { + index = 0; + } + else if(next == -1) { + index = size; + } + else { + index = 1; + for(int pos = firstIndex;pos != previous;pos = (int)links[pos], index++); + } + } + } + + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/collections/templates/maps/impl/hash/OpenHashMap.template b/src/builder/resources/speiger/assets/collections/templates/maps/impl/hash/OpenHashMap.template index 60060d1..fd13e6f 100644 --- a/src/builder/resources/speiger/assets/collections/templates/maps/impl/hash/OpenHashMap.template +++ b/src/builder/resources/speiger/assets/collections/templates/maps/impl/hash/OpenHashMap.template @@ -1,1509 +1,1511 @@ -package speiger.src.collections.PACKAGE.maps.impl.hash; - -import java.util.Arrays; -import java.util.ConcurrentModificationException; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Objects; -import java.util.function.Consumer; -import java.util.function.BiFunction; -import java.util.function.Predicate; -#if !TYPE_OBJECT && JDK_TYPE -import java.util.function.PREDICATE; -#endif -#if !SAME_TYPE && JDK_VALUE && !VALUE_OBJECT -import java.util.function.VALUE_PREDICATE; -#endif - -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.collections.ITERATOR; -import speiger.src.collections.PACKAGE.functions.CONSUMER; -import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; -#endif -import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER; -#if !TYPE_OBJECT && !VALUE_OBJECT -import speiger.src.collections.ints.functions.consumer.IntObjectConsumer; -#endif -#if !SAME_TYPE -import speiger.src.collections.ints.functions.consumer.VALUE_BI_FROM_INT_CONSUMER; -#endif -import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; -#if !VALUE_BOOLEAN || !JDK_TYPE -import speiger.src.collections.PACKAGE.functions.function.FUNCTION; -#endif -import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; -#if !SAME_TYPE -import speiger.src.collections.PACKAGE.functions.function.SINGLE_UNARY_OPERATOR; -#endif -#if !TYPE_OBJECT && !VALUE_BOOLEAN && !JDK_TYPE -import speiger.src.collections.PACKAGE.functions.function.PREDICATE; -#endif -import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET; -import speiger.src.collections.PACKAGE.sets.SET; -#endif -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; -import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_SUPPLIER; -#if !SAME_TYPE -import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR; - -#if !VALUE_OBJECT -#if !TYPE_OBJECT -import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator; -#endif -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; -import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER; -#endif -#else if !VALUE_OBJECT -import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator; - -#endif -#if !TYPE_OBJECT && !VALUE_OBJECT || !VALUE_OBJECT -import speiger.src.collections.objects.functions.consumer.ObjectObjectConsumer; -#endif -#if !SAME_TYPE -#if !TYPE_OBJECT -import speiger.src.collections.objects.functions.consumer.VALUE_BI_FROM_OBJECT_CONSUMER; -#endif - -#if !JDK_VALUE -import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE; -#endif -#endif -import speiger.src.collections.objects.collections.ObjectIterator; -import speiger.src.collections.objects.sets.AbstractObjectSet; -import speiger.src.collections.objects.sets.ObjectSet; -import speiger.src.collections.utils.HashUtil; -import speiger.src.collections.utils.ITrimmable; - -/** - * A Type Specific Custom implementation of the HashMap - * Instead of using Wrapper Object Arrays for storing keys and values there is dedicated arrays for storing keys and values. - * Extra to that there is a couple quality of life functions provided - * @Type(T) - * @ValueType(V) - */ -public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements ITrimmable -{ - /** The Backing keys array */ - protected transient KEY_TYPE[] keys; - /** The Backing values array */ - protected transient VALUE_TYPE[] values; - /** If a null value is present */ - protected transient boolean containsNull; - /** Minimum array size the HashMap will be */ - protected transient int minCapacity; - /** Index of the Null Value */ - protected transient int nullIndex; - /** Maximum amount of Values that can be stored before the array gets expanded usually 75% */ - protected transient int maxFill; - /** Max Index that is allowed to be searched through nullIndex - 1 */ - protected transient int mask; - /** EntrySet cache */ - protected transient FastEntrySet KEY_VALUE_GENERIC_TYPE entrySet; - /** KeySet cache */ - protected transient SET KEY_GENERIC_TYPE keySet; - /** Values cache */ - protected transient VALUE_COLLECTION VALUE_GENERIC_TYPE valuesC; - - /** Amount of Elements stored in the HashMap */ - protected int size; - /** How full the Arrays are allowed to get before resize */ - protected final float loadFactor; - - /** - * Default Constructor - */ - public HASH_MAP() { - this(HashUtil.DEFAULT_MIN_CAPACITY, HashUtil.DEFAULT_LOAD_FACTOR); - } - - /** - * Constructor that defines the minimum capacity - * @param minCapacity the minimum capacity the HashMap is allowed to be. - * @throws IllegalStateException if the minimum capacity is negative - */ - public HASH_MAP(int minCapacity) { - this(minCapacity, HashUtil.DEFAULT_LOAD_FACTOR); - } - - /** - * Constructor that defines the minimum capacity and load factor - * @param minCapacity the minimum capacity the HashMap is allowed to be. - * @param loadFactor the percentage of how full the backing array can be before they resize - * @throws IllegalStateException if the minimum capacity is negative - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - */ - public HASH_MAP(int minCapacity, float loadFactor) { - if(minCapacity < 0) throw new IllegalStateException("Minimum Capacity is negative. This is not allowed"); - if(loadFactor <= 0 || loadFactor >= 1F) throw new IllegalStateException("Load Factor is not between 0 and 1"); - this.loadFactor = loadFactor; - this.minCapacity = nullIndex = HashUtil.arraySize(minCapacity, loadFactor); - mask = nullIndex - 1; - maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1); - keys = NEW_KEY_ARRAY(nullIndex + 1); - values = NEW_VALUE_ARRAY(nullIndex + 1); - } - -#if !TYPE_OBJECT || !VALUE_OBJECT - /** - * Helper constructor that allow to create a map from boxed values (it will unbox them) - * @param keys the keys that should be put into the map - * @param values the values that should be put into the map. - * @throws IllegalStateException if the keys and values do not match in lenght - */ - public HASH_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values) { - this(keys, values, HashUtil.DEFAULT_LOAD_FACTOR); - } - - /** - * Helper constructor that allow to create a map from boxed values (it will unbox them) - * @param keys the keys that should be put into the map - * @param values the values that should be put into the map. - * @param loadFactor the percentage of how full the backing array can be before they resize - * @throws IllegalStateException if the keys and values do not match in lenght - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - */ - public HASH_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, float loadFactor) { - this(keys.length, loadFactor); - if(keys.length != values.length) throw new IllegalStateException("Input Arrays are not equal size"); - for(int i = 0,m=keys.length;i map) { - this(map, HashUtil.DEFAULT_LOAD_FACTOR); - } - - /** - * A Helper constructor that allows to create a Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - * @param loadFactor the percentage of how full the backing array can be before they resize - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - */ - public HASH_MAP(Map map, float loadFactor) { - this(map.size(), loadFactor); - putAll(map); - } - - /** - * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - */ - public HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map) { - this(map, HashUtil.DEFAULT_LOAD_FACTOR); - } - - /** - * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - * @param loadFactor the percentage of how full the backing array can be before they resize - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - */ - public HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map, float loadFactor) { - this(map.size(), loadFactor); - putAll(map); - } - - @Override - public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { - int slot = findIndex(key); - if(slot < 0) { - insert(-slot-1, key, value); - return getDefaultReturnValue(); - } - VALUE_TYPE oldValue = values[slot]; - values[slot] = value; - return oldValue; - } - - @Override - public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { - int slot = findIndex(key); - if(slot < 0) { - insert(-slot-1, key, value); - return getDefaultReturnValue(); - } - else if(VALUE_EQUALS(values[slot], getDefaultReturnValue())) { - VALUE_TYPE oldValue = values[slot]; - values[slot] = value; - return oldValue; - } - return values[slot]; - } - -#if VALUE_PRIMITIVES - @Override - public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { - int slot = findIndex(key); - if(slot < 0) { - insert(-slot-1, key, value); - return getDefaultReturnValue(); - } - VALUE_TYPE oldValue = values[slot]; - values[slot] += value; - return oldValue; - } - - @Override - public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { - int slot = findIndex(key); - if(slot < 0) return getDefaultReturnValue(); - VALUE_TYPE oldValue = values[slot]; - values[slot] -= value; - if(value < 0 ? (values[slot] >= getDefaultReturnValue()) : (values[slot] <= getDefaultReturnValue())) removeIndex(slot); - return oldValue; - } -#endif -#if !TYPE_OBJECT - @Override - public boolean containsKey(KEY_TYPE key) { - return findIndex(key) >= 0; - } - -#endif - @Override - @Primitive - public boolean containsKey(Object key) { - return findIndex(key) >= 0; - } - -#if !VALUE_OBJECT - @Override - public boolean containsValue(VALUE_TYPE value) { - if(containsNull && VALUE_EQUALS(values[nullIndex], value)) return true; - for(int i = nullIndex-1;i >= 0;i--) - if(KEY_EQUALS_NOT_NULL(keys[i]) && VALUE_EQUALS(values[i], value)) return true; - return false; - } - -#endif - @Override - @ValuePrimitive - public boolean containsValue(Object value) { -#if VALUE_OBJECT - if(containsNull && VALUE_EQUALS(values[nullIndex], value)) return true; -#else - if(containsNull && ((value == null && values[nullIndex] == getDefaultReturnValue()) || EQUALS_VALUE_TYPE(values[nullIndex], value))) return true; -#endif - for(int i = nullIndex-1;i >= 0;i--) -#if VALUE_OBJECT - if(KEY_EQUALS_NOT_NULL(keys[i]) && EQUALS_VALUE_TYPE(values[i], value)) return true; -#else - if(KEY_EQUALS_NOT_NULL(keys[i]) && ((value == null && values[i] == getDefaultReturnValue()) || EQUALS_VALUE_TYPE(values[i], value))) return true; -#endif - return false; - } - - @Override - public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { - int slot = findIndex(key); - if(slot < 0) return getDefaultReturnValue(); - return removeIndex(slot); - } - - @Override - public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { - int slot = findIndex(key); - if(slot < 0) return defaultValue; - return removeIndex(slot); - } - - @Override - public CLASS_VALUE_TYPE remove(Object key) { - int slot = findIndex(key); - if(slot < 0) return VALUE_TO_OBJ(getDefaultReturnValue()); - return removeIndex(slot); - } - -#if !TYPE_OBJECT || !VALUE_OBJECT - @Override - public boolean remove(KEY_TYPE key, VALUE_TYPE value) { - if(KEY_EQUALS_NULL(key)) { - if(containsNull && VALUE_EQUALS(value, values[nullIndex])) { - removeNullIndex(); - return true; - } - return false; - } - int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask; - KEY_TYPE current = keys[pos]; - if(KEY_EQUALS_NULL(current)) return false; - if(KEY_EQUALS(current, key) && VALUE_EQUALS(value, values[pos])) { - removeIndex(pos); - return true; - } - while(true) { - if(KEY_EQUALS_NULL((current = keys[pos = (++pos & mask)]))) return false; - else if(KEY_EQUALS(current, key) && VALUE_EQUALS(value, values[pos])) { - removeIndex(pos); - return true; - } - } - } - -#endif - @Override - public boolean remove(Object key, Object value) { - Objects.requireNonNull(value); -#if TYPE_OBJECT - if(key == null) { -#else - if(key == null || (key instanceof CLASS_TYPE && KEY_EQUALS_NULL(CLASS_TO_KEY(key)))) { -#endif - if(containsNull && EQUALS_VALUE_TYPE(values[nullIndex], value)) { - removeNullIndex(); - return true; - } - return false; - } - int pos = HashUtil.mix(key.hashCode()) & mask; - KEY_TYPE current = keys[pos]; - if(KEY_EQUALS_NULL(current)) return false; - if(EQUALS_KEY_TYPE(current, key) && EQUALS_VALUE_TYPE(values[pos], value)) { - removeIndex(pos); - return true; - } - while(true) { - if(KEY_EQUALS_NULL((current = keys[pos = (++pos & mask)]))) return false; - else if(EQUALS_KEY_TYPE(current, key) && EQUALS_VALUE_TYPE(values[pos], value)){ - removeIndex(pos); - return true; - } - } - } - - @Override - public VALUE_TYPE GET_VALUE(KEY_TYPE key) { - int slot = findIndex(key); - return slot < 0 ? getDefaultReturnValue() : values[slot]; - } - - @Override - public CLASS_VALUE_TYPE get(Object key) { - int slot = findIndex(key); - return VALUE_TO_OBJ(slot < 0 ? getDefaultReturnValue() : values[slot]); - } - -#if TYPE_OBJECT && VALUE_OBJECT - @Override - public VALUE_TYPE getOrDefault(Object key, VALUE_TYPE defaultValue) { - int slot = findIndex(key); - return slot < 0 ? defaultValue : values[slot]; - } - -#else - @Override - public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { - int slot = findIndex(key); - return slot < 0 ? defaultValue : values[slot]; - } - -#endif - @Override - public HASH_MAP KEY_VALUE_GENERIC_TYPE copy() { - HASH_MAP KEY_VALUE_GENERIC_TYPE map = new HASH_MAPKV_BRACES(0, loadFactor); - map.minCapacity = minCapacity; - map.mask = mask; - map.maxFill = maxFill; - map.nullIndex = nullIndex; - map.containsNull = containsNull; - map.size = size; - map.keys = Arrays.copyOf(keys, keys.length); - map.values = Arrays.copyOf(values, values.length); - return map; - } - - @Override - public ObjectSet ENTRY_SET() { - if(entrySet == null) entrySet = new MapEntrySet(); - return entrySet; - } - - @Override - public SET KEY_GENERIC_TYPE keySet() { - if(keySet == null) keySet = new KeySet(); - return keySet; - } - - @Override - public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { - if(valuesC == null) valuesC = new Values(); - return valuesC; - } - - @Override - public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { - if(size() <= 0) return; - if(containsNull) action.accept(keys[nullIndex], values[nullIndex]); - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(keys[i], values[i]); - } - } - - @Override - public boolean replace(KEY_TYPE key, VALUE_TYPE oldValue, VALUE_TYPE newValue) { - int index = findIndex(key); - if(index < 0 || values[index] != oldValue) return false; - values[index] = newValue; - return true; - } - - @Override - public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value) { - int index = findIndex(key); - if(index < 0) return getDefaultReturnValue(); - VALUE_TYPE oldValue = values[index]; - values[index] = value; - return oldValue; - } - - @Override - public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); - int index = findIndex(key); - if(index < 0) { - VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, getDefaultReturnValue()); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - insert(-index-1, key, newValue); - return newValue; - } - VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, values[index]); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - removeIndex(index); - return newValue; - } - values[index] = newValue; - return newValue; - } - - @Override - public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); - int index = findIndex(key); - if(index < 0) { - VALUE_TYPE newValue = mappingFunction.APPLY(key); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - insert(-index-1, key, newValue); - return newValue; - } - VALUE_TYPE newValue = values[index]; - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - newValue = mappingFunction.APPLY(key); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - values[index] = newValue; - } - return newValue; - } - - @Override - public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) { - Objects.requireNonNull(valueProvider); - int index = findIndex(key); - if(index < 0) { - VALUE_TYPE newValue = valueProvider.VALUE_SUPPLY_GET(); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - insert(-index-1, key, newValue); - return newValue; - } - VALUE_TYPE newValue = values[index]; - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - newValue = valueProvider.VALUE_SUPPLY_GET(); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - values[index] = newValue; - } - return newValue; - } - - @Override - public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); - int index = findIndex(key); - if(index < 0 || VALUE_EQUALS(values[index], getDefaultReturnValue())) return getDefaultReturnValue(); - VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, values[index]); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - removeIndex(index); - return newValue; - } - values[index] = newValue; - return newValue; - } - - @Override - public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); -#if VALUE_OBJECT - Objects.requireNonNull(value); -#endif - int index = findIndex(key); - VALUE_TYPE newValue = index < 0 || VALUE_EQUALS(values[index], getDefaultReturnValue()) ? value : mappingFunction.APPLY_VALUE(values[index], value); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - if(index >= 0) - removeIndex(index); - } - else if(index < 0) insert(-index-1, key, newValue); - else values[index] = newValue; - return newValue; - } - - @Override - public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); - for(MAP.Entry KEY_VALUE_GENERIC_TYPE entry : getFastIterable(m)) { - KEY_TYPE key = entry.ENTRY_KEY(); - int index = findIndex(key); - VALUE_TYPE newValue = index < 0 || VALUE_EQUALS(values[index], getDefaultReturnValue()) ? entry.ENTRY_VALUE() : mappingFunction.APPLY_VALUE(values[index], entry.ENTRY_VALUE()); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - if(index >= 0) - removeIndex(index); - } - else if(index < 0) insert(-index-1, key, newValue); - else values[index] = newValue; - } - } - - @Override - public int size() { return size; } - - @Override - public void clear() { - if(size == 0) return; - size = 0; - containsNull = false; - Arrays.fill(keys, EMPTY_KEY_VALUE); - Arrays.fill(values, EMPTY_VALUE); - } - - @Override - public boolean trim(int size) { - int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor))); - if(request >= nullIndex || this.size >= Math.min((int)Math.ceil(request * loadFactor), request - 1)) return false; - try { - rehash(request); - } - catch(OutOfMemoryError noMemory) { return false; } - return true; - } - - @Override - public void clearAndTrim(int size) { - int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor))); - if(request >= nullIndex) { - clear(); - return; - } - nullIndex = request; - mask = request-1; - maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1); - keys = NEW_KEY_ARRAY(request + 1); - values = NEW_VALUE_ARRAY(request + 1); - this.size = 0; - containsNull = false; - } - -#if !TYPE_OBJECT - protected int findIndex(KEY_TYPE key) { - if(KEY_EQUALS_NULL(key)) return containsNull ? nullIndex : -(nullIndex + 1); - int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask; - KEY_TYPE current = keys[pos]; - if(KEY_EQUALS_NOT_NULL(current)) { - if(KEY_EQUALS(current, key)) return pos; - while(KEY_EQUALS_NOT_NULL((current = keys[pos = (++pos & mask)]))) - if(KEY_EQUALS(current, key)) return pos; - } - return -(pos + 1); - } - -#endif - protected int findIndex(Object key) { - if(key == null) return containsNull ? nullIndex : -(nullIndex + 1); -#if !TYPE_OBJECT - if(key instanceof CLASS_TYPE && KEY_EQUALS_NULL(CLASS_TO_KEY(key))) return containsNull ? nullIndex : -(nullIndex + 1); -#endif - int pos = HashUtil.mix(key.hashCode()) & mask; - KEY_TYPE current = keys[pos]; - if(KEY_EQUALS_NOT_NULL(current)) { - if(EQUALS_KEY_TYPE(current, key)) return pos; - while(KEY_EQUALS_NOT_NULL((current = keys[pos = (++pos & mask)]))) - if(EQUALS_KEY_TYPE(current, key)) return pos; - } - return -(pos + 1); - } - - protected VALUE_TYPE removeIndex(int pos) { - if(pos == nullIndex) return containsNull ? removeNullIndex() : getDefaultReturnValue(); - VALUE_TYPE value = values[pos]; - keys[pos] = EMPTY_KEY_VALUE; - values[pos] = EMPTY_VALUE; - size--; - onNodeRemoved(pos); - shiftKeys(pos); - if(nullIndex > minCapacity && size < maxFill / 4 && nullIndex > HashUtil.DEFAULT_MIN_CAPACITY) rehash(nullIndex / 2); - return value; - } - - protected VALUE_TYPE removeNullIndex() { - VALUE_TYPE value = values[nullIndex]; - containsNull = false; - keys[nullIndex] = EMPTY_KEY_VALUE; - values[nullIndex] = EMPTY_VALUE; - size--; - onNodeRemoved(nullIndex); - if(nullIndex > minCapacity && size < maxFill / 4 && nullIndex > HashUtil.DEFAULT_MIN_CAPACITY) rehash(nullIndex / 2); - return value; - } - - protected void insert(int slot, KEY_TYPE key, VALUE_TYPE value) { - if(slot == nullIndex) containsNull = true; - keys[slot] = key; - values[slot] = value; - onNodeAdded(slot); - if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor)); - } - - protected void rehash(int newSize) { - int newMask = newSize - 1; - KEY_TYPE[] newKeys = NEW_KEY_ARRAY(newSize + 1); - VALUE_TYPE[] newValues = NEW_VALUE_ARRAY(newSize + 1); - for(int i = nullIndex, pos = 0, j = (size - (containsNull ? 1 : 0));j-- != 0;) { - while(true) { - if(--i < 0) throw new ConcurrentModificationException("Map was modified during rehash"); - if(KEY_EQUALS_NOT_NULL(keys[i])) break; - } - if(KEY_EQUALS_NOT_NULL(newKeys[pos = HashUtil.mix(KEY_TO_HASH(keys[i])) & newMask])) - while(KEY_EQUALS_NOT_NULL(newKeys[pos = (++pos & newMask)])); - newKeys[pos] = keys[i]; - newValues[pos] = values[i]; - } - newValues[newSize] = values[nullIndex]; - nullIndex = newSize; - mask = newMask; - maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1); - keys = newKeys; - values = newValues; - } - - protected void onNodeAdded(int pos) { - - } - - protected void onNodeRemoved(int pos) { - - } - - protected void onNodeMoved(int from, int to) { - - } - - protected void shiftKeys(int startPos) { - int slot, last; - KEY_TYPE current; - while(true) { - startPos = ((last = startPos) + 1) & mask; - while(true){ - if(KEY_EQUALS_NULL((current = keys[startPos]))) { - keys[last] = EMPTY_KEY_VALUE; - values[last] = EMPTY_VALUE; - return; - } - slot = HashUtil.mix(KEY_TO_HASH(current)) & mask; - if(last <= startPos ? (last >= slot || slot > startPos) : (last >= slot && slot > startPos)) break; - startPos = ++startPos & mask; - } - keys[last] = current; - values[last] = values[startPos]; - onNodeMoved(startPos, last); - } - } - - protected class MapEntry implements MAP.Entry KEY_VALUE_GENERIC_TYPE, Map.Entry { - public int index = -1; - - public MapEntry() {} - public MapEntry(int index) { - this.index = index; - } - - @Override - public KEY_TYPE ENTRY_KEY() { - return keys[index]; - } - - @Override - public VALUE_TYPE ENTRY_VALUE() { - return values[index]; - } - - @Override - public VALUE_TYPE setValue(VALUE_TYPE value) { - VALUE_TYPE oldValue = values[index]; - values[index] = value; - return oldValue; - } - - @Override - public boolean equals(Object obj) { - if(obj instanceof Map.Entry) { - if(obj instanceof MAP.Entry) { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)obj; - return KEY_EQUALS(keys[index], entry.ENTRY_KEY()) && VALUE_EQUALS(values[index], entry.ENTRY_VALUE()); - } - Map.Entry entry = (Map.Entry)obj; - Object key = entry.getKey(); - Object value = entry.getValue(); -#if TYPE_OBJECT && VALUE_OBJECT - return KEY_EQUALS(keys[index], key) && VALUE_EQUALS(values[index], value); -#else if TYPE_OBJECT - return value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(keys[index], key) && VALUE_EQUALS(values[index], CLASS_TO_VALUE(value)); -#else if VALUE_OBJECT - return key instanceof CLASS_TYPE && KEY_EQUALS(keys[index], CLASS_TO_KEY(key)) && VALUE_EQUALS(values[index], value); -#else - return key instanceof CLASS_TYPE && value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(keys[index], CLASS_TO_KEY(key)) && VALUE_EQUALS(values[index], CLASS_TO_VALUE(value)); -#endif - } - return false; - } - - @Override - public int hashCode() { - return KEY_TO_HASH(keys[index]) ^ VALUE_TO_HASH(values[index]); - } - - @Override - public String toString() { - return KEY_TO_STRING(keys[index]) + "=" + VALUE_TO_STRING(values[index]); - } - } - - private final class MapEntrySet extends AbstractObjectSet implements MAP.FastEntrySet KEY_VALUE_GENERIC_TYPE { - @Override - public ObjectIterator fastIterator() { - return new FastEntryIterator(); - } - - @Override - public ObjectIterator iterator() { - return new EntryIterator(); - } - - @Override - public void forEach(Consumer action) { - if(containsNull) action.accept(new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex])); - for(int i = nullIndex-1;i>=0;i--) - if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(new BasicEntryKV_BRACES(keys[i], values[i])); - } - - @Override - public void fastForEach(Consumer action) { - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - if(containsNull) { - entry.set(keys[nullIndex], values[nullIndex]); - action.accept(entry); - } - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NOT_NULL(keys[i])) { - entry.set(keys[i], values[i]); - action.accept(entry); - } - } - } - - @Override - public void forEachIndexed(IntObjectConsumer action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - if(containsNull) action.accept(0, new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex])); - for(int i = nullIndex-1, index = containsNull ? 1 : 0;i>=0;i--) { - if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(index++, new BasicEntryKV_BRACES(keys[i], values[i])); - } - } - - @Override - public void forEach(E input, ObjectObjectConsumer action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - if(containsNull) action.accept(input, new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex])); - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(input, new BasicEntryKV_BRACES(keys[i], values[i])); - } - } - - @Override - public boolean matchesAny(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return false; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - if(containsNull) { - entry.set(keys[nullIndex], values[nullIndex]); - if(filter.test(entry)) return true; - } - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NOT_NULL(keys[i])) { - entry.set(keys[i], values[i]); - if(filter.test(entry)) return true; - } - } - return false; - } - - @Override - public boolean matchesNone(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - if(containsNull) { - entry.set(keys[nullIndex], values[nullIndex]); - if(filter.test(entry)) return false; - } - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NOT_NULL(keys[i])) { - entry.set(keys[i], values[i]); - if(filter.test(entry)) return false; - } - } - return true; - } - - @Override - public boolean matchesAll(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - if(containsNull) { - entry.set(keys[nullIndex], values[nullIndex]); - if(!filter.test(entry)) return false; - } - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NOT_NULL(keys[i])) { - entry.set(keys[i], values[i]); - if(!filter.test(entry)) return false; - } - } - return true; - } - - @Override - public E reduce(E identity, BiFunction operator) { - Objects.requireNonNull(operator); - E state = identity; - if(containsNull) state = operator.apply(state, new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex])); - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NULL(keys[i])) continue; - state = operator.apply(state, new BasicEntryKV_BRACES(keys[i], values[i])); - } - return state; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE reduce(ObjectObjectUnaryOperator operator) { - Objects.requireNonNull(operator); - MAP.Entry KEY_VALUE_GENERIC_TYPE state = null; - boolean empty = true; - if(containsNull) { - state = new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex]); - empty = false; - } - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NULL(keys[i])) continue; - if(empty) { - empty = false; - state = new BasicEntryKV_BRACES(keys[i], values[i]); - continue; - } - state = operator.apply(state, new BasicEntryKV_BRACES(keys[i], values[i])); - } - return state; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE findFirst(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return null; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - if(containsNull) { - entry.set(keys[nullIndex], values[nullIndex]); - if(filter.test(entry)) return entry; - } - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NOT_NULL(keys[i])) { - entry.set(keys[i], values[i]); - if(filter.test(entry)) return entry; - } - } - return null; - } - - @Override - public int count(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return 0; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - int result = 0; - if(containsNull) { - entry.set(keys[nullIndex], values[nullIndex]); - if(filter.test(entry)) result++; - } - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NOT_NULL(keys[i])) { - entry.set(keys[i], values[i]); - if(filter.test(entry)) result++; - } - } - return result; - } - - @Override - public int size() { - return HASH_MAP.this.size(); - } - - @Override - public void clear() { - HASH_MAP.this.clear(); - } - - @Override - public boolean contains(Object o) { - if(o instanceof Map.Entry) { - if(o instanceof MAP.Entry) { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; - int index = HASH_MAP.this.findIndex(entry.ENTRY_KEY()); - if(index >= 0) return VALUE_EQUALS(entry.ENTRY_VALUE(), HASH_MAP.this.values[index]); - } - else { - Map.Entry entry = (Map.Entry)o; - int index = HASH_MAP.this.findIndex(entry.getKey()); - if(index >= 0) return Objects.equals(entry.getValue(), VALUE_TO_OBJ(HASH_MAP.this.values[index])); - } - } - return false; - } - - @Override - public boolean remove(Object o) { - if(o instanceof Map.Entry) { - if(o instanceof MAP.Entry) { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; - return HASH_MAP.this.remove(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); - } - Map.Entry entry = (Map.Entry)o; - return HASH_MAP.this.remove(entry.getKey(), entry.getValue()); - } - return false; - } - } - - private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE { -#if TYPE_OBJECT - @Override - public boolean contains(Object e) { - return containsKey(e); - } - - @Override - public boolean remove(Object o) { - int oldSize = size; - HASH_MAP.this.remove(o); - return size != oldSize; - } - -#else - @Override - public boolean contains(KEY_TYPE e) { - return containsKey(e); - } - - @Override - public boolean remove(KEY_TYPE o) { - int oldSize = size; - HASH_MAP.this.remove(o); - return size != oldSize; - } - -#endif - @Override - public boolean add(KEY_TYPE o) { - throw new UnsupportedOperationException(); - } - - @Override - public ITERATOR KEY_GENERIC_TYPE iterator() { - return new KeyIterator(); - } - - @Override - public int size() { - return HASH_MAP.this.size(); - } - - @Override - public void clear() { - HASH_MAP.this.clear(); - } - - @Override - public KeySet copy() { throw new UnsupportedOperationException(); } - - @Override - public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { - if(containsNull) action.accept(keys[nullIndex]); - for(int i = nullIndex-1;i>=0;i--) - if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(keys[i]); - } - - @Override - public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - if(containsNull) action.accept(0, keys[nullIndex]); - for(int i = nullIndex-1, index = containsNull ? 1 : 0;i>=0;i--) { - if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(index++, keys[i]); - } - } - - @Override - public void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - if(containsNull) action.accept(input, keys[nullIndex]); - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(input, keys[i]); - } - } - - @Override - public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return false; - if(containsNull && filter.test(keys[nullIndex])) return true; - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.test(keys[i])) return true; - } - return false; - } - - @Override - public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - if(containsNull && filter.test(keys[nullIndex])) return false; - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.test(keys[i])) return false; - } - return true; - } - - @Override - public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - if(containsNull && !filter.test(keys[nullIndex])) return false; - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NOT_NULL(keys[i]) && !filter.test(keys[i])) return false; - } - return true; - } - -#if !TYPE_OBJECT - @Override - public KEY_TYPE reduce(KEY_TYPE identity, SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - KEY_TYPE state = identity; - if(containsNull) state = operator.APPLY_KEY_VALUE(state, keys[nullIndex]); - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NULL(keys[i])) continue; - state = operator.APPLY_KEY_VALUE(state, keys[i]); - } - return state; - } - -#else - @Override - public KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) { - Objects.requireNonNull(operator); - KEY_SPECIAL_TYPE state = identity; - if(containsNull) state = operator.apply(state, keys[nullIndex]); - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NULL(keys[i])) continue; - state = operator.apply(state, keys[i]); - } - return state; - } - -#endif - @Override - public KEY_TYPE reduce(SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - KEY_TYPE state = EMPTY_KEY_VALUE; - boolean empty = true; - if(containsNull) { - state = keys[nullIndex]; - empty = false; - } - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NULL(keys[i])) continue; - if(empty) { - empty = false; - state = keys[i]; - continue; - } - state = operator.APPLY_KEY_VALUE(state, keys[i]); - } - return state; - } - - @Override - public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return EMPTY_KEY_VALUE; - if(containsNull && filter.test(keys[nullIndex])) return keys[nullIndex]; - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.test(keys[i])) return keys[i]; - } - return EMPTY_KEY_VALUE; - } - - @Override - public int count(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return 0; - int result = 0; - if(containsNull && filter.test(keys[nullIndex])) result++; - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.test(keys[i])) result++; - } - return result; - } - } - - private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { -#if VALUE_OBJECT - @Override - public boolean contains(Object e) { - return containsValue(e); - } - -#else - @Override - public boolean contains(VALUE_TYPE e) { - return containsValue(e); - } - -#endif - @Override - public boolean add(VALUE_TYPE o) { - throw new UnsupportedOperationException(); - } - - @Override - public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() { - return new ValueIterator(); - } - - @Override - public int size() { - return HASH_MAP.this.size(); - } - - @Override - public void clear() { - HASH_MAP.this.clear(); - } - - @Override - public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) { - if(containsNull) action.accept(values[nullIndex]); - for(int i = nullIndex-1;i>=0;i--) - if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(values[i]); - } - - @Override - public void forEachIndexed(VALUE_BI_FROM_INT_CONSUMER VALUE_GENERIC_TYPE action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - if(containsNull) action.accept(0, values[nullIndex]); - for(int i = nullIndex-1, index = containsNull ? 1 : 0;i>=0;i--) { - if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(index++, values[i]); - } - } - - @Override - public void forEach(E input, VALUE_BI_FROM_OBJECT_CONSUMER VSV_GENERIC_TYPE action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - if(containsNull) action.accept(input, values[nullIndex]); - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(input, values[i]); - } - } - - @Override - public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return false; - if(containsNull && filter.test(values[nullIndex])) return true; - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.test(values[i])) return true; - } - return false; - } - - @Override - public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - if(containsNull && filter.test(values[nullIndex])) return false; - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.test(values[i])) return false; - } - return true; - } - - @Override - public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - if(containsNull && !filter.test(values[nullIndex])) return false; - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NOT_NULL(keys[i]) && !filter.test(values[i])) return false; - } - return true; - } - -#if !VALUE_OBJECT - @Override - public VALUE_TYPE reduce(VALUE_TYPE identity, VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - VALUE_TYPE state = identity; - if(containsNull) state = operator.APPLY_VALUE(state, values[nullIndex]); - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NULL(keys[i])) continue; - state = operator.APPLY_VALUE(state, values[i]); - } - return state; - } - -#else - @Override - public VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction operator) { - Objects.requireNonNull(operator); - VALUE_SPECIAL_TYPE state = identity; - if(containsNull) state = operator.APPLY_VALUE(state, values[nullIndex]); - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NULL(keys[i])) continue; - state = operator.APPLY_VALUE(state, values[i]); - } - return state; - } - -#endif - @Override - public VALUE_TYPE reduce(VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - VALUE_TYPE state = EMPTY_VALUE; - boolean empty = true; - if(containsNull) { - state = values[nullIndex]; - empty = false; - } - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NULL(keys[i])) continue; - if(empty) { - empty = false; - state = values[i]; - continue; - } - state = operator.APPLY_VALUE(state, values[i]); - } - return state; - } - - @Override - public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return EMPTY_VALUE; - if(containsNull && filter.test(values[nullIndex])) return values[nullIndex]; - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.test(values[i])) return values[i]; - } - return EMPTY_VALUE; - } - - @Override - public int count(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return 0; - int result = 0; - if(containsNull && filter.test(values[nullIndex])) result++; - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.test(values[i])) result++; - } - return result; - } - } - - private class FastEntryIterator extends MapIterator implements ObjectIterator { - MapEntry entry = new MapEntry(); - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { - entry.index = nextEntry(); - return entry; - } - } - - private class EntryIterator extends MapIterator implements ObjectIterator { - MapEntry entry; - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { - return entry = new MapEntry(nextEntry()); - } - - @Override - public void remove() { - super.remove(); - entry.index = -1; - } - } - - private class KeyIterator extends MapIterator implements ITERATOR KEY_GENERIC_TYPE { - @Override - public KEY_TYPE NEXT() { - return keys[nextEntry()]; - } - } - - private class ValueIterator extends MapIterator implements VALUE_ITERATOR VALUE_GENERIC_TYPE { - @Override - public VALUE_TYPE VALUE_NEXT() { - return values[nextEntry()]; - } - } - - private class MapIterator { - int pos = nullIndex; - int returnedPos = -1; - int lastReturned = -1; - int nextIndex = Integer.MIN_VALUE; - boolean returnNull = containsNull; - KEY_TYPE[] wrapped = null; - int wrappedIndex = 0; - - public boolean hasNext() { - if(nextIndex == Integer.MIN_VALUE) { - if(returnNull) { - returnNull = false; - nextIndex = nullIndex; - } - else - { - while(true) { - if(--pos < 0) { - if(wrapped == null || wrappedIndex <= -pos - 1) break; - nextIndex = -pos - 1; - break; - } - if(KEY_EQUALS_NOT_NULL(keys[pos])){ - nextIndex = pos; - break; - } - } - } - } - return nextIndex != Integer.MIN_VALUE; - } - - public int nextEntry() { - if(!hasNext()) throw new NoSuchElementException(); - returnedPos = pos; - if(nextIndex < 0){ - lastReturned = Integer.MAX_VALUE; - int value = findIndex(wrapped[nextIndex]); - if(value < 0) throw new IllegalStateException("Entry ["+nextIndex+"] was removed during Iteration"); - nextIndex = Integer.MIN_VALUE; - return value; - } - int value = (lastReturned = nextIndex); - nextIndex = Integer.MIN_VALUE; - return value; - } - - public void remove() { - if(lastReturned == -1) throw new IllegalStateException(); - if(lastReturned == nullIndex) { - containsNull = false; - keys[nullIndex] = EMPTY_KEY_VALUE; - values[nullIndex] = EMPTY_VALUE; - } - else if(returnedPos >= 0) shiftKeys(returnedPos); - else { - HASH_MAP.this.remove(wrapped[-returnedPos - 1]); - lastReturned = -1; - return; - } - size--; - lastReturned = -1; - } - - private void shiftKeys(int startPos) { - int slot, last; - KEY_TYPE current; - while(true) { - startPos = ((last = startPos) + 1) & mask; - while(true){ - if(KEY_EQUALS_NULL((current = keys[startPos]))) { - keys[last] = EMPTY_KEY_VALUE; - values[last] = EMPTY_VALUE; - return; - } - slot = HashUtil.mix(KEY_TO_HASH(current)) & mask; - if(last <= startPos ? (last >= slot || slot > startPos) : (last >= slot && slot > startPos)) break; - startPos = ++startPos & mask; - } - if(startPos < last) addWrapper(keys[startPos]); - keys[last] = current; - values[last] = values[startPos]; - } - } - - private void addWrapper(KEY_TYPE value) { - if(wrapped == null) wrapped = NEW_KEY_ARRAY(2); - else if(wrappedIndex >= wrapped.length) { - KEY_TYPE[] newArray = NEW_KEY_ARRAY(wrapped.length * 2); - System.arraycopy(wrapped, 0, newArray, 0, wrapped.length); - wrapped = newArray; - } - wrapped[wrappedIndex++] = value; - } - } +package speiger.src.collections.PACKAGE.maps.impl.hash; + +import java.util.Arrays; +import java.util.ConcurrentModificationException; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Objects; +import java.util.function.Consumer; +import java.util.function.BiFunction; +import java.util.function.Predicate; +#if !TYPE_OBJECT && JDK_TYPE +import java.util.function.PREDICATE; +#endif +#if !SAME_TYPE && JDK_VALUE && !VALUE_OBJECT +import java.util.function.VALUE_PREDICATE; +#endif + +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.collections.ITERATOR; +import speiger.src.collections.PACKAGE.functions.CONSUMER; +import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; +#endif +import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER; +#if !TYPE_OBJECT && !VALUE_OBJECT +import speiger.src.collections.ints.functions.consumer.IntObjectConsumer; +#endif +#if !SAME_TYPE && !TYPE_INT +import speiger.src.collections.ints.functions.consumer.VALUE_BI_FROM_INT_CONSUMER; +#endif +#if !TYPE_INT || !SAME_TYPE +import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; +#endif +#if !VALUE_BOOLEAN || !JDK_TYPE +import speiger.src.collections.PACKAGE.functions.function.FUNCTION; +#endif +import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; +#if !SAME_TYPE +import speiger.src.collections.PACKAGE.functions.function.SINGLE_UNARY_OPERATOR; +#endif +#if !TYPE_OBJECT && !VALUE_BOOLEAN && !JDK_TYPE +import speiger.src.collections.PACKAGE.functions.function.PREDICATE; +#endif +import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET; +import speiger.src.collections.PACKAGE.sets.SET; +#endif +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; +import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_SUPPLIER; +#if !SAME_TYPE +import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR; + +#if !VALUE_OBJECT +#if !TYPE_OBJECT +import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator; +#endif +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; +import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER; +#endif +#else if !VALUE_OBJECT +import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator; + +#endif +#if !TYPE_OBJECT && !VALUE_OBJECT || !VALUE_OBJECT +import speiger.src.collections.objects.functions.consumer.ObjectObjectConsumer; +#endif +#if !SAME_TYPE +#if !TYPE_OBJECT +import speiger.src.collections.objects.functions.consumer.VALUE_BI_FROM_OBJECT_CONSUMER; +#endif + +#if !JDK_VALUE +import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE; +#endif +#endif +import speiger.src.collections.objects.collections.ObjectIterator; +import speiger.src.collections.objects.sets.AbstractObjectSet; +import speiger.src.collections.objects.sets.ObjectSet; +import speiger.src.collections.utils.HashUtil; +import speiger.src.collections.utils.ITrimmable; + +/** + * A Type Specific Custom implementation of the HashMap + * Instead of using Wrapper Object Arrays for storing keys and values there is dedicated arrays for storing keys and values. + * Extra to that there is a couple quality of life functions provided + * @Type(T) + * @ValueType(V) + */ +public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements ITrimmable +{ + /** The Backing keys array */ + protected transient KEY_TYPE[] keys; + /** The Backing values array */ + protected transient VALUE_TYPE[] values; + /** If a null value is present */ + protected transient boolean containsNull; + /** Minimum array size the HashMap will be */ + protected transient int minCapacity; + /** Index of the Null Value */ + protected transient int nullIndex; + /** Maximum amount of Values that can be stored before the array gets expanded usually 75% */ + protected transient int maxFill; + /** Max Index that is allowed to be searched through nullIndex - 1 */ + protected transient int mask; + /** EntrySet cache */ + protected transient FastEntrySet KEY_VALUE_GENERIC_TYPE entrySet; + /** KeySet cache */ + protected transient SET KEY_GENERIC_TYPE keySet; + /** Values cache */ + protected transient VALUE_COLLECTION VALUE_GENERIC_TYPE valuesC; + + /** Amount of Elements stored in the HashMap */ + protected int size; + /** How full the Arrays are allowed to get before resize */ + protected final float loadFactor; + + /** + * Default Constructor + */ + public HASH_MAP() { + this(HashUtil.DEFAULT_MIN_CAPACITY, HashUtil.DEFAULT_LOAD_FACTOR); + } + + /** + * Constructor that defines the minimum capacity + * @param minCapacity the minimum capacity the HashMap is allowed to be. + * @throws IllegalStateException if the minimum capacity is negative + */ + public HASH_MAP(int minCapacity) { + this(minCapacity, HashUtil.DEFAULT_LOAD_FACTOR); + } + + /** + * Constructor that defines the minimum capacity and load factor + * @param minCapacity the minimum capacity the HashMap is allowed to be. + * @param loadFactor the percentage of how full the backing array can be before they resize + * @throws IllegalStateException if the minimum capacity is negative + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + */ + public HASH_MAP(int minCapacity, float loadFactor) { + if(minCapacity < 0) throw new IllegalStateException("Minimum Capacity is negative. This is not allowed"); + if(loadFactor <= 0 || loadFactor >= 1F) throw new IllegalStateException("Load Factor is not between 0 and 1"); + this.loadFactor = loadFactor; + this.minCapacity = nullIndex = HashUtil.arraySize(minCapacity, loadFactor); + mask = nullIndex - 1; + maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1); + keys = NEW_KEY_ARRAY(nullIndex + 1); + values = NEW_VALUE_ARRAY(nullIndex + 1); + } + +#if !TYPE_OBJECT || !VALUE_OBJECT + /** + * Helper constructor that allow to create a map from boxed values (it will unbox them) + * @param keys the keys that should be put into the map + * @param values the values that should be put into the map. + * @throws IllegalStateException if the keys and values do not match in lenght + */ + public HASH_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values) { + this(keys, values, HashUtil.DEFAULT_LOAD_FACTOR); + } + + /** + * Helper constructor that allow to create a map from boxed values (it will unbox them) + * @param keys the keys that should be put into the map + * @param values the values that should be put into the map. + * @param loadFactor the percentage of how full the backing array can be before they resize + * @throws IllegalStateException if the keys and values do not match in lenght + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + */ + public HASH_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, float loadFactor) { + this(keys.length, loadFactor); + if(keys.length != values.length) throw new IllegalStateException("Input Arrays are not equal size"); + for(int i = 0,m=keys.length;i map) { + this(map, HashUtil.DEFAULT_LOAD_FACTOR); + } + + /** + * A Helper constructor that allows to create a Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + * @param loadFactor the percentage of how full the backing array can be before they resize + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + */ + public HASH_MAP(Map map, float loadFactor) { + this(map.size(), loadFactor); + putAll(map); + } + + /** + * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + */ + public HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map) { + this(map, HashUtil.DEFAULT_LOAD_FACTOR); + } + + /** + * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + * @param loadFactor the percentage of how full the backing array can be before they resize + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + */ + public HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map, float loadFactor) { + this(map.size(), loadFactor); + putAll(map); + } + + @Override + public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { + int slot = findIndex(key); + if(slot < 0) { + insert(-slot-1, key, value); + return getDefaultReturnValue(); + } + VALUE_TYPE oldValue = values[slot]; + values[slot] = value; + return oldValue; + } + + @Override + public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { + int slot = findIndex(key); + if(slot < 0) { + insert(-slot-1, key, value); + return getDefaultReturnValue(); + } + else if(VALUE_EQUALS(values[slot], getDefaultReturnValue())) { + VALUE_TYPE oldValue = values[slot]; + values[slot] = value; + return oldValue; + } + return values[slot]; + } + +#if VALUE_PRIMITIVES + @Override + public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { + int slot = findIndex(key); + if(slot < 0) { + insert(-slot-1, key, value); + return getDefaultReturnValue(); + } + VALUE_TYPE oldValue = values[slot]; + values[slot] += value; + return oldValue; + } + + @Override + public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { + int slot = findIndex(key); + if(slot < 0) return getDefaultReturnValue(); + VALUE_TYPE oldValue = values[slot]; + values[slot] -= value; + if(value < 0 ? (values[slot] >= getDefaultReturnValue()) : (values[slot] <= getDefaultReturnValue())) removeIndex(slot); + return oldValue; + } +#endif +#if !TYPE_OBJECT + @Override + public boolean containsKey(KEY_TYPE key) { + return findIndex(key) >= 0; + } + +#endif + @Override + @Primitive + public boolean containsKey(Object key) { + return findIndex(key) >= 0; + } + +#if !VALUE_OBJECT + @Override + public boolean containsValue(VALUE_TYPE value) { + if(containsNull && VALUE_EQUALS(values[nullIndex], value)) return true; + for(int i = nullIndex-1;i >= 0;i--) + if(KEY_EQUALS_NOT_NULL(keys[i]) && VALUE_EQUALS(values[i], value)) return true; + return false; + } + +#endif + @Override + @ValuePrimitive + public boolean containsValue(Object value) { +#if VALUE_OBJECT + if(containsNull && VALUE_EQUALS(values[nullIndex], value)) return true; +#else + if(containsNull && ((value == null && values[nullIndex] == getDefaultReturnValue()) || EQUALS_VALUE_TYPE(values[nullIndex], value))) return true; +#endif + for(int i = nullIndex-1;i >= 0;i--) +#if VALUE_OBJECT + if(KEY_EQUALS_NOT_NULL(keys[i]) && EQUALS_VALUE_TYPE(values[i], value)) return true; +#else + if(KEY_EQUALS_NOT_NULL(keys[i]) && ((value == null && values[i] == getDefaultReturnValue()) || EQUALS_VALUE_TYPE(values[i], value))) return true; +#endif + return false; + } + + @Override + public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { + int slot = findIndex(key); + if(slot < 0) return getDefaultReturnValue(); + return removeIndex(slot); + } + + @Override + public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { + int slot = findIndex(key); + if(slot < 0) return defaultValue; + return removeIndex(slot); + } + + @Override + public CLASS_VALUE_TYPE remove(Object key) { + int slot = findIndex(key); + if(slot < 0) return VALUE_TO_OBJ(getDefaultReturnValue()); + return removeIndex(slot); + } + +#if !TYPE_OBJECT || !VALUE_OBJECT + @Override + public boolean remove(KEY_TYPE key, VALUE_TYPE value) { + if(KEY_EQUALS_NULL(key)) { + if(containsNull && VALUE_EQUALS(value, values[nullIndex])) { + removeNullIndex(); + return true; + } + return false; + } + int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask; + KEY_TYPE current = keys[pos]; + if(KEY_EQUALS_NULL(current)) return false; + if(KEY_EQUALS(current, key) && VALUE_EQUALS(value, values[pos])) { + removeIndex(pos); + return true; + } + while(true) { + if(KEY_EQUALS_NULL((current = keys[pos = (++pos & mask)]))) return false; + else if(KEY_EQUALS(current, key) && VALUE_EQUALS(value, values[pos])) { + removeIndex(pos); + return true; + } + } + } + +#endif + @Override + public boolean remove(Object key, Object value) { + Objects.requireNonNull(value); +#if TYPE_OBJECT + if(key == null) { +#else + if(key == null || (key instanceof CLASS_TYPE && KEY_EQUALS_NULL(CLASS_TO_KEY(key)))) { +#endif + if(containsNull && EQUALS_VALUE_TYPE(values[nullIndex], value)) { + removeNullIndex(); + return true; + } + return false; + } + int pos = HashUtil.mix(key.hashCode()) & mask; + KEY_TYPE current = keys[pos]; + if(KEY_EQUALS_NULL(current)) return false; + if(EQUALS_KEY_TYPE(current, key) && EQUALS_VALUE_TYPE(values[pos], value)) { + removeIndex(pos); + return true; + } + while(true) { + if(KEY_EQUALS_NULL((current = keys[pos = (++pos & mask)]))) return false; + else if(EQUALS_KEY_TYPE(current, key) && EQUALS_VALUE_TYPE(values[pos], value)){ + removeIndex(pos); + return true; + } + } + } + + @Override + public VALUE_TYPE GET_VALUE(KEY_TYPE key) { + int slot = findIndex(key); + return slot < 0 ? getDefaultReturnValue() : values[slot]; + } + + @Override + public CLASS_VALUE_TYPE get(Object key) { + int slot = findIndex(key); + return VALUE_TO_OBJ(slot < 0 ? getDefaultReturnValue() : values[slot]); + } + +#if TYPE_OBJECT && VALUE_OBJECT + @Override + public VALUE_TYPE getOrDefault(Object key, VALUE_TYPE defaultValue) { + int slot = findIndex(key); + return slot < 0 ? defaultValue : values[slot]; + } + +#else + @Override + public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { + int slot = findIndex(key); + return slot < 0 ? defaultValue : values[slot]; + } + +#endif + @Override + public HASH_MAP KEY_VALUE_GENERIC_TYPE copy() { + HASH_MAP KEY_VALUE_GENERIC_TYPE map = new HASH_MAPKV_BRACES(0, loadFactor); + map.minCapacity = minCapacity; + map.mask = mask; + map.maxFill = maxFill; + map.nullIndex = nullIndex; + map.containsNull = containsNull; + map.size = size; + map.keys = Arrays.copyOf(keys, keys.length); + map.values = Arrays.copyOf(values, values.length); + return map; + } + + @Override + public ObjectSet ENTRY_SET() { + if(entrySet == null) entrySet = new MapEntrySet(); + return entrySet; + } + + @Override + public SET KEY_GENERIC_TYPE keySet() { + if(keySet == null) keySet = new KeySet(); + return keySet; + } + + @Override + public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { + if(valuesC == null) valuesC = new Values(); + return valuesC; + } + + @Override + public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { + if(size() <= 0) return; + if(containsNull) action.accept(keys[nullIndex], values[nullIndex]); + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(keys[i], values[i]); + } + } + + @Override + public boolean replace(KEY_TYPE key, VALUE_TYPE oldValue, VALUE_TYPE newValue) { + int index = findIndex(key); + if(index < 0 || values[index] != oldValue) return false; + values[index] = newValue; + return true; + } + + @Override + public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value) { + int index = findIndex(key); + if(index < 0) return getDefaultReturnValue(); + VALUE_TYPE oldValue = values[index]; + values[index] = value; + return oldValue; + } + + @Override + public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); + int index = findIndex(key); + if(index < 0) { + VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, getDefaultReturnValue()); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + insert(-index-1, key, newValue); + return newValue; + } + VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, values[index]); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + removeIndex(index); + return newValue; + } + values[index] = newValue; + return newValue; + } + + @Override + public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); + int index = findIndex(key); + if(index < 0) { + VALUE_TYPE newValue = mappingFunction.APPLY(key); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + insert(-index-1, key, newValue); + return newValue; + } + VALUE_TYPE newValue = values[index]; + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + newValue = mappingFunction.APPLY(key); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + values[index] = newValue; + } + return newValue; + } + + @Override + public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) { + Objects.requireNonNull(valueProvider); + int index = findIndex(key); + if(index < 0) { + VALUE_TYPE newValue = valueProvider.VALUE_SUPPLY_GET(); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + insert(-index-1, key, newValue); + return newValue; + } + VALUE_TYPE newValue = values[index]; + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + newValue = valueProvider.VALUE_SUPPLY_GET(); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + values[index] = newValue; + } + return newValue; + } + + @Override + public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); + int index = findIndex(key); + if(index < 0 || VALUE_EQUALS(values[index], getDefaultReturnValue())) return getDefaultReturnValue(); + VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, values[index]); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + removeIndex(index); + return newValue; + } + values[index] = newValue; + return newValue; + } + + @Override + public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); +#if VALUE_OBJECT + Objects.requireNonNull(value); +#endif + int index = findIndex(key); + VALUE_TYPE newValue = index < 0 || VALUE_EQUALS(values[index], getDefaultReturnValue()) ? value : mappingFunction.APPLY_VALUE(values[index], value); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + if(index >= 0) + removeIndex(index); + } + else if(index < 0) insert(-index-1, key, newValue); + else values[index] = newValue; + return newValue; + } + + @Override + public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); + for(MAP.Entry KEY_VALUE_GENERIC_TYPE entry : getFastIterable(m)) { + KEY_TYPE key = entry.ENTRY_KEY(); + int index = findIndex(key); + VALUE_TYPE newValue = index < 0 || VALUE_EQUALS(values[index], getDefaultReturnValue()) ? entry.ENTRY_VALUE() : mappingFunction.APPLY_VALUE(values[index], entry.ENTRY_VALUE()); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + if(index >= 0) + removeIndex(index); + } + else if(index < 0) insert(-index-1, key, newValue); + else values[index] = newValue; + } + } + + @Override + public int size() { return size; } + + @Override + public void clear() { + if(size == 0) return; + size = 0; + containsNull = false; + Arrays.fill(keys, EMPTY_KEY_VALUE); + Arrays.fill(values, EMPTY_VALUE); + } + + @Override + public boolean trim(int size) { + int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor))); + if(request >= nullIndex || this.size >= Math.min((int)Math.ceil(request * loadFactor), request - 1)) return false; + try { + rehash(request); + } + catch(OutOfMemoryError noMemory) { return false; } + return true; + } + + @Override + public void clearAndTrim(int size) { + int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor))); + if(request >= nullIndex) { + clear(); + return; + } + nullIndex = request; + mask = request-1; + maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1); + keys = NEW_KEY_ARRAY(request + 1); + values = NEW_VALUE_ARRAY(request + 1); + this.size = 0; + containsNull = false; + } + +#if !TYPE_OBJECT + protected int findIndex(KEY_TYPE key) { + if(KEY_EQUALS_NULL(key)) return containsNull ? nullIndex : -(nullIndex + 1); + int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask; + KEY_TYPE current = keys[pos]; + if(KEY_EQUALS_NOT_NULL(current)) { + if(KEY_EQUALS(current, key)) return pos; + while(KEY_EQUALS_NOT_NULL((current = keys[pos = (++pos & mask)]))) + if(KEY_EQUALS(current, key)) return pos; + } + return -(pos + 1); + } + +#endif + protected int findIndex(Object key) { + if(key == null) return containsNull ? nullIndex : -(nullIndex + 1); +#if !TYPE_OBJECT + if(key instanceof CLASS_TYPE && KEY_EQUALS_NULL(CLASS_TO_KEY(key))) return containsNull ? nullIndex : -(nullIndex + 1); +#endif + int pos = HashUtil.mix(key.hashCode()) & mask; + KEY_TYPE current = keys[pos]; + if(KEY_EQUALS_NOT_NULL(current)) { + if(EQUALS_KEY_TYPE(current, key)) return pos; + while(KEY_EQUALS_NOT_NULL((current = keys[pos = (++pos & mask)]))) + if(EQUALS_KEY_TYPE(current, key)) return pos; + } + return -(pos + 1); + } + + protected VALUE_TYPE removeIndex(int pos) { + if(pos == nullIndex) return containsNull ? removeNullIndex() : getDefaultReturnValue(); + VALUE_TYPE value = values[pos]; + keys[pos] = EMPTY_KEY_VALUE; + values[pos] = EMPTY_VALUE; + size--; + onNodeRemoved(pos); + shiftKeys(pos); + if(nullIndex > minCapacity && size < maxFill / 4 && nullIndex > HashUtil.DEFAULT_MIN_CAPACITY) rehash(nullIndex / 2); + return value; + } + + protected VALUE_TYPE removeNullIndex() { + VALUE_TYPE value = values[nullIndex]; + containsNull = false; + keys[nullIndex] = EMPTY_KEY_VALUE; + values[nullIndex] = EMPTY_VALUE; + size--; + onNodeRemoved(nullIndex); + if(nullIndex > minCapacity && size < maxFill / 4 && nullIndex > HashUtil.DEFAULT_MIN_CAPACITY) rehash(nullIndex / 2); + return value; + } + + protected void insert(int slot, KEY_TYPE key, VALUE_TYPE value) { + if(slot == nullIndex) containsNull = true; + keys[slot] = key; + values[slot] = value; + onNodeAdded(slot); + if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor)); + } + + protected void rehash(int newSize) { + int newMask = newSize - 1; + KEY_TYPE[] newKeys = NEW_KEY_ARRAY(newSize + 1); + VALUE_TYPE[] newValues = NEW_VALUE_ARRAY(newSize + 1); + for(int i = nullIndex, pos = 0, j = (size - (containsNull ? 1 : 0));j-- != 0;) { + while(true) { + if(--i < 0) throw new ConcurrentModificationException("Map was modified during rehash"); + if(KEY_EQUALS_NOT_NULL(keys[i])) break; + } + if(KEY_EQUALS_NOT_NULL(newKeys[pos = HashUtil.mix(KEY_TO_HASH(keys[i])) & newMask])) + while(KEY_EQUALS_NOT_NULL(newKeys[pos = (++pos & newMask)])); + newKeys[pos] = keys[i]; + newValues[pos] = values[i]; + } + newValues[newSize] = values[nullIndex]; + nullIndex = newSize; + mask = newMask; + maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1); + keys = newKeys; + values = newValues; + } + + protected void onNodeAdded(int pos) { + + } + + protected void onNodeRemoved(int pos) { + + } + + protected void onNodeMoved(int from, int to) { + + } + + protected void shiftKeys(int startPos) { + int slot, last; + KEY_TYPE current; + while(true) { + startPos = ((last = startPos) + 1) & mask; + while(true){ + if(KEY_EQUALS_NULL((current = keys[startPos]))) { + keys[last] = EMPTY_KEY_VALUE; + values[last] = EMPTY_VALUE; + return; + } + slot = HashUtil.mix(KEY_TO_HASH(current)) & mask; + if(last <= startPos ? (last >= slot || slot > startPos) : (last >= slot && slot > startPos)) break; + startPos = ++startPos & mask; + } + keys[last] = current; + values[last] = values[startPos]; + onNodeMoved(startPos, last); + } + } + + protected class MapEntry implements MAP.Entry KEY_VALUE_GENERIC_TYPE, Map.Entry { + public int index = -1; + + public MapEntry() {} + public MapEntry(int index) { + this.index = index; + } + + @Override + public KEY_TYPE ENTRY_KEY() { + return keys[index]; + } + + @Override + public VALUE_TYPE ENTRY_VALUE() { + return values[index]; + } + + @Override + public VALUE_TYPE setValue(VALUE_TYPE value) { + VALUE_TYPE oldValue = values[index]; + values[index] = value; + return oldValue; + } + + @Override + public boolean equals(Object obj) { + if(obj instanceof Map.Entry) { + if(obj instanceof MAP.Entry) { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)obj; + return KEY_EQUALS(keys[index], entry.ENTRY_KEY()) && VALUE_EQUALS(values[index], entry.ENTRY_VALUE()); + } + Map.Entry entry = (Map.Entry)obj; + Object key = entry.getKey(); + Object value = entry.getValue(); +#if TYPE_OBJECT && VALUE_OBJECT + return KEY_EQUALS(keys[index], key) && VALUE_EQUALS(values[index], value); +#else if TYPE_OBJECT + return value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(keys[index], key) && VALUE_EQUALS(values[index], CLASS_TO_VALUE(value)); +#else if VALUE_OBJECT + return key instanceof CLASS_TYPE && KEY_EQUALS(keys[index], CLASS_TO_KEY(key)) && VALUE_EQUALS(values[index], value); +#else + return key instanceof CLASS_TYPE && value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(keys[index], CLASS_TO_KEY(key)) && VALUE_EQUALS(values[index], CLASS_TO_VALUE(value)); +#endif + } + return false; + } + + @Override + public int hashCode() { + return KEY_TO_HASH(keys[index]) ^ VALUE_TO_HASH(values[index]); + } + + @Override + public String toString() { + return KEY_TO_STRING(keys[index]) + "=" + VALUE_TO_STRING(values[index]); + } + } + + private final class MapEntrySet extends AbstractObjectSet implements MAP.FastEntrySet KEY_VALUE_GENERIC_TYPE { + @Override + public ObjectIterator fastIterator() { + return new FastEntryIterator(); + } + + @Override + public ObjectIterator iterator() { + return new EntryIterator(); + } + + @Override + public void forEach(Consumer action) { + if(containsNull) action.accept(new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex])); + for(int i = nullIndex-1;i>=0;i--) + if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(new BasicEntryKV_BRACES(keys[i], values[i])); + } + + @Override + public void fastForEach(Consumer action) { + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + if(containsNull) { + entry.set(keys[nullIndex], values[nullIndex]); + action.accept(entry); + } + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NOT_NULL(keys[i])) { + entry.set(keys[i], values[i]); + action.accept(entry); + } + } + } + + @Override + public void forEachIndexed(IntObjectConsumer action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + if(containsNull) action.accept(0, new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex])); + for(int i = nullIndex-1, index = containsNull ? 1 : 0;i>=0;i--) { + if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(index++, new BasicEntryKV_BRACES(keys[i], values[i])); + } + } + + @Override + public void forEach(E input, ObjectObjectConsumer action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + if(containsNull) action.accept(input, new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex])); + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(input, new BasicEntryKV_BRACES(keys[i], values[i])); + } + } + + @Override + public boolean matchesAny(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return false; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + if(containsNull) { + entry.set(keys[nullIndex], values[nullIndex]); + if(filter.test(entry)) return true; + } + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NOT_NULL(keys[i])) { + entry.set(keys[i], values[i]); + if(filter.test(entry)) return true; + } + } + return false; + } + + @Override + public boolean matchesNone(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + if(containsNull) { + entry.set(keys[nullIndex], values[nullIndex]); + if(filter.test(entry)) return false; + } + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NOT_NULL(keys[i])) { + entry.set(keys[i], values[i]); + if(filter.test(entry)) return false; + } + } + return true; + } + + @Override + public boolean matchesAll(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + if(containsNull) { + entry.set(keys[nullIndex], values[nullIndex]); + if(!filter.test(entry)) return false; + } + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NOT_NULL(keys[i])) { + entry.set(keys[i], values[i]); + if(!filter.test(entry)) return false; + } + } + return true; + } + + @Override + public E reduce(E identity, BiFunction operator) { + Objects.requireNonNull(operator); + E state = identity; + if(containsNull) state = operator.apply(state, new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex])); + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NULL(keys[i])) continue; + state = operator.apply(state, new BasicEntryKV_BRACES(keys[i], values[i])); + } + return state; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE reduce(ObjectObjectUnaryOperator operator) { + Objects.requireNonNull(operator); + MAP.Entry KEY_VALUE_GENERIC_TYPE state = null; + boolean empty = true; + if(containsNull) { + state = new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex]); + empty = false; + } + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NULL(keys[i])) continue; + if(empty) { + empty = false; + state = new BasicEntryKV_BRACES(keys[i], values[i]); + continue; + } + state = operator.apply(state, new BasicEntryKV_BRACES(keys[i], values[i])); + } + return state; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE findFirst(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return null; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + if(containsNull) { + entry.set(keys[nullIndex], values[nullIndex]); + if(filter.test(entry)) return entry; + } + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NOT_NULL(keys[i])) { + entry.set(keys[i], values[i]); + if(filter.test(entry)) return entry; + } + } + return null; + } + + @Override + public int count(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return 0; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + int result = 0; + if(containsNull) { + entry.set(keys[nullIndex], values[nullIndex]); + if(filter.test(entry)) result++; + } + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NOT_NULL(keys[i])) { + entry.set(keys[i], values[i]); + if(filter.test(entry)) result++; + } + } + return result; + } + + @Override + public int size() { + return HASH_MAP.this.size(); + } + + @Override + public void clear() { + HASH_MAP.this.clear(); + } + + @Override + public boolean contains(Object o) { + if(o instanceof Map.Entry) { + if(o instanceof MAP.Entry) { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; + int index = HASH_MAP.this.findIndex(entry.ENTRY_KEY()); + if(index >= 0) return VALUE_EQUALS(entry.ENTRY_VALUE(), HASH_MAP.this.values[index]); + } + else { + Map.Entry entry = (Map.Entry)o; + int index = HASH_MAP.this.findIndex(entry.getKey()); + if(index >= 0) return Objects.equals(entry.getValue(), VALUE_TO_OBJ(HASH_MAP.this.values[index])); + } + } + return false; + } + + @Override + public boolean remove(Object o) { + if(o instanceof Map.Entry) { + if(o instanceof MAP.Entry) { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; + return HASH_MAP.this.remove(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); + } + Map.Entry entry = (Map.Entry)o; + return HASH_MAP.this.remove(entry.getKey(), entry.getValue()); + } + return false; + } + } + + private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE { +#if TYPE_OBJECT + @Override + public boolean contains(Object e) { + return containsKey(e); + } + + @Override + public boolean remove(Object o) { + int oldSize = size; + HASH_MAP.this.remove(o); + return size != oldSize; + } + +#else + @Override + public boolean contains(KEY_TYPE e) { + return containsKey(e); + } + + @Override + public boolean remove(KEY_TYPE o) { + int oldSize = size; + HASH_MAP.this.remove(o); + return size != oldSize; + } + +#endif + @Override + public boolean add(KEY_TYPE o) { + throw new UnsupportedOperationException(); + } + + @Override + public ITERATOR KEY_GENERIC_TYPE iterator() { + return new KeyIterator(); + } + + @Override + public int size() { + return HASH_MAP.this.size(); + } + + @Override + public void clear() { + HASH_MAP.this.clear(); + } + + @Override + public KeySet copy() { throw new UnsupportedOperationException(); } + + @Override + public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { + if(containsNull) action.accept(keys[nullIndex]); + for(int i = nullIndex-1;i>=0;i--) + if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(keys[i]); + } + + @Override + public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + if(containsNull) action.accept(0, keys[nullIndex]); + for(int i = nullIndex-1, index = containsNull ? 1 : 0;i>=0;i--) { + if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(index++, keys[i]); + } + } + + @Override + public void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + if(containsNull) action.accept(input, keys[nullIndex]); + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(input, keys[i]); + } + } + + @Override + public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return false; + if(containsNull && filter.test(keys[nullIndex])) return true; + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.test(keys[i])) return true; + } + return false; + } + + @Override + public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + if(containsNull && filter.test(keys[nullIndex])) return false; + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.test(keys[i])) return false; + } + return true; + } + + @Override + public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + if(containsNull && !filter.test(keys[nullIndex])) return false; + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NOT_NULL(keys[i]) && !filter.test(keys[i])) return false; + } + return true; + } + +#if !TYPE_OBJECT + @Override + public KEY_TYPE reduce(KEY_TYPE identity, SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + KEY_TYPE state = identity; + if(containsNull) state = operator.APPLY_KEY_VALUE(state, keys[nullIndex]); + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NULL(keys[i])) continue; + state = operator.APPLY_KEY_VALUE(state, keys[i]); + } + return state; + } + +#else + @Override + public KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) { + Objects.requireNonNull(operator); + KEY_SPECIAL_TYPE state = identity; + if(containsNull) state = operator.apply(state, keys[nullIndex]); + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NULL(keys[i])) continue; + state = operator.apply(state, keys[i]); + } + return state; + } + +#endif + @Override + public KEY_TYPE reduce(SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + KEY_TYPE state = EMPTY_KEY_VALUE; + boolean empty = true; + if(containsNull) { + state = keys[nullIndex]; + empty = false; + } + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NULL(keys[i])) continue; + if(empty) { + empty = false; + state = keys[i]; + continue; + } + state = operator.APPLY_KEY_VALUE(state, keys[i]); + } + return state; + } + + @Override + public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return EMPTY_KEY_VALUE; + if(containsNull && filter.test(keys[nullIndex])) return keys[nullIndex]; + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.test(keys[i])) return keys[i]; + } + return EMPTY_KEY_VALUE; + } + + @Override + public int count(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return 0; + int result = 0; + if(containsNull && filter.test(keys[nullIndex])) result++; + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.test(keys[i])) result++; + } + return result; + } + } + + private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { +#if VALUE_OBJECT + @Override + public boolean contains(Object e) { + return containsValue(e); + } + +#else + @Override + public boolean contains(VALUE_TYPE e) { + return containsValue(e); + } + +#endif + @Override + public boolean add(VALUE_TYPE o) { + throw new UnsupportedOperationException(); + } + + @Override + public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() { + return new ValueIterator(); + } + + @Override + public int size() { + return HASH_MAP.this.size(); + } + + @Override + public void clear() { + HASH_MAP.this.clear(); + } + + @Override + public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) { + if(containsNull) action.accept(values[nullIndex]); + for(int i = nullIndex-1;i>=0;i--) + if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(values[i]); + } + + @Override + public void forEachIndexed(VALUE_BI_FROM_INT_CONSUMER VALUE_GENERIC_TYPE action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + if(containsNull) action.accept(0, values[nullIndex]); + for(int i = nullIndex-1, index = containsNull ? 1 : 0;i>=0;i--) { + if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(index++, values[i]); + } + } + + @Override + public void forEach(E input, VALUE_BI_FROM_OBJECT_CONSUMER VSV_GENERIC_TYPE action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + if(containsNull) action.accept(input, values[nullIndex]); + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(input, values[i]); + } + } + + @Override + public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return false; + if(containsNull && filter.test(values[nullIndex])) return true; + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.test(values[i])) return true; + } + return false; + } + + @Override + public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + if(containsNull && filter.test(values[nullIndex])) return false; + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.test(values[i])) return false; + } + return true; + } + + @Override + public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + if(containsNull && !filter.test(values[nullIndex])) return false; + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NOT_NULL(keys[i]) && !filter.test(values[i])) return false; + } + return true; + } + +#if !VALUE_OBJECT + @Override + public VALUE_TYPE reduce(VALUE_TYPE identity, VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + VALUE_TYPE state = identity; + if(containsNull) state = operator.APPLY_VALUE(state, values[nullIndex]); + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NULL(keys[i])) continue; + state = operator.APPLY_VALUE(state, values[i]); + } + return state; + } + +#else + @Override + public VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction operator) { + Objects.requireNonNull(operator); + VALUE_SPECIAL_TYPE state = identity; + if(containsNull) state = operator.APPLY_VALUE(state, values[nullIndex]); + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NULL(keys[i])) continue; + state = operator.APPLY_VALUE(state, values[i]); + } + return state; + } + +#endif + @Override + public VALUE_TYPE reduce(VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + VALUE_TYPE state = EMPTY_VALUE; + boolean empty = true; + if(containsNull) { + state = values[nullIndex]; + empty = false; + } + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NULL(keys[i])) continue; + if(empty) { + empty = false; + state = values[i]; + continue; + } + state = operator.APPLY_VALUE(state, values[i]); + } + return state; + } + + @Override + public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return EMPTY_VALUE; + if(containsNull && filter.test(values[nullIndex])) return values[nullIndex]; + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.test(values[i])) return values[i]; + } + return EMPTY_VALUE; + } + + @Override + public int count(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return 0; + int result = 0; + if(containsNull && filter.test(values[nullIndex])) result++; + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.test(values[i])) result++; + } + return result; + } + } + + private class FastEntryIterator extends MapIterator implements ObjectIterator { + MapEntry entry = new MapEntry(); + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { + entry.index = nextEntry(); + return entry; + } + } + + private class EntryIterator extends MapIterator implements ObjectIterator { + MapEntry entry; + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { + return entry = new MapEntry(nextEntry()); + } + + @Override + public void remove() { + super.remove(); + entry.index = -1; + } + } + + private class KeyIterator extends MapIterator implements ITERATOR KEY_GENERIC_TYPE { + @Override + public KEY_TYPE NEXT() { + return keys[nextEntry()]; + } + } + + private class ValueIterator extends MapIterator implements VALUE_ITERATOR VALUE_GENERIC_TYPE { + @Override + public VALUE_TYPE VALUE_NEXT() { + return values[nextEntry()]; + } + } + + private class MapIterator { + int pos = nullIndex; + int returnedPos = -1; + int lastReturned = -1; + int nextIndex = Integer.MIN_VALUE; + boolean returnNull = containsNull; + KEY_TYPE[] wrapped = null; + int wrappedIndex = 0; + + public boolean hasNext() { + if(nextIndex == Integer.MIN_VALUE) { + if(returnNull) { + returnNull = false; + nextIndex = nullIndex; + } + else + { + while(true) { + if(--pos < 0) { + if(wrapped == null || wrappedIndex <= -pos - 1) break; + nextIndex = -pos - 1; + break; + } + if(KEY_EQUALS_NOT_NULL(keys[pos])){ + nextIndex = pos; + break; + } + } + } + } + return nextIndex != Integer.MIN_VALUE; + } + + public int nextEntry() { + if(!hasNext()) throw new NoSuchElementException(); + returnedPos = pos; + if(nextIndex < 0){ + lastReturned = Integer.MAX_VALUE; + int value = findIndex(wrapped[nextIndex]); + if(value < 0) throw new IllegalStateException("Entry ["+nextIndex+"] was removed during Iteration"); + nextIndex = Integer.MIN_VALUE; + return value; + } + int value = (lastReturned = nextIndex); + nextIndex = Integer.MIN_VALUE; + return value; + } + + public void remove() { + if(lastReturned == -1) throw new IllegalStateException(); + if(lastReturned == nullIndex) { + containsNull = false; + keys[nullIndex] = EMPTY_KEY_VALUE; + values[nullIndex] = EMPTY_VALUE; + } + else if(returnedPos >= 0) shiftKeys(returnedPos); + else { + HASH_MAP.this.remove(wrapped[-returnedPos - 1]); + lastReturned = -1; + return; + } + size--; + lastReturned = -1; + } + + private void shiftKeys(int startPos) { + int slot, last; + KEY_TYPE current; + while(true) { + startPos = ((last = startPos) + 1) & mask; + while(true){ + if(KEY_EQUALS_NULL((current = keys[startPos]))) { + keys[last] = EMPTY_KEY_VALUE; + values[last] = EMPTY_VALUE; + return; + } + slot = HashUtil.mix(KEY_TO_HASH(current)) & mask; + if(last <= startPos ? (last >= slot || slot > startPos) : (last >= slot && slot > startPos)) break; + startPos = ++startPos & mask; + } + if(startPos < last) addWrapper(keys[startPos]); + keys[last] = current; + values[last] = values[startPos]; + } + } + + private void addWrapper(KEY_TYPE value) { + if(wrapped == null) wrapped = NEW_KEY_ARRAY(2); + else if(wrappedIndex >= wrapped.length) { + KEY_TYPE[] newArray = NEW_KEY_ARRAY(wrapped.length * 2); + System.arraycopy(wrapped, 0, newArray, 0, wrapped.length); + wrapped = newArray; + } + wrapped[wrappedIndex++] = value; + } + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/collections/templates/maps/impl/immutable/ImmutableOpenHashMap.template b/src/builder/resources/speiger/assets/collections/templates/maps/impl/immutable/ImmutableOpenHashMap.template index 5d8f2f0..13bbb03 100644 --- a/src/builder/resources/speiger/assets/collections/templates/maps/impl/immutable/ImmutableOpenHashMap.template +++ b/src/builder/resources/speiger/assets/collections/templates/maps/impl/immutable/ImmutableOpenHashMap.template @@ -1,1406 +1,1408 @@ -package speiger.src.collections.PACKAGE.maps.impl.immutable; - -import java.util.Arrays; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Objects; -import java.util.function.Consumer; -import java.util.function.BiFunction; -import java.util.function.Predicate; -#if !TYPE_OBJECT && JDK_TYPE -import java.util.function.PREDICATE; -#endif -#if !SAME_TYPE && JDK_VALUE && !VALUE_OBJECT -import java.util.function.VALUE_PREDICATE; -#endif - -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; -import speiger.src.collections.PACKAGE.functions.CONSUMER; -import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; -#endif -import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER; -#if !TYPE_OBJECT && !VALUE_OBJECT -import speiger.src.collections.ints.functions.consumer.IntObjectConsumer; -#endif -#if !SAME_TYPE -import speiger.src.collections.ints.functions.consumer.VALUE_BI_FROM_INT_CONSUMER; -#endif -#if !TYPE_OBJECT && !VALUE_BOOLEAN && !JDK_TYPE -import speiger.src.collections.PACKAGE.functions.function.PREDICATE; -#endif -import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; -#if !VALUE_BOOLEAN || !JDK_TYPE -import speiger.src.collections.PACKAGE.functions.function.FUNCTION; -#endif -import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; -#if !SAME_TYPE -import speiger.src.collections.PACKAGE.functions.function.SINGLE_UNARY_OPERATOR; -#endif -import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; -import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP; -import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.sets.ORDERED_SET; -#endif -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.utils.ARRAYS; -#endif -#if !TYPE_OBJECT && !VALUE_OBJECT || !VALUE_OBJECT -import speiger.src.collections.objects.functions.consumer.ObjectObjectConsumer; -#endif -#if !SAME_TYPE -#if !TYPE_OBJECT -import speiger.src.collections.objects.functions.consumer.VALUE_BI_FROM_OBJECT_CONSUMER; - -#endif -#if !JDK_VALUE -import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE; -#endif -#endif -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET; -#endif -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; -import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_SUPPLIER; -#if !SAME_TYPE -import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR; -#if !VALUE_OBJECT -import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER; -import speiger.src.collections.VALUE_PACKAGE.lists.VALUE_LIST_ITERATOR; -import speiger.src.collections.VALUE_PACKAGE.utils.VALUE_ARRAYS; -#endif -#endif -import speiger.src.collections.objects.collections.ObjectBidirectionalIterator; -#if !TYPE_OBJECT -#if !VALUE_OBJECT -import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator; - -#endif -import speiger.src.collections.objects.lists.ObjectListIterator; -#endif -import speiger.src.collections.objects.sets.AbstractObjectSet; -import speiger.src.collections.objects.sets.ObjectOrderedSet; -import speiger.src.collections.utils.HashUtil; -import speiger.src.collections.utils.SanityChecks; - -/** - * A Type Specific Custom implementation of the HashMap - * Instead of using Wrapper Object Arrays for storing keys and values there is dedicated arrays for storing keys and values. - * Extra to that there is a couple quality of life functions provided - * @Type(T) - * @ValueType(V) - */ -public class IMMUTABLE_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements ORDERED_MAP KEY_VALUE_GENERIC_TYPE -{ - /** The Backing keys array */ - protected transient KEY_TYPE[] keys; - /** The Backing values array */ - protected transient VALUE_TYPE[] values; - /** The Backing array for links between nodes. Left 32 Bits => Previous Entry, Right 32 Bits => Next Entry */ - protected transient long[] links; - /** If a null value is present */ - protected transient boolean containsNull; - /** Index of the Null Value */ - protected transient int nullIndex; - /** Max Index that is allowed to be searched through nullIndex - 1 */ - protected transient int mask; - /** The First Index in the Map */ - protected int firstIndex = -1; - /** The Last Index in the Map */ - protected int lastIndex = -1; - /** EntrySet cache */ - protected transient FastOrderedSet KEY_VALUE_GENERIC_TYPE entrySet; - /** KeySet cache */ - protected transient ORDERED_SET KEY_GENERIC_TYPE keySet; - /** Values cache */ - protected transient VALUE_COLLECTION VALUE_GENERIC_TYPE valuesC; - - /** Amount of Elements stored in the HashMap */ - protected int size; - - /** - * Helper constructor for copying the Map - */ - protected IMMUTABLE_HASH_MAP() {} - -#if !TYPE_OBJECT || !VALUE_OBJECT - /** - * Helper constructor that allow to create a map from boxed values (it will unbox them) - * @param keys the keys that should be put into the map - * @param values the values that should be put into the map. - * @throws IllegalStateException if the keys and values do not match in lenght - */ - public IMMUTABLE_HASH_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values) { - this(keys, values, HashUtil.DEFAULT_LOAD_FACTOR); - } - - /** - * Helper constructor that allow to create a map from boxed values (it will unbox them) - * @param keys the keys that should be put into the map - * @param values the values that should be put into the map. - * @param loadFactor the percentage of how full the backing array can be before they resize - * @throws IllegalStateException if the keys and values do not match in lenght - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - */ - public IMMUTABLE_HASH_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, float loadFactor) { - if(keys.length != values.length) throw new IllegalStateException("Input Arrays are not equal size"); -#if TYPE_OBJECT && VALUE_OBJECT - init(keys, values, 0, keys.length, loadFactor); -#else if TYPE_OBJECT - init(keys, VALUE_ARRAYS.unwrap(values), 0, keys.length, loadFactor); -#else if VALUE_OBJECT - init(ARRAYS.unwrap(keys), values, 0, keys.length, loadFactor); -#else - init(ARRAYS.unwrap(keys), VALUE_ARRAYS.unwrap(values), 0, keys.length, loadFactor); -#endif - } - -#endif - /** - * Helper constructor that allow to create a map from unboxed values - * @param keys the keys that should be put into the map - * @param values the values that should be put into the map. - * @throws IllegalStateException if the keys and values do not match in lenght - */ - public IMMUTABLE_HASH_MAP(KEY_TYPE[] keys, VALUE_TYPE[] values) { - this(keys, values, HashUtil.DEFAULT_LOAD_FACTOR); - } - - /** - * Helper constructor that allow to create a map from unboxed values - * @param keys the keys that should be put into the map - * @param values the values that should be put into the map. - * @param loadFactor the percentage of how full the backing array can be before they resize - * @throws IllegalStateException if the keys and values do not match in lenght - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - */ - public IMMUTABLE_HASH_MAP(KEY_TYPE[] keys, VALUE_TYPE[] values, float loadFactor) { - if(keys.length != values.length) throw new IllegalStateException("Input Arrays are not equal size"); - init(keys, values, 0, keys.length, loadFactor); - } - - /** - * A Helper constructor that allows to create a Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - */ - public IMMUTABLE_HASH_MAP(Map map) { - this(map, HashUtil.DEFAULT_LOAD_FACTOR); - } - - /** - * A Helper constructor that allows to create a Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - * @param loadFactor the percentage of how full the backing array can be before they resize - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - */ - public IMMUTABLE_HASH_MAP(Map map, float loadFactor) { - KEY_TYPE[] keys = NEW_KEY_ARRAY(map.size()); - VALUE_TYPE[] values = NEW_VALUE_ARRAY(keys.length); - int index = 0; - for(Map.Entry entry : map.entrySet()) { - keys[index] = OBJ_TO_KEY(entry.getKey()); - values[index] = OBJ_TO_VALUE(entry.getValue()); - index++; - } - init(keys, values, 0, index, loadFactor); - } - - /** - * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - */ - public IMMUTABLE_HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map) { - this(map, HashUtil.DEFAULT_LOAD_FACTOR); - } - - /** - * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - * @param loadFactor the percentage of how full the backing array can be before they resize - * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 - */ - public IMMUTABLE_HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map, float loadFactor) { - KEY_TYPE[] keys = NEW_KEY_ARRAY(map.size()); - VALUE_TYPE[] values = NEW_VALUE_ARRAY(keys.length); - int index = 0; - for(MAP.Entry KEY_VALUE_GENERIC_TYPE entry : getFastIterable(map)) { - keys[index] = entry.ENTRY_KEY(); - values[index] = entry.ENTRY_VALUE(); - index++; - } - init(keys, values, 0, index, loadFactor); - } - - protected void init(KEY_TYPE[] a, VALUE_TYPE[] b, int offset, int length, float loadFactor) { - SanityChecks.checkArrayCapacity(a.length, offset, length); - int newSize = HashUtil.arraySize(length+1, loadFactor); - int newMask = newSize - 1; - KEY_TYPE[] newKeys = NEW_KEY_ARRAY(newSize + 1); - VALUE_TYPE[] newValues = NEW_VALUE_ARRAY(newSize + 1); - long[] newLinks = new long[newSize + 1]; - int prev = -1; - for(int i = offset,m=offset+length;i= 0; - } - -#endif - @Override - @Primitive - public boolean containsKey(Object key) { - return findIndex(key) >= 0; - } - -#if !VALUE_OBJECT - @Override - public boolean containsValue(VALUE_TYPE value) { - int index = firstIndex; - while(index != -1) { - if(VALUE_EQUALS(values[index], value)) return true; - index = (int)links[index]; - } - return false; - } - -#endif - @Override - @ValuePrimitive - public boolean containsValue(Object value) { - int index = firstIndex; - while(index != -1) { -#if VALUE_OBJECT - if(VALUE_EQUALS(values[index], value)) return true; -#else - if((value == null && values[index] == getDefaultReturnValue()) || EQUALS_VALUE_TYPE(values[index], value)) return true; -#endif - index = (int)links[index]; - } - return false; - } - - @Override - public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { throw new UnsupportedOperationException(); } - - @Override - public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { throw new UnsupportedOperationException(); } - - @Override - @Deprecated - public CLASS_VALUE_TYPE remove(Object key) { throw new UnsupportedOperationException(); } - -#if !TYPE_OBJECT || !VALUE_OBJECT - @Override - public boolean remove(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } - -#endif - @Override - public boolean remove(Object key, Object value) { throw new UnsupportedOperationException(); } - - @Override - public VALUE_TYPE GET_VALUE(KEY_TYPE key) { - int slot = findIndex(key); - return slot < 0 ? getDefaultReturnValue() : values[slot]; - } - - @Override - public CLASS_VALUE_TYPE get(Object key) { - int slot = findIndex(key); - return VALUE_TO_OBJ(slot < 0 ? getDefaultReturnValue() : values[slot]); - } - -#if TYPE_OBJECT && VALUE_OBJECT - @Override - public VALUE_TYPE getOrDefault(Object key, VALUE_TYPE defaultValue) { - int slot = findIndex(key); - return slot < 0 ? defaultValue : values[slot]; - } - -#else - @Override - public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { - int slot = findIndex(key); - return slot < 0 ? defaultValue : values[slot]; - } - -#endif - @Override - public KEY_TYPE FIRST_ENTRY_KEY() { - if(size == 0) throw new NoSuchElementException(); - return keys[firstIndex]; - } - - @Override - public KEY_TYPE POLL_FIRST_ENTRY_KEY() { throw new UnsupportedOperationException(); } - - @Override - public KEY_TYPE LAST_ENTRY_KEY() { - if(size == 0) throw new NoSuchElementException(); - return keys[lastIndex]; - } - - @Override - public KEY_TYPE POLL_LAST_ENTRY_KEY() { throw new UnsupportedOperationException(); } - - @Override - public VALUE_TYPE FIRST_ENTRY_VALUE() { - if(size == 0) throw new NoSuchElementException(); - return values[firstIndex]; - } - - @Override - public VALUE_TYPE LAST_ENTRY_VALUE() { - if(size == 0) throw new NoSuchElementException(); - return values[lastIndex]; - } - - @Override - public ObjectOrderedSet ENTRY_SET() { - if(entrySet == null) entrySet = new MapEntrySet(); - return entrySet; - } - - @Override - public ORDERED_SET KEY_GENERIC_TYPE keySet() { - if(keySet == null) keySet = new KeySet(); - return keySet; - } - - @Override - public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { - if(valuesC == null) valuesC = new Values(); - return valuesC; - } - - @Override - public IMMUTABLE_HASH_MAP KEY_VALUE_GENERIC_TYPE copy() { - IMMUTABLE_HASH_MAP KEY_VALUE_GENERIC_TYPE map = new IMMUTABLE_HASH_MAPKV_BRACES(); - map.mask = mask; - map.nullIndex = nullIndex; - map.containsNull = containsNull; - map.size = size; - map.keys = Arrays.copyOf(keys, keys.length); - map.values = Arrays.copyOf(values, values.length); - map.links = Arrays.copyOf(links, links.length); - map.firstIndex = firstIndex; - map.lastIndex = lastIndex; - return map; - } - - @Override - public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { - int index = firstIndex; - while(index != -1){ - action.accept(keys[index], values[index]); - index = (int)links[index]; - } - } - - @Override - public boolean replace(KEY_TYPE key, VALUE_TYPE oldValue, VALUE_TYPE newValue) { throw new UnsupportedOperationException(); } - - @Override - public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } - - @Override - public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } - - @Override - public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } - - @Override - public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) { throw new UnsupportedOperationException(); } - - @Override - public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } - - @Override - public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } - - @Override - public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } - - @Override - public int size() { return size; } - - @Override - public void clear() { throw new UnsupportedOperationException(); } - -#if !TYPE_OBJECT - protected int findIndex(KEY_TYPE key) { - if(KEY_EQUALS_NULL(key)) return containsNull ? nullIndex : -(nullIndex + 1); - int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask; - KEY_TYPE current = keys[pos]; - if(KEY_EQUALS_NOT_NULL(current)) { - if(KEY_EQUALS(current, key)) return pos; - while(KEY_EQUALS_NOT_NULL((current = keys[pos = (++pos & mask)]))) - if(KEY_EQUALS(current, key)) return pos; - } - return -(pos + 1); - } - -#endif - protected int findIndex(Object key) { - if(key == null) return containsNull ? nullIndex : -(nullIndex + 1); -#if !TYPE_OBJECT - if(KEY_EQUALS_NULL(CLASS_TO_KEY(key))) return containsNull ? nullIndex : -(nullIndex + 1); -#endif - int pos = HashUtil.mix(key.hashCode()) & mask; - KEY_TYPE current = keys[pos]; - if(KEY_EQUALS_NOT_NULL(current)) { - if(EQUALS_KEY_TYPE(current, key)) return pos; - while(KEY_EQUALS_NOT_NULL((current = keys[pos = (++pos & mask)]))) - if(EQUALS_KEY_TYPE(current, key)) return pos; - } - return -(pos + 1); - } - - protected class MapEntry implements MAP.Entry KEY_VALUE_GENERIC_TYPE, Map.Entry { - public int index = -1; - - public MapEntry() {} - public MapEntry(int index) { - this.index = index; - } - - @Override - public KEY_TYPE ENTRY_KEY() { - return keys[index]; - } - - @Override - public VALUE_TYPE ENTRY_VALUE() { - return values[index]; - } - - @Override - public VALUE_TYPE setValue(VALUE_TYPE value) { throw new UnsupportedOperationException(); } - - @Override - public boolean equals(Object obj) { - if(obj instanceof Map.Entry) { - if(obj instanceof MAP.Entry) { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)obj; - return KEY_EQUALS(keys[index], entry.ENTRY_KEY()) && VALUE_EQUALS(values[index], entry.ENTRY_VALUE()); - } - Map.Entry entry = (Map.Entry)obj; - Object key = entry.getKey(); -#if !TYPE_OBJECT - if(!(key instanceof CLASS_TYPE)) return false; -#endif - Object value = entry.getValue(); -#if TYPE_OBJECT && VALUE_OBJECT - return KEY_EQUALS(keys[index], key) && VALUE_EQUALS(values[index], value); -#else if TYPE_OBJECT - return value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(keys[index], key) && VALUE_EQUALS(values[index], CLASS_TO_VALUE(value)); -#else if VALUE_OBJECT - return key instanceof CLASS_TYPE && KEY_EQUALS(keys[index], CLASS_TO_KEY(key)) && VALUE_EQUALS(values[index], value); -#else - return key instanceof CLASS_TYPE && value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(keys[index], CLASS_TO_KEY(key)) && VALUE_EQUALS(values[index], CLASS_TO_VALUE(value)); -#endif - } - return false; - } - - @Override - public int hashCode() { - return KEY_TO_HASH(keys[index]) ^ VALUE_TO_HASH(values[index]); - } - - @Override - public String toString() { - return KEY_TO_STRING(keys[index]) + "=" + VALUE_TO_STRING(values[index]); - } - } - - private class MapEntrySet extends AbstractObjectSet implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE { - @Override - public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } - @Override - public boolean addAndMoveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } - - @Override - public boolean moveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } - - @Override - public boolean moveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE first() { - return new BasicEntryKV_BRACES(FIRST_ENTRY_KEY(), FIRST_ENTRY_VALUE()); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE last() { - return new BasicEntryKV_BRACES(LAST_ENTRY_KEY(), LAST_ENTRY_VALUE()); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirst() { throw new UnsupportedOperationException(); } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLast() { throw new UnsupportedOperationException(); } - - @Override - public ObjectBidirectionalIterator iterator() { - return new EntryIterator(); - } - - @Override - public ObjectBidirectionalIterator iterator(MAP.Entry KEY_VALUE_GENERIC_TYPE fromElement) { - return new EntryIterator(fromElement.ENTRY_KEY()); - } - - @Override - public ObjectBidirectionalIterator fastIterator() { - return new FastEntryIterator(); - } - - @Override - public ObjectBidirectionalIterator fastIterator(KEY_TYPE fromElement) { - return new FastEntryIterator(fromElement); - } - - @Override - public MapEntrySet copy() { throw new UnsupportedOperationException(); } - - @Override - public void forEach(Consumer action) { - int index = firstIndex; - while(index != -1){ - action.accept(new BasicEntryKV_BRACES(keys[index], values[index])); - index = (int)links[index]; - } - } - - @Override - public void fastForEach(Consumer action) { - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - int index = firstIndex; - while(index != -1){ - entry.set(keys[index], values[index]); - action.accept(entry); - index = (int)links[index]; - } - } - - @Override - public void forEachIndexed(IntObjectConsumer action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - int count = 0; - int index = firstIndex; - while(index != -1) { - action.accept(count++, new BasicEntryKV_BRACES(keys[index], values[index])); - index = (int)links[index]; - } - } - - @Override - public void forEach(E input, ObjectObjectConsumer action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - int index = firstIndex; - while(index != -1) { - action.accept(input, new BasicEntryKV_BRACES(keys[index], values[index])); - index = (int)links[index]; - } - } - - @Override - public boolean matchesAny(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return false; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - int index = firstIndex; - while(index != -1) { - entry.set(keys[index], values[index]); - if(filter.test(entry)) return true; - index = (int)links[index]; - } - return false; - } - - @Override - public boolean matchesNone(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - int index = firstIndex; - while(index != -1) { - entry.set(keys[index], values[index]); - if(filter.test(entry)) return false; - index = (int)links[index]; - } - return true; - } - - @Override - public boolean matchesAll(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - int index = firstIndex; - while(index != -1) { - entry.set(keys[index], values[index]); - if(!filter.test(entry)) return false; - index = (int)links[index]; - } - return true; - } - - @Override - public E reduce(E identity, BiFunction operator) { - Objects.requireNonNull(operator); - E state = identity; - int index = firstIndex; - while(index != -1) { - state = operator.apply(state, new BasicEntryKV_BRACES(keys[index], values[index])); - index = (int)links[index]; - } - return state; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE reduce(ObjectObjectUnaryOperator operator) { - Objects.requireNonNull(operator); - MAP.Entry KEY_VALUE_GENERIC_TYPE state = null; - boolean empty = true; - int index = firstIndex; - while(index != -1) { - if(empty) { - empty = false; - state = new BasicEntryKV_BRACES(keys[index], values[index]); - index = (int)links[index]; - continue; - } - state = operator.apply(state, new BasicEntryKV_BRACES(keys[index], values[index])); - index = (int)links[index]; - } - return state; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE findFirst(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return null; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - int index = firstIndex; - while(index != -1) { - entry.set(keys[index], values[index]); - if(filter.test(entry)) return entry; - index = (int)links[index]; - } - return null; - } - - @Override - public int count(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return 0; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - int result = 0; - int index = firstIndex; - while(index != -1) { - entry.set(keys[index], values[index]); - if(filter.test(entry)) result++; - index = (int)links[index]; - } - return result; - } - - @Override - @Deprecated - public boolean contains(Object o) { - if(o instanceof Map.Entry) { - if(o instanceof MAP.Entry) { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; - int index = IMMUTABLE_HASH_MAP.this.findIndex(entry.ENTRY_KEY()); - if(index >= 0) return VALUE_EQUALS(entry.ENTRY_VALUE(), IMMUTABLE_HASH_MAP.this.values[index]); - } - else { - Map.Entry entry = (Map.Entry)o; - int index = IMMUTABLE_HASH_MAP.this.findIndex(entry.getKey()); - if(index >= 0) return Objects.equals(entry.getValue(), VALUE_TO_OBJ(IMMUTABLE_HASH_MAP.this.values[index])); - } - } - return false; - } - - @Override - @Deprecated - public boolean remove(Object o) { throw new UnsupportedOperationException(); } - - @Override - public int size() { - return IMMUTABLE_HASH_MAP.this.size(); - } - - @Override - public void clear() { throw new UnsupportedOperationException(); } - } - - private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE { -#if TYPE_OBJECT - @Override - @Deprecated - public boolean contains(Object e) { - return containsKey(e); - } - - @Override - public boolean remove(Object o) { throw new UnsupportedOperationException(); } - -#else - @Override - public boolean contains(KEY_TYPE e) { - return containsKey(e); - } - - @Override - public boolean remove(KEY_TYPE o) { throw new UnsupportedOperationException(); } - -#endif - @Override - public boolean add(KEY_TYPE o) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); } - - @Override - public boolean addAndMoveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); } - - @Override - public boolean moveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); } - - @Override - public boolean moveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); } - - @Override - public LIST_ITERATOR KEY_GENERIC_TYPE iterator() { - return new KeyIterator(); - } - - @Override - public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { - return new KeyIterator(fromElement); - } - - @Override - public KeySet copy() { throw new UnsupportedOperationException(); } - - @Override - public int size() { - return IMMUTABLE_HASH_MAP.this.size(); - } - - @Override - public void clear() { throw new UnsupportedOperationException(); } - - @Override - public KEY_TYPE FIRST_KEY() { - return FIRST_ENTRY_KEY(); - } - - @Override - public KEY_TYPE POLL_FIRST_KEY() { throw new UnsupportedOperationException(); } - - @Override - public KEY_TYPE LAST_KEY() { - return LAST_ENTRY_KEY(); - } - - @Override - public KEY_TYPE POLL_LAST_KEY() { throw new UnsupportedOperationException(); } - - @Override - public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { - int index = firstIndex; - while(index != -1){ - action.accept(keys[index]); - index = (int)links[index]; - } - } - - @Override - public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - int count = 0; - int index = firstIndex; - while(index != -1){ - action.accept(count++, keys[index]); - index = (int)links[index]; - } - } - - @Override - public void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - int index = firstIndex; - while(index != -1){ - action.accept(input, keys[index]); - index = (int)links[index]; - } - } - - @Override - public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return false; - int index = firstIndex; - while(index != -1){ - if(filter.test(keys[index])) return true; - index = (int)links[index]; - } - return false; - } - - @Override - public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - int index = firstIndex; - while(index != -1){ - if(filter.test(keys[index])) return false; - index = (int)links[index]; - } - return true; - } - - @Override - public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - int index = firstIndex; - while(index != -1){ - if(!filter.test(keys[index])) return false; - index = (int)links[index]; - } - return true; - } - -#if !TYPE_OBJECT - @Override - public KEY_TYPE reduce(KEY_TYPE identity, SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - KEY_TYPE state = identity; - int index = firstIndex; - while(index != -1) { - state = operator.APPLY_KEY_VALUE(state, keys[index]); - index = (int)links[index]; - } - return state; - } - -#else - @Override - public KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) { - Objects.requireNonNull(operator); - KEY_SPECIAL_TYPE state = identity; - int index = firstIndex; - while(index != -1) { - state = operator.apply(state, keys[index]); - index = (int)links[index]; - } - return state; - } - -#endif - @Override - public KEY_TYPE reduce(SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - KEY_TYPE state = EMPTY_KEY_VALUE; - boolean empty = true; - int index = firstIndex; - while(index != -1) { - if(empty) { - empty = false; - state = keys[index]; - index = (int)links[index]; - continue; - } - state = operator.APPLY_KEY_VALUE(state, keys[index]); - index = (int)links[index]; - } - return state; - } - - @Override - public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return EMPTY_KEY_VALUE; - int index = firstIndex; - while(index != -1){ - if(filter.test(keys[index])) return keys[index]; - index = (int)links[index]; - } - return EMPTY_KEY_VALUE; - } - - @Override - public int count(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return 0; - int index = firstIndex; - int result = 0; - while(index != -1){ - if(filter.test(keys[index])) result++; - index = (int)links[index]; - } - return result; - } - } - - private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { -#if VALUE_OBJECT - @Override - @Deprecated - public boolean contains(Object e) { - return containsValue(e); - } - -#else - @Override - public boolean contains(VALUE_TYPE e) { - return containsValue(e); - } - -#endif - @Override - public boolean add(VALUE_TYPE o) { - throw new UnsupportedOperationException(); - } - - @Override - public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() { - return new ValueIterator(); - } - - @Override - public int size() { - return IMMUTABLE_HASH_MAP.this.size(); - } - - @Override - public void clear() { throw new UnsupportedOperationException(); } - - @Override - public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) { - int index = firstIndex; - while(index != -1){ - action.accept(values[index]); - index = (int)links[index]; - } - } - - @Override - public void forEachIndexed(VALUE_BI_FROM_INT_CONSUMER VALUE_GENERIC_TYPE action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - int count = 0; - int index = firstIndex; - while(index != -1){ - action.accept(count++, values[index]); - index = (int)links[index]; - } - } - - @Override - public void forEach(E input, VALUE_BI_FROM_OBJECT_CONSUMER VSV_GENERIC_TYPE action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - int index = firstIndex; - while(index != -1){ - action.accept(input, values[index]); - index = (int)links[index]; - } - } - - @Override - public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return false; - int index = firstIndex; - while(index != -1){ - if(filter.test(values[index])) return true; - index = (int)links[index]; - } - return false; - } - - @Override - public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - int index = firstIndex; - while(index != -1){ - if(filter.test(values[index])) return false; - index = (int)links[index]; - } - return true; - } - - @Override - public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - int index = firstIndex; - while(index != -1){ - if(!filter.test(values[index])) return false; - index = (int)links[index]; - } - return true; - } - -#if !VALUE_OBJECT - @Override - public VALUE_TYPE reduce(VALUE_TYPE identity, VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - VALUE_TYPE state = identity; - int index = firstIndex; - while(index != -1) { - state = operator.APPLY_VALUE(state, values[index]); - index = (int)links[index]; - } - return state; - } - -#else - @Override - public VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction operator) { - Objects.requireNonNull(operator); - VALUE_SPECIAL_TYPE state = identity; - int index = firstIndex; - while(index != -1) { - state = operator.apply(state, values[index]); - index = (int)links[index]; - } - return state; - } - -#endif - @Override - public VALUE_TYPE reduce(VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - VALUE_TYPE state = EMPTY_VALUE; - boolean empty = true; - int index = firstIndex; - while(index != -1) { - if(empty) { - empty = false; - state = values[index]; - index = (int)links[index]; - continue; - } - state = operator.APPLY_VALUE(state, values[index]); - index = (int)links[index]; - } - return state; - } - - @Override - public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return EMPTY_VALUE; - int index = firstIndex; - while(index != -1){ - if(filter.test(values[index])) return values[index]; - index = (int)links[index]; - } - return EMPTY_VALUE; - } - - @Override - public int count(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return 0; - int result = 0; - int index = firstIndex; - while(index != -1){ - if(filter.test(values[index])) result++; - index = (int)links[index]; - } - return result; - } - } - - private class FastEntryIterator extends MapIterator implements ObjectListIterator { - MapEntry entry = new MapEntry(); - - public FastEntryIterator() {} - public FastEntryIterator(KEY_TYPE from) { - super(from); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { - entry.index = nextEntry(); - return entry; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { - entry.index = previousEntry(); - return entry; - } - - @Override - public void set(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } - - @Override - public void add(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } - } - - private class EntryIterator extends MapIterator implements ObjectListIterator { - - public EntryIterator() {} - public EntryIterator(KEY_TYPE from) { - super(from); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { - return new MapEntry(nextEntry()); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { - return new MapEntry(previousEntry()); - } - - @Override - public void remove() { throw new UnsupportedOperationException(); } - - @Override - public void set(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } - - @Override - public void add(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } - } - - private class KeyIterator extends MapIterator implements LIST_ITERATOR KEY_GENERIC_TYPE { - - public KeyIterator() {} - public KeyIterator(KEY_TYPE from) { - super(from); - } - - @Override - public KEY_TYPE PREVIOUS() { - return keys[previousEntry()]; - } - - @Override - public KEY_TYPE NEXT() { - return keys[nextEntry()]; - } - - @Override - public void set(KEY_TYPE e) { throw new UnsupportedOperationException(); } - @Override - public void add(KEY_TYPE e) { throw new UnsupportedOperationException(); } - } - - private class ValueIterator extends MapIterator implements VALUE_LIST_ITERATOR VALUE_GENERIC_TYPE { - public ValueIterator() {} - - @Override - public VALUE_TYPE VALUE_PREVIOUS() { - return values[previousEntry()]; - } - - @Override - public VALUE_TYPE VALUE_NEXT() { - return values[nextEntry()]; - } - - @Override - public void set(VALUE_TYPE e) { throw new UnsupportedOperationException(); } - - @Override - public void add(VALUE_TYPE e) { throw new UnsupportedOperationException(); } - - } - - private class MapIterator { - int previous = -1; - int next = -1; - int current = -1; - int index = 0; - - MapIterator() { - next = firstIndex; - } - - MapIterator(KEY_TYPE from) { - if(KEY_EQUALS_NULL(from)) { - if(containsNull) { - next = (int) links[nullIndex]; - previous = nullIndex; - } - else throw new NoSuchElementException("The null element is not in the set"); - } - else if(keys[lastIndex] == from) { - previous = lastIndex; - index = size; - } - else { - int pos = HashUtil.mix(KEY_TO_HASH(from)) & mask; - while(KEY_EQUALS_NOT_NULL(keys[pos])) { - if(KEY_EQUALS(keys[pos], from)) { - next = (int)links[pos]; - previous = pos; - break; - } - pos = ++pos & mask; - } - if(previous == -1 && next == -1) - throw new NoSuchElementException("The element was not found"); - } - } - - public boolean hasNext() { - return next != -1; - } - - public boolean hasPrevious() { - return previous != -1; - } - - public int nextIndex() { - ensureIndexKnown(); - return index; - } - - public int previousIndex() { - ensureIndexKnown(); - return index - 1; - } - - public void remove() { throw new UnsupportedOperationException(); } - - public int previousEntry() { - if(!hasPrevious()) throw new NoSuchElementException(); - current = previous; - previous = (int)(links[current] >> 32); - next = current; - if(index >= 0) index--; - return current; - } - - public int nextEntry() { - if(!hasNext()) throw new NoSuchElementException(); - current = next; - next = (int)(links[current]); - previous = current; - if(index >= 0) index++; - return current; - } - - private void ensureIndexKnown() { - if(index == -1) { - if(previous == -1) { - index = 0; - } - else if(next == -1) { - index = size; - } - else { - index = 1; - for(int pos = firstIndex;pos != previous;pos = (int)links[pos], index++); - } - } - } - } +package speiger.src.collections.PACKAGE.maps.impl.immutable; + +import java.util.Arrays; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Objects; +import java.util.function.Consumer; +import java.util.function.BiFunction; +import java.util.function.Predicate; +#if !TYPE_OBJECT && JDK_TYPE +import java.util.function.PREDICATE; +#endif +#if !SAME_TYPE && JDK_VALUE && !VALUE_OBJECT +import java.util.function.VALUE_PREDICATE; +#endif + +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; +import speiger.src.collections.PACKAGE.functions.CONSUMER; +import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; +#endif +import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER; +#if !TYPE_OBJECT && !VALUE_OBJECT +import speiger.src.collections.ints.functions.consumer.IntObjectConsumer; +#endif +#if !SAME_TYPE && !TYPE_INT +import speiger.src.collections.ints.functions.consumer.VALUE_BI_FROM_INT_CONSUMER; +#endif +#if !TYPE_OBJECT && !VALUE_BOOLEAN && !JDK_TYPE +import speiger.src.collections.PACKAGE.functions.function.PREDICATE; +#endif +#if !TYPE_INT || !SAME_TYPE +import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; +#endif +#if !VALUE_BOOLEAN || !JDK_TYPE +import speiger.src.collections.PACKAGE.functions.function.FUNCTION; +#endif +import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; +#if !SAME_TYPE +import speiger.src.collections.PACKAGE.functions.function.SINGLE_UNARY_OPERATOR; +#endif +import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; +import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP; +import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.sets.ORDERED_SET; +#endif +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.utils.ARRAYS; +#endif +#if !TYPE_OBJECT && !VALUE_OBJECT || !VALUE_OBJECT +import speiger.src.collections.objects.functions.consumer.ObjectObjectConsumer; +#endif +#if !SAME_TYPE +#if !TYPE_OBJECT +import speiger.src.collections.objects.functions.consumer.VALUE_BI_FROM_OBJECT_CONSUMER; + +#endif +#if !JDK_VALUE +import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE; +#endif +#endif +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET; +#endif +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; +import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_SUPPLIER; +#if !SAME_TYPE +import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR; +#if !VALUE_OBJECT +import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER; +import speiger.src.collections.VALUE_PACKAGE.lists.VALUE_LIST_ITERATOR; +import speiger.src.collections.VALUE_PACKAGE.utils.VALUE_ARRAYS; +#endif +#endif +import speiger.src.collections.objects.collections.ObjectBidirectionalIterator; +#if !TYPE_OBJECT +#if !VALUE_OBJECT +import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator; + +#endif +import speiger.src.collections.objects.lists.ObjectListIterator; +#endif +import speiger.src.collections.objects.sets.AbstractObjectSet; +import speiger.src.collections.objects.sets.ObjectOrderedSet; +import speiger.src.collections.utils.HashUtil; +import speiger.src.collections.utils.SanityChecks; + +/** + * A Type Specific Custom implementation of the HashMap + * Instead of using Wrapper Object Arrays for storing keys and values there is dedicated arrays for storing keys and values. + * Extra to that there is a couple quality of life functions provided + * @Type(T) + * @ValueType(V) + */ +public class IMMUTABLE_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements ORDERED_MAP KEY_VALUE_GENERIC_TYPE +{ + /** The Backing keys array */ + protected transient KEY_TYPE[] keys; + /** The Backing values array */ + protected transient VALUE_TYPE[] values; + /** The Backing array for links between nodes. Left 32 Bits => Previous Entry, Right 32 Bits => Next Entry */ + protected transient long[] links; + /** If a null value is present */ + protected transient boolean containsNull; + /** Index of the Null Value */ + protected transient int nullIndex; + /** Max Index that is allowed to be searched through nullIndex - 1 */ + protected transient int mask; + /** The First Index in the Map */ + protected int firstIndex = -1; + /** The Last Index in the Map */ + protected int lastIndex = -1; + /** EntrySet cache */ + protected transient FastOrderedSet KEY_VALUE_GENERIC_TYPE entrySet; + /** KeySet cache */ + protected transient ORDERED_SET KEY_GENERIC_TYPE keySet; + /** Values cache */ + protected transient VALUE_COLLECTION VALUE_GENERIC_TYPE valuesC; + + /** Amount of Elements stored in the HashMap */ + protected int size; + + /** + * Helper constructor for copying the Map + */ + protected IMMUTABLE_HASH_MAP() {} + +#if !TYPE_OBJECT || !VALUE_OBJECT + /** + * Helper constructor that allow to create a map from boxed values (it will unbox them) + * @param keys the keys that should be put into the map + * @param values the values that should be put into the map. + * @throws IllegalStateException if the keys and values do not match in lenght + */ + public IMMUTABLE_HASH_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values) { + this(keys, values, HashUtil.DEFAULT_LOAD_FACTOR); + } + + /** + * Helper constructor that allow to create a map from boxed values (it will unbox them) + * @param keys the keys that should be put into the map + * @param values the values that should be put into the map. + * @param loadFactor the percentage of how full the backing array can be before they resize + * @throws IllegalStateException if the keys and values do not match in lenght + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + */ + public IMMUTABLE_HASH_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, float loadFactor) { + if(keys.length != values.length) throw new IllegalStateException("Input Arrays are not equal size"); +#if TYPE_OBJECT && VALUE_OBJECT + init(keys, values, 0, keys.length, loadFactor); +#else if TYPE_OBJECT + init(keys, VALUE_ARRAYS.unwrap(values), 0, keys.length, loadFactor); +#else if VALUE_OBJECT + init(ARRAYS.unwrap(keys), values, 0, keys.length, loadFactor); +#else + init(ARRAYS.unwrap(keys), VALUE_ARRAYS.unwrap(values), 0, keys.length, loadFactor); +#endif + } + +#endif + /** + * Helper constructor that allow to create a map from unboxed values + * @param keys the keys that should be put into the map + * @param values the values that should be put into the map. + * @throws IllegalStateException if the keys and values do not match in lenght + */ + public IMMUTABLE_HASH_MAP(KEY_TYPE[] keys, VALUE_TYPE[] values) { + this(keys, values, HashUtil.DEFAULT_LOAD_FACTOR); + } + + /** + * Helper constructor that allow to create a map from unboxed values + * @param keys the keys that should be put into the map + * @param values the values that should be put into the map. + * @param loadFactor the percentage of how full the backing array can be before they resize + * @throws IllegalStateException if the keys and values do not match in lenght + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + */ + public IMMUTABLE_HASH_MAP(KEY_TYPE[] keys, VALUE_TYPE[] values, float loadFactor) { + if(keys.length != values.length) throw new IllegalStateException("Input Arrays are not equal size"); + init(keys, values, 0, keys.length, loadFactor); + } + + /** + * A Helper constructor that allows to create a Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + */ + public IMMUTABLE_HASH_MAP(Map map) { + this(map, HashUtil.DEFAULT_LOAD_FACTOR); + } + + /** + * A Helper constructor that allows to create a Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + * @param loadFactor the percentage of how full the backing array can be before they resize + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + */ + public IMMUTABLE_HASH_MAP(Map map, float loadFactor) { + KEY_TYPE[] keys = NEW_KEY_ARRAY(map.size()); + VALUE_TYPE[] values = NEW_VALUE_ARRAY(keys.length); + int index = 0; + for(Map.Entry entry : map.entrySet()) { + keys[index] = OBJ_TO_KEY(entry.getKey()); + values[index] = OBJ_TO_VALUE(entry.getValue()); + index++; + } + init(keys, values, 0, index, loadFactor); + } + + /** + * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + */ + public IMMUTABLE_HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map) { + this(map, HashUtil.DEFAULT_LOAD_FACTOR); + } + + /** + * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + * @param loadFactor the percentage of how full the backing array can be before they resize + * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 + */ + public IMMUTABLE_HASH_MAP(MAP KEY_VALUE_GENERIC_TYPE map, float loadFactor) { + KEY_TYPE[] keys = NEW_KEY_ARRAY(map.size()); + VALUE_TYPE[] values = NEW_VALUE_ARRAY(keys.length); + int index = 0; + for(MAP.Entry KEY_VALUE_GENERIC_TYPE entry : getFastIterable(map)) { + keys[index] = entry.ENTRY_KEY(); + values[index] = entry.ENTRY_VALUE(); + index++; + } + init(keys, values, 0, index, loadFactor); + } + + protected void init(KEY_TYPE[] a, VALUE_TYPE[] b, int offset, int length, float loadFactor) { + SanityChecks.checkArrayCapacity(a.length, offset, length); + int newSize = HashUtil.arraySize(length+1, loadFactor); + int newMask = newSize - 1; + KEY_TYPE[] newKeys = NEW_KEY_ARRAY(newSize + 1); + VALUE_TYPE[] newValues = NEW_VALUE_ARRAY(newSize + 1); + long[] newLinks = new long[newSize + 1]; + int prev = -1; + for(int i = offset,m=offset+length;i= 0; + } + +#endif + @Override + @Primitive + public boolean containsKey(Object key) { + return findIndex(key) >= 0; + } + +#if !VALUE_OBJECT + @Override + public boolean containsValue(VALUE_TYPE value) { + int index = firstIndex; + while(index != -1) { + if(VALUE_EQUALS(values[index], value)) return true; + index = (int)links[index]; + } + return false; + } + +#endif + @Override + @ValuePrimitive + public boolean containsValue(Object value) { + int index = firstIndex; + while(index != -1) { +#if VALUE_OBJECT + if(VALUE_EQUALS(values[index], value)) return true; +#else + if((value == null && values[index] == getDefaultReturnValue()) || EQUALS_VALUE_TYPE(values[index], value)) return true; +#endif + index = (int)links[index]; + } + return false; + } + + @Override + public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { throw new UnsupportedOperationException(); } + + @Override + public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { throw new UnsupportedOperationException(); } + + @Override + @Deprecated + public CLASS_VALUE_TYPE remove(Object key) { throw new UnsupportedOperationException(); } + +#if !TYPE_OBJECT || !VALUE_OBJECT + @Override + public boolean remove(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } + +#endif + @Override + public boolean remove(Object key, Object value) { throw new UnsupportedOperationException(); } + + @Override + public VALUE_TYPE GET_VALUE(KEY_TYPE key) { + int slot = findIndex(key); + return slot < 0 ? getDefaultReturnValue() : values[slot]; + } + + @Override + public CLASS_VALUE_TYPE get(Object key) { + int slot = findIndex(key); + return VALUE_TO_OBJ(slot < 0 ? getDefaultReturnValue() : values[slot]); + } + +#if TYPE_OBJECT && VALUE_OBJECT + @Override + public VALUE_TYPE getOrDefault(Object key, VALUE_TYPE defaultValue) { + int slot = findIndex(key); + return slot < 0 ? defaultValue : values[slot]; + } + +#else + @Override + public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { + int slot = findIndex(key); + return slot < 0 ? defaultValue : values[slot]; + } + +#endif + @Override + public KEY_TYPE FIRST_ENTRY_KEY() { + if(size == 0) throw new NoSuchElementException(); + return keys[firstIndex]; + } + + @Override + public KEY_TYPE POLL_FIRST_ENTRY_KEY() { throw new UnsupportedOperationException(); } + + @Override + public KEY_TYPE LAST_ENTRY_KEY() { + if(size == 0) throw new NoSuchElementException(); + return keys[lastIndex]; + } + + @Override + public KEY_TYPE POLL_LAST_ENTRY_KEY() { throw new UnsupportedOperationException(); } + + @Override + public VALUE_TYPE FIRST_ENTRY_VALUE() { + if(size == 0) throw new NoSuchElementException(); + return values[firstIndex]; + } + + @Override + public VALUE_TYPE LAST_ENTRY_VALUE() { + if(size == 0) throw new NoSuchElementException(); + return values[lastIndex]; + } + + @Override + public ObjectOrderedSet ENTRY_SET() { + if(entrySet == null) entrySet = new MapEntrySet(); + return entrySet; + } + + @Override + public ORDERED_SET KEY_GENERIC_TYPE keySet() { + if(keySet == null) keySet = new KeySet(); + return keySet; + } + + @Override + public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { + if(valuesC == null) valuesC = new Values(); + return valuesC; + } + + @Override + public IMMUTABLE_HASH_MAP KEY_VALUE_GENERIC_TYPE copy() { + IMMUTABLE_HASH_MAP KEY_VALUE_GENERIC_TYPE map = new IMMUTABLE_HASH_MAPKV_BRACES(); + map.mask = mask; + map.nullIndex = nullIndex; + map.containsNull = containsNull; + map.size = size; + map.keys = Arrays.copyOf(keys, keys.length); + map.values = Arrays.copyOf(values, values.length); + map.links = Arrays.copyOf(links, links.length); + map.firstIndex = firstIndex; + map.lastIndex = lastIndex; + return map; + } + + @Override + public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { + int index = firstIndex; + while(index != -1){ + action.accept(keys[index], values[index]); + index = (int)links[index]; + } + } + + @Override + public boolean replace(KEY_TYPE key, VALUE_TYPE oldValue, VALUE_TYPE newValue) { throw new UnsupportedOperationException(); } + + @Override + public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } + + @Override + public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } + + @Override + public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } + + @Override + public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) { throw new UnsupportedOperationException(); } + + @Override + public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } + + @Override + public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } + + @Override + public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } + + @Override + public int size() { return size; } + + @Override + public void clear() { throw new UnsupportedOperationException(); } + +#if !TYPE_OBJECT + protected int findIndex(KEY_TYPE key) { + if(KEY_EQUALS_NULL(key)) return containsNull ? nullIndex : -(nullIndex + 1); + int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask; + KEY_TYPE current = keys[pos]; + if(KEY_EQUALS_NOT_NULL(current)) { + if(KEY_EQUALS(current, key)) return pos; + while(KEY_EQUALS_NOT_NULL((current = keys[pos = (++pos & mask)]))) + if(KEY_EQUALS(current, key)) return pos; + } + return -(pos + 1); + } + +#endif + protected int findIndex(Object key) { + if(key == null) return containsNull ? nullIndex : -(nullIndex + 1); +#if !TYPE_OBJECT + if(KEY_EQUALS_NULL(CLASS_TO_KEY(key))) return containsNull ? nullIndex : -(nullIndex + 1); +#endif + int pos = HashUtil.mix(key.hashCode()) & mask; + KEY_TYPE current = keys[pos]; + if(KEY_EQUALS_NOT_NULL(current)) { + if(EQUALS_KEY_TYPE(current, key)) return pos; + while(KEY_EQUALS_NOT_NULL((current = keys[pos = (++pos & mask)]))) + if(EQUALS_KEY_TYPE(current, key)) return pos; + } + return -(pos + 1); + } + + protected class MapEntry implements MAP.Entry KEY_VALUE_GENERIC_TYPE, Map.Entry { + public int index = -1; + + public MapEntry() {} + public MapEntry(int index) { + this.index = index; + } + + @Override + public KEY_TYPE ENTRY_KEY() { + return keys[index]; + } + + @Override + public VALUE_TYPE ENTRY_VALUE() { + return values[index]; + } + + @Override + public VALUE_TYPE setValue(VALUE_TYPE value) { throw new UnsupportedOperationException(); } + + @Override + public boolean equals(Object obj) { + if(obj instanceof Map.Entry) { + if(obj instanceof MAP.Entry) { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)obj; + return KEY_EQUALS(keys[index], entry.ENTRY_KEY()) && VALUE_EQUALS(values[index], entry.ENTRY_VALUE()); + } + Map.Entry entry = (Map.Entry)obj; + Object key = entry.getKey(); +#if !TYPE_OBJECT + if(!(key instanceof CLASS_TYPE)) return false; +#endif + Object value = entry.getValue(); +#if TYPE_OBJECT && VALUE_OBJECT + return KEY_EQUALS(keys[index], key) && VALUE_EQUALS(values[index], value); +#else if TYPE_OBJECT + return value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(keys[index], key) && VALUE_EQUALS(values[index], CLASS_TO_VALUE(value)); +#else if VALUE_OBJECT + return key instanceof CLASS_TYPE && KEY_EQUALS(keys[index], CLASS_TO_KEY(key)) && VALUE_EQUALS(values[index], value); +#else + return key instanceof CLASS_TYPE && value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(keys[index], CLASS_TO_KEY(key)) && VALUE_EQUALS(values[index], CLASS_TO_VALUE(value)); +#endif + } + return false; + } + + @Override + public int hashCode() { + return KEY_TO_HASH(keys[index]) ^ VALUE_TO_HASH(values[index]); + } + + @Override + public String toString() { + return KEY_TO_STRING(keys[index]) + "=" + VALUE_TO_STRING(values[index]); + } + } + + private class MapEntrySet extends AbstractObjectSet implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE { + @Override + public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } + @Override + public boolean addAndMoveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } + + @Override + public boolean moveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } + + @Override + public boolean moveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE first() { + return new BasicEntryKV_BRACES(FIRST_ENTRY_KEY(), FIRST_ENTRY_VALUE()); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE last() { + return new BasicEntryKV_BRACES(LAST_ENTRY_KEY(), LAST_ENTRY_VALUE()); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirst() { throw new UnsupportedOperationException(); } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLast() { throw new UnsupportedOperationException(); } + + @Override + public ObjectBidirectionalIterator iterator() { + return new EntryIterator(); + } + + @Override + public ObjectBidirectionalIterator iterator(MAP.Entry KEY_VALUE_GENERIC_TYPE fromElement) { + return new EntryIterator(fromElement.ENTRY_KEY()); + } + + @Override + public ObjectBidirectionalIterator fastIterator() { + return new FastEntryIterator(); + } + + @Override + public ObjectBidirectionalIterator fastIterator(KEY_TYPE fromElement) { + return new FastEntryIterator(fromElement); + } + + @Override + public MapEntrySet copy() { throw new UnsupportedOperationException(); } + + @Override + public void forEach(Consumer action) { + int index = firstIndex; + while(index != -1){ + action.accept(new BasicEntryKV_BRACES(keys[index], values[index])); + index = (int)links[index]; + } + } + + @Override + public void fastForEach(Consumer action) { + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + int index = firstIndex; + while(index != -1){ + entry.set(keys[index], values[index]); + action.accept(entry); + index = (int)links[index]; + } + } + + @Override + public void forEachIndexed(IntObjectConsumer action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + int count = 0; + int index = firstIndex; + while(index != -1) { + action.accept(count++, new BasicEntryKV_BRACES(keys[index], values[index])); + index = (int)links[index]; + } + } + + @Override + public void forEach(E input, ObjectObjectConsumer action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + int index = firstIndex; + while(index != -1) { + action.accept(input, new BasicEntryKV_BRACES(keys[index], values[index])); + index = (int)links[index]; + } + } + + @Override + public boolean matchesAny(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return false; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + int index = firstIndex; + while(index != -1) { + entry.set(keys[index], values[index]); + if(filter.test(entry)) return true; + index = (int)links[index]; + } + return false; + } + + @Override + public boolean matchesNone(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + int index = firstIndex; + while(index != -1) { + entry.set(keys[index], values[index]); + if(filter.test(entry)) return false; + index = (int)links[index]; + } + return true; + } + + @Override + public boolean matchesAll(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + int index = firstIndex; + while(index != -1) { + entry.set(keys[index], values[index]); + if(!filter.test(entry)) return false; + index = (int)links[index]; + } + return true; + } + + @Override + public E reduce(E identity, BiFunction operator) { + Objects.requireNonNull(operator); + E state = identity; + int index = firstIndex; + while(index != -1) { + state = operator.apply(state, new BasicEntryKV_BRACES(keys[index], values[index])); + index = (int)links[index]; + } + return state; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE reduce(ObjectObjectUnaryOperator operator) { + Objects.requireNonNull(operator); + MAP.Entry KEY_VALUE_GENERIC_TYPE state = null; + boolean empty = true; + int index = firstIndex; + while(index != -1) { + if(empty) { + empty = false; + state = new BasicEntryKV_BRACES(keys[index], values[index]); + index = (int)links[index]; + continue; + } + state = operator.apply(state, new BasicEntryKV_BRACES(keys[index], values[index])); + index = (int)links[index]; + } + return state; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE findFirst(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return null; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + int index = firstIndex; + while(index != -1) { + entry.set(keys[index], values[index]); + if(filter.test(entry)) return entry; + index = (int)links[index]; + } + return null; + } + + @Override + public int count(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return 0; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + int result = 0; + int index = firstIndex; + while(index != -1) { + entry.set(keys[index], values[index]); + if(filter.test(entry)) result++; + index = (int)links[index]; + } + return result; + } + + @Override + @Deprecated + public boolean contains(Object o) { + if(o instanceof Map.Entry) { + if(o instanceof MAP.Entry) { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; + int index = IMMUTABLE_HASH_MAP.this.findIndex(entry.ENTRY_KEY()); + if(index >= 0) return VALUE_EQUALS(entry.ENTRY_VALUE(), IMMUTABLE_HASH_MAP.this.values[index]); + } + else { + Map.Entry entry = (Map.Entry)o; + int index = IMMUTABLE_HASH_MAP.this.findIndex(entry.getKey()); + if(index >= 0) return Objects.equals(entry.getValue(), VALUE_TO_OBJ(IMMUTABLE_HASH_MAP.this.values[index])); + } + } + return false; + } + + @Override + @Deprecated + public boolean remove(Object o) { throw new UnsupportedOperationException(); } + + @Override + public int size() { + return IMMUTABLE_HASH_MAP.this.size(); + } + + @Override + public void clear() { throw new UnsupportedOperationException(); } + } + + private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE { +#if TYPE_OBJECT + @Override + @Deprecated + public boolean contains(Object e) { + return containsKey(e); + } + + @Override + public boolean remove(Object o) { throw new UnsupportedOperationException(); } + +#else + @Override + public boolean contains(KEY_TYPE e) { + return containsKey(e); + } + + @Override + public boolean remove(KEY_TYPE o) { throw new UnsupportedOperationException(); } + +#endif + @Override + public boolean add(KEY_TYPE o) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); } + + @Override + public boolean addAndMoveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); } + + @Override + public boolean moveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); } + + @Override + public boolean moveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); } + + @Override + public LIST_ITERATOR KEY_GENERIC_TYPE iterator() { + return new KeyIterator(); + } + + @Override + public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { + return new KeyIterator(fromElement); + } + + @Override + public KeySet copy() { throw new UnsupportedOperationException(); } + + @Override + public int size() { + return IMMUTABLE_HASH_MAP.this.size(); + } + + @Override + public void clear() { throw new UnsupportedOperationException(); } + + @Override + public KEY_TYPE FIRST_KEY() { + return FIRST_ENTRY_KEY(); + } + + @Override + public KEY_TYPE POLL_FIRST_KEY() { throw new UnsupportedOperationException(); } + + @Override + public KEY_TYPE LAST_KEY() { + return LAST_ENTRY_KEY(); + } + + @Override + public KEY_TYPE POLL_LAST_KEY() { throw new UnsupportedOperationException(); } + + @Override + public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { + int index = firstIndex; + while(index != -1){ + action.accept(keys[index]); + index = (int)links[index]; + } + } + + @Override + public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + int count = 0; + int index = firstIndex; + while(index != -1){ + action.accept(count++, keys[index]); + index = (int)links[index]; + } + } + + @Override + public void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + int index = firstIndex; + while(index != -1){ + action.accept(input, keys[index]); + index = (int)links[index]; + } + } + + @Override + public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return false; + int index = firstIndex; + while(index != -1){ + if(filter.test(keys[index])) return true; + index = (int)links[index]; + } + return false; + } + + @Override + public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + int index = firstIndex; + while(index != -1){ + if(filter.test(keys[index])) return false; + index = (int)links[index]; + } + return true; + } + + @Override + public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + int index = firstIndex; + while(index != -1){ + if(!filter.test(keys[index])) return false; + index = (int)links[index]; + } + return true; + } + +#if !TYPE_OBJECT + @Override + public KEY_TYPE reduce(KEY_TYPE identity, SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + KEY_TYPE state = identity; + int index = firstIndex; + while(index != -1) { + state = operator.APPLY_KEY_VALUE(state, keys[index]); + index = (int)links[index]; + } + return state; + } + +#else + @Override + public KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) { + Objects.requireNonNull(operator); + KEY_SPECIAL_TYPE state = identity; + int index = firstIndex; + while(index != -1) { + state = operator.apply(state, keys[index]); + index = (int)links[index]; + } + return state; + } + +#endif + @Override + public KEY_TYPE reduce(SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + KEY_TYPE state = EMPTY_KEY_VALUE; + boolean empty = true; + int index = firstIndex; + while(index != -1) { + if(empty) { + empty = false; + state = keys[index]; + index = (int)links[index]; + continue; + } + state = operator.APPLY_KEY_VALUE(state, keys[index]); + index = (int)links[index]; + } + return state; + } + + @Override + public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return EMPTY_KEY_VALUE; + int index = firstIndex; + while(index != -1){ + if(filter.test(keys[index])) return keys[index]; + index = (int)links[index]; + } + return EMPTY_KEY_VALUE; + } + + @Override + public int count(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return 0; + int index = firstIndex; + int result = 0; + while(index != -1){ + if(filter.test(keys[index])) result++; + index = (int)links[index]; + } + return result; + } + } + + private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { +#if VALUE_OBJECT + @Override + @Deprecated + public boolean contains(Object e) { + return containsValue(e); + } + +#else + @Override + public boolean contains(VALUE_TYPE e) { + return containsValue(e); + } + +#endif + @Override + public boolean add(VALUE_TYPE o) { + throw new UnsupportedOperationException(); + } + + @Override + public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() { + return new ValueIterator(); + } + + @Override + public int size() { + return IMMUTABLE_HASH_MAP.this.size(); + } + + @Override + public void clear() { throw new UnsupportedOperationException(); } + + @Override + public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) { + int index = firstIndex; + while(index != -1){ + action.accept(values[index]); + index = (int)links[index]; + } + } + + @Override + public void forEachIndexed(VALUE_BI_FROM_INT_CONSUMER VALUE_GENERIC_TYPE action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + int count = 0; + int index = firstIndex; + while(index != -1){ + action.accept(count++, values[index]); + index = (int)links[index]; + } + } + + @Override + public void forEach(E input, VALUE_BI_FROM_OBJECT_CONSUMER VSV_GENERIC_TYPE action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + int index = firstIndex; + while(index != -1){ + action.accept(input, values[index]); + index = (int)links[index]; + } + } + + @Override + public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return false; + int index = firstIndex; + while(index != -1){ + if(filter.test(values[index])) return true; + index = (int)links[index]; + } + return false; + } + + @Override + public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + int index = firstIndex; + while(index != -1){ + if(filter.test(values[index])) return false; + index = (int)links[index]; + } + return true; + } + + @Override + public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + int index = firstIndex; + while(index != -1){ + if(!filter.test(values[index])) return false; + index = (int)links[index]; + } + return true; + } + +#if !VALUE_OBJECT + @Override + public VALUE_TYPE reduce(VALUE_TYPE identity, VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + VALUE_TYPE state = identity; + int index = firstIndex; + while(index != -1) { + state = operator.APPLY_VALUE(state, values[index]); + index = (int)links[index]; + } + return state; + } + +#else + @Override + public VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction operator) { + Objects.requireNonNull(operator); + VALUE_SPECIAL_TYPE state = identity; + int index = firstIndex; + while(index != -1) { + state = operator.apply(state, values[index]); + index = (int)links[index]; + } + return state; + } + +#endif + @Override + public VALUE_TYPE reduce(VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + VALUE_TYPE state = EMPTY_VALUE; + boolean empty = true; + int index = firstIndex; + while(index != -1) { + if(empty) { + empty = false; + state = values[index]; + index = (int)links[index]; + continue; + } + state = operator.APPLY_VALUE(state, values[index]); + index = (int)links[index]; + } + return state; + } + + @Override + public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return EMPTY_VALUE; + int index = firstIndex; + while(index != -1){ + if(filter.test(values[index])) return values[index]; + index = (int)links[index]; + } + return EMPTY_VALUE; + } + + @Override + public int count(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return 0; + int result = 0; + int index = firstIndex; + while(index != -1){ + if(filter.test(values[index])) result++; + index = (int)links[index]; + } + return result; + } + } + + private class FastEntryIterator extends MapIterator implements ObjectListIterator { + MapEntry entry = new MapEntry(); + + public FastEntryIterator() {} + public FastEntryIterator(KEY_TYPE from) { + super(from); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { + entry.index = nextEntry(); + return entry; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { + entry.index = previousEntry(); + return entry; + } + + @Override + public void set(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } + + @Override + public void add(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } + } + + private class EntryIterator extends MapIterator implements ObjectListIterator { + + public EntryIterator() {} + public EntryIterator(KEY_TYPE from) { + super(from); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { + return new MapEntry(nextEntry()); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { + return new MapEntry(previousEntry()); + } + + @Override + public void remove() { throw new UnsupportedOperationException(); } + + @Override + public void set(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } + + @Override + public void add(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } + } + + private class KeyIterator extends MapIterator implements LIST_ITERATOR KEY_GENERIC_TYPE { + + public KeyIterator() {} + public KeyIterator(KEY_TYPE from) { + super(from); + } + + @Override + public KEY_TYPE PREVIOUS() { + return keys[previousEntry()]; + } + + @Override + public KEY_TYPE NEXT() { + return keys[nextEntry()]; + } + + @Override + public void set(KEY_TYPE e) { throw new UnsupportedOperationException(); } + @Override + public void add(KEY_TYPE e) { throw new UnsupportedOperationException(); } + } + + private class ValueIterator extends MapIterator implements VALUE_LIST_ITERATOR VALUE_GENERIC_TYPE { + public ValueIterator() {} + + @Override + public VALUE_TYPE VALUE_PREVIOUS() { + return values[previousEntry()]; + } + + @Override + public VALUE_TYPE VALUE_NEXT() { + return values[nextEntry()]; + } + + @Override + public void set(VALUE_TYPE e) { throw new UnsupportedOperationException(); } + + @Override + public void add(VALUE_TYPE e) { throw new UnsupportedOperationException(); } + + } + + private class MapIterator { + int previous = -1; + int next = -1; + int current = -1; + int index = 0; + + MapIterator() { + next = firstIndex; + } + + MapIterator(KEY_TYPE from) { + if(KEY_EQUALS_NULL(from)) { + if(containsNull) { + next = (int) links[nullIndex]; + previous = nullIndex; + } + else throw new NoSuchElementException("The null element is not in the set"); + } + else if(keys[lastIndex] == from) { + previous = lastIndex; + index = size; + } + else { + int pos = HashUtil.mix(KEY_TO_HASH(from)) & mask; + while(KEY_EQUALS_NOT_NULL(keys[pos])) { + if(KEY_EQUALS(keys[pos], from)) { + next = (int)links[pos]; + previous = pos; + break; + } + pos = ++pos & mask; + } + if(previous == -1 && next == -1) + throw new NoSuchElementException("The element was not found"); + } + } + + public boolean hasNext() { + return next != -1; + } + + public boolean hasPrevious() { + return previous != -1; + } + + public int nextIndex() { + ensureIndexKnown(); + return index; + } + + public int previousIndex() { + ensureIndexKnown(); + return index - 1; + } + + public void remove() { throw new UnsupportedOperationException(); } + + public int previousEntry() { + if(!hasPrevious()) throw new NoSuchElementException(); + current = previous; + previous = (int)(links[current] >> 32); + next = current; + if(index >= 0) index--; + return current; + } + + public int nextEntry() { + if(!hasNext()) throw new NoSuchElementException(); + current = next; + next = (int)(links[current]); + previous = current; + if(index >= 0) index++; + return current; + } + + private void ensureIndexKnown() { + if(index == -1) { + if(previous == -1) { + index = 0; + } + else if(next == -1) { + index = size; + } + else { + index = 1; + for(int pos = firstIndex;pos != previous;pos = (int)links[pos], index++); + } + } + } + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/collections/templates/maps/impl/misc/ArrayMap.template b/src/builder/resources/speiger/assets/collections/templates/maps/impl/misc/ArrayMap.template index 3ba4341..11d3ae2 100644 --- a/src/builder/resources/speiger/assets/collections/templates/maps/impl/misc/ArrayMap.template +++ b/src/builder/resources/speiger/assets/collections/templates/maps/impl/misc/ArrayMap.template @@ -1,1456 +1,1458 @@ -package speiger.src.collections.PACKAGE.maps.impl.misc; - -import java.util.Arrays; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Objects; -import java.util.function.Consumer; -import java.util.function.BiFunction; -import java.util.function.Predicate; -#if !TYPE_OBJECT && JDK_TYPE -import java.util.function.PREDICATE; -#endif -#if !SAME_TYPE && JDK_VALUE && !VALUE_OBJECT -import java.util.function.VALUE_PREDICATE; -#endif - -import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.functions.CONSUMER; -import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; -#endif -import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER; -#if !TYPE_OBJECT && !VALUE_OBJECT -import speiger.src.collections.ints.functions.consumer.IntObjectConsumer; -#endif -#if !SAME_TYPE -import speiger.src.collections.ints.functions.consumer.VALUE_BI_FROM_INT_CONSUMER; -#endif -#if !TYPE_OBJECT && !VALUE_BOOLEAN && !JDK_TYPE -import speiger.src.collections.PACKAGE.functions.function.PREDICATE; -#endif -import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; -#if !VALUE_BOOLEAN || !JDK_TYPE -import speiger.src.collections.PACKAGE.functions.function.FUNCTION; -#endif -import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; -#if !SAME_TYPE -import speiger.src.collections.PACKAGE.functions.function.SINGLE_UNARY_OPERATOR; -#endif -import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; -import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP; -import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET; -import speiger.src.collections.PACKAGE.sets.ORDERED_SET; -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; -import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_SUPPLIER; -#if !SAME_TYPE -import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR; -#if !VALUE_OBJECT -import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER; -import speiger.src.collections.VALUE_PACKAGE.lists.VALUE_LIST_ITERATOR; -#endif -#endif -#if !TYPE_OBJECT && !VALUE_OBJECT || !VALUE_OBJECT -import speiger.src.collections.objects.functions.consumer.ObjectObjectConsumer; -#endif -#if !SAME_TYPE -#if VALUE_OBJECT -import speiger.src.collections.objects.functions.consumer.VALUE_BI_FROM_OBJECT_CONSUMER; - -#endif -#if !JDK_VALUE -import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE; -#endif -#endif -#if !VALUE_OBJECT -import speiger.src.collections.objects.collections.ObjectIterator; -#endif -#if !TYPE_OBJECT -#if !VALUE_OBJECT -import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator; - -#endif -import speiger.src.collections.objects.collections.ObjectBidirectionalIterator; -import speiger.src.collections.objects.lists.ObjectListIterator; -import speiger.src.collections.objects.sets.AbstractObjectSet; -import speiger.src.collections.objects.sets.ObjectOrderedSet; -#endif -import speiger.src.collections.utils.HashUtil; - -/** - * A Very Specific Type Specific implementation of a ArrayMap. - * This type of map is for very specific use cases that usaully would have lead to Tupled Lists otherwise. - * It also does not allow duplication (except for array constructors) and checks from last to first. - * It is not designed to be used as a HashMap replacement due to the poor performance it would cause. - * @note in this implementation SubMaps do NOT keep track of parent changes fully. For performance reasons it will just have a start/end index and not values - * Anything within that range will be updated appropiatly a shrink/growth of elements will break SubMaps in some ways. This can be useful but be careful - * @note this implementation does not shrink and only grows. - * @Type(T) - * @ValueType(V) - */ -public class ARRAY_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements ORDERED_MAP KEY_VALUE_GENERIC_TYPE -{ - /** The Backing keys array */ - protected transient KEY_TYPE[] keys; - /** The Backing values array */ - protected transient VALUE_TYPE[] values; - /** Amount of Elements stored in the ArrayMap */ - protected int size = 0; - /** KeySet cache */ - protected ORDERED_SET KEY_GENERIC_TYPE keySet; - /** Values cache */ - protected VALUE_COLLECTION VALUE_GENERIC_TYPE valuesC; - /** EntrySet cache */ - protected FastOrderedSet KEY_VALUE_GENERIC_TYPE entrySet; - - /** - * Default Constructor - */ - public ARRAY_MAP() { - this(HashUtil.DEFAULT_MIN_CAPACITY); - } - - /** - * Constructor that defines the minimum capacity - * @param minCapacity the minimum capacity the HashMap is allowed to be. - * @throws IllegalStateException if the minimum capacity is negative - */ - public ARRAY_MAP(int minCapacity) { - if(minCapacity < 0) throw new IllegalStateException("Minimum Capacity is negative. This is not allowed"); - keys = NEW_KEY_ARRAY(minCapacity); - values = NEW_VALUE_ARRAY(minCapacity); - } - -#if !TYPE_OBJECT || !VALUE_OBJECT - /** - * Helper constructor that allow to create a map from boxed values (it will unbox them) - * @param keys the keys that should be put into the map - * @param values the values that should be put into the map. - * @throws IllegalStateException if the keys and values do not match in length - */ - public ARRAY_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values) { - this(keys, values, keys.length); - } - - /** - * Helper constructor that allow to create a map from boxed values (it will unbox them) with a custom length - * @param keys the keys that should be put into the map - * @param values the values that should be put into the map. - * @param length the amount of values that should be pulled from the array - * @throws IllegalStateException if the keys and values do not match in length - */ - public ARRAY_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, int length) { - this(length); - if(keys.length != values.length) throw new IllegalStateException("Input Arrays are not equal size"); - putAll(keys, values, 0, length); - } - -#endif - /** - * Helper constructor that allow to create a map from unboxed values - * @param keys the keys that should be put into the map - * @param values the values that should be put into the map. - * @throws IllegalStateException if the keys and values do not match in lenght - */ - public ARRAY_MAP(KEY_TYPE[] keys, VALUE_TYPE[] values) { - this(keys, values, keys.length); - } - - /** - * Helper constructor that allow to create a map from unboxed values - * @param keys the keys that should be put into the map - * @param values the values that should be put into the map. - * @param length the amount of values that should be pulled from the array - * @throws IllegalStateException if the keys and values do not match in lenght - */ - public ARRAY_MAP(KEY_TYPE[] keys, VALUE_TYPE[] values, int length) { - this(length); - if(keys.length != values.length) throw new IllegalStateException("Input Arrays are not equal size"); - putAll(keys, values, 0, length); - } - - /** - * A Helper constructor that allows to create a Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - */ - public ARRAY_MAP(Map map) { - this(map.size()); - putAll(map); - } - - /** - * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - */ - public ARRAY_MAP(MAP KEY_VALUE_GENERIC_TYPE map) { - this(map.size()); - for(ObjectIterator iter = getFastIterator(map);iter.hasNext();size++) { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = iter.next(); - keys[size] = entry.ENTRY_KEY(); - values[size] = entry.ENTRY_VALUE(); - } - } - - @Override - public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { - int index = findIndex(key); - if(index < 0) { - insertIndex(size++, key, value); - return getDefaultReturnValue(); - } - VALUE_TYPE oldValue = values[index]; - values[index] = value; - return oldValue; - } - - @Override - public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { - int index = findIndex(key); - if(index < 0) { - insertIndex(size++, key, value); - return getDefaultReturnValue(); - } - else if(VALUE_EQUALS(values[index], getDefaultReturnValue())) { - VALUE_TYPE oldValue = values[index]; - values[index] = value; - return oldValue; - } - return values[index]; - } - -#if VALUE_PRIMITIVES - @Override - public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { - int index = findIndex(key); - if(index < 0) { - insertIndex(size++, key, value); - return getDefaultReturnValue(); - } - VALUE_TYPE oldValue = values[index]; - values[index] += value; - return oldValue; - } - - @Override - public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { - int slot = findIndex(key); - if(slot < 0) return getDefaultReturnValue(); - VALUE_TYPE oldValue = values[slot]; - values[slot] -= value; - if(value < 0 ? (values[slot] >= getDefaultReturnValue()) : (values[slot] <= getDefaultReturnValue())) removeIndex(slot); - return oldValue; - } - -#endif - @Override - public VALUE_TYPE putAndMoveToFirst(KEY_TYPE key, VALUE_TYPE value) { - int index = findIndex(key); - if(index < 0) { - insertIndex(0, key, value); - size++; - return getDefaultReturnValue(); - } - VALUE_TYPE lastValue = values[index]; - values[index] = value; - moveIndexToFirst(index); - return lastValue; - } - - @Override - public VALUE_TYPE putAndMoveToLast(KEY_TYPE key, VALUE_TYPE value) { - int index = findIndex(key); - if(index < 0) { - insertIndex(size++, key, value); - return getDefaultReturnValue(); - } - VALUE_TYPE lastValue = values[index]; - values[index] = value; - moveIndexToLast(index); - return lastValue; - } - - @Override - public boolean moveToFirst(KEY_TYPE key) { - int index = findIndex(key); - if(index > 0) { - moveIndexToFirst(index); - return true; - } - return false; - } - - @Override - public boolean moveToLast(KEY_TYPE key) { - int index = findIndex(key); - if(index >= 0 && index < size-1) { - moveIndexToLast(index); - return true; - } - return false; - } - -#if !TYPE_OBJECT - @Override - public boolean containsKey(KEY_TYPE key) { - return findIndex(key) >= 0; - } - -#endif -#if !VALUE_OBJECT - @Override - public boolean containsValue(VALUE_TYPE value) { - return findValue(value) >= 0; - } - -#endif - @Override - public boolean containsKey(Object key) { - return findIndex(key) >= 0; - } - - @Override - public boolean containsValue(Object value) { - return findValue(value) >= 0; - } - - @Override - public VALUE_TYPE GET_VALUE(KEY_TYPE key) { - int index = findIndex(key); - return index < 0 ? getDefaultReturnValue() : values[index]; - } - -#if TYPE_OBJECT - @Override - public VALUE_TYPE getOrDefault(Object key, VALUE_TYPE defaultValue) { - int index = findIndex(key); - return index < 0 ? defaultValue : values[index]; - } - -#else - @Override - public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { - int index = findIndex(key); - return index < 0 ? defaultValue : values[index]; - } - -#endif - @Override - public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key) { - int index = findIndex(key); - if(index >= 0) { - VALUE_TYPE value = values[index]; - moveIndexToFirst(index); - return value; - } - return getDefaultReturnValue(); - } - - @Override - public VALUE_TYPE getAndMoveToLast(KEY_TYPE key) { - int index = findIndex(key); - if(index >= 0) { - VALUE_TYPE value = values[index]; - moveIndexToLast(index); - return value; - } - return getDefaultReturnValue(); - } - - @Override - public KEY_TYPE FIRST_ENTRY_KEY() { - if(size <= 0) throw new NoSuchElementException(); - return keys[0]; - } - - @Override - public KEY_TYPE LAST_ENTRY_KEY() { - if(size <= 0) throw new NoSuchElementException(); - return keys[size-1]; - } - - @Override - public VALUE_TYPE FIRST_ENTRY_VALUE() { - if(size <= 0) throw new NoSuchElementException(); - return values[0]; - } - - @Override - public VALUE_TYPE LAST_ENTRY_VALUE() { - if(size <= 0) throw new NoSuchElementException(); - return values[size-1]; - } - - @Override - public KEY_TYPE POLL_FIRST_ENTRY_KEY() { - if(size == 0) throw new NoSuchElementException(); - KEY_TYPE result = keys[0]; - removeIndex(0); - return result; - } - - @Override - public KEY_TYPE POLL_LAST_ENTRY_KEY() { - if(size == 0) throw new NoSuchElementException(); - KEY_TYPE result = keys[size-1]; - removeIndex(size-1); - return result; - } - - @Override - public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { - int index = findIndex(key); - if(index < 0) return getDefaultReturnValue(); - VALUE_TYPE value = values[index]; - removeIndex(index); - return value; - } - - @Override - public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { - int index = findIndex(key); - if(index < 0) return defaultValue; - VALUE_TYPE value = values[index]; - removeIndex(index); - return value; - } - -#if !TYPE_OBJECT || !VALUE_OBJECT - @Override - public boolean remove(KEY_TYPE key, VALUE_TYPE value) { - int index = findIndex(key, value); - if(index < 0) return false; - removeIndex(index); - return true; - } - -#endif - @Override - public CLASS_VALUE_TYPE remove(Object key) { - int index = findIndex(key); - if(index < 0) return VALUE_TO_OBJ(getDefaultReturnValue()); - VALUE_TYPE value = values[index]; - removeIndex(index); - return VALUE_TO_OBJ(value); - } - - @Override - public boolean remove(Object key, Object value) { - int index = findIndex(key, value); - if(index < 0) return false; - removeIndex(index); - return true; - } - - @Override - public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { - if(size() <= 0) return; - for(int i = 0;i ENTRY_SET() { - if(entrySet == null) entrySet = new MapEntrySet(); - return entrySet; - } - - @Override - public boolean replace(KEY_TYPE key, VALUE_TYPE oldValue, VALUE_TYPE newValue) { - int index = findIndex(key); - if(index < 0 || values[index] != oldValue) return false; - values[index] = newValue; - return true; - } - - @Override - public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value) { - int index = findIndex(key); - if(index < 0) return getDefaultReturnValue(); - VALUE_TYPE oldValue = values[index]; - values[index] = value; - return oldValue; - } - - @Override - public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); - int index = findIndex(key); - if(index == -1) { - VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, getDefaultReturnValue()); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - insertIndex(size++, key, newValue); - return newValue; - } - VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, values[index]); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - removeIndex(index); - return newValue; - } - values[index] = newValue; - return newValue; - } - - @Override - public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); - int index = findIndex(key); - if(index == -1) { - VALUE_TYPE newValue = mappingFunction.APPLY(key); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - insertIndex(size++, key, newValue); - return newValue; - } - VALUE_TYPE newValue = values[index]; - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - newValue = mappingFunction.APPLY(key); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - values[index] = newValue; - } - return newValue; - } - - @Override - public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) { - Objects.requireNonNull(valueProvider); - int index = findIndex(key); - if(index == -1) { - VALUE_TYPE newValue = valueProvider.VALUE_SUPPLY_GET(); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - insertIndex(size++, key, newValue); - return newValue; - } - VALUE_TYPE newValue = values[index]; - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - newValue = valueProvider.VALUE_SUPPLY_GET(); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - values[index] = newValue; - } - return newValue; - } - - @Override - public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); - int index = findIndex(key); - if(index == -1 || VALUE_EQUALS(values[index], getDefaultReturnValue())) return getDefaultReturnValue(); - VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, values[index]); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - removeIndex(index); - return newValue; - } - values[index] = newValue; - return newValue; - } - - @Override - public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); -#if VALUE_OBJECT - Objects.requireNonNull(value); -#endif - int index = findIndex(key); - VALUE_TYPE newValue = index == -1 || VALUE_EQUALS(values[index], getDefaultReturnValue()) ? value : mappingFunction.APPLY_VALUE(values[index], value); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - if(index >= 0) - removeIndex(index); - } - else if(index == -1) insertIndex(size++, key, newValue); - else values[index] = newValue; - return newValue; - } - - @Override - public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); - for(MAP.Entry KEY_VALUE_GENERIC_TYPE entry : getFastIterable(m)) { - KEY_TYPE key = entry.ENTRY_KEY(); - int index = findIndex(key); - VALUE_TYPE newValue = index == -1 || VALUE_EQUALS(values[index], getDefaultReturnValue()) ? entry.ENTRY_VALUE() : mappingFunction.APPLY_VALUE(values[index], entry.ENTRY_VALUE()); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - if(index >= 0) - removeIndex(index); - } - else if(index == -1) insertIndex(size++, key, newValue); - else values[index] = newValue; - } - } - - @Override - public int size() { - return size; - } - - @Override - public void clear() { - Arrays.fill(keys, 0, size, EMPTY_KEY_VALUE); - Arrays.fill(values, 0, size, EMPTY_VALUE); - size = 0; - } - - public ARRAY_MAP KEY_VALUE_GENERIC_TYPE copy() { - ARRAY_MAP KEY_VALUE_GENERIC_TYPE map = new ARRAY_MAPKV_BRACES(); - map.size = size; - map.keys = Arrays.copyOf(keys, keys.length); - map.values = Arrays.copyOf(values, keys.length); - return map; - } - - protected void moveIndexToFirst(int index) { - if(index == 0) return; - KEY_TYPE key = keys[index]; - VALUE_TYPE value = values[index]; - System.arraycopy(keys, 0, keys, 1, index); - System.arraycopy(values, 0, values, 1, index); - keys[0] = key; - values[0] = value; - } - - protected void moveIndexToLast(int index) { - if(index == size-1) return; - KEY_TYPE key = keys[index]; - VALUE_TYPE value = values[index]; - System.arraycopy(keys, index+1, keys, index, size-index-1); - System.arraycopy(values, index+1, values, index, size-index-1); - keys[size-1] = key; - values[size-1] = value; - } - - protected void grow(int newSize) { - if(newSize < keys.length) return; - newSize = Math.max(newSize, keys.length == 0 ? 2 : keys.length * 2); - keys = Arrays.copyOf(keys, newSize); - values = Arrays.copyOf(values, newSize); - } - - protected void insertIndex(int index, KEY_TYPE key, VALUE_TYPE value) { - grow(size+1); - if(index != size) { - System.arraycopy(keys, index, keys, index+1, size-index); - System.arraycopy(values, index, values, index+1, size-index); - } - keys[index] = key; - values[index] = value; - } - - protected void removeRange(int from, int to) { - if(from < 0 || from >= size) throw new IllegalStateException("From Element "); - int length = to - from; - if(length <= 0) return; - if(to != size) { - System.arraycopy(keys, to, keys, from, size - to); - System.arraycopy(values, to, values, from, size - to); - } - for(int i = 0;i=0;i--) - if(KEY_EQUALS(keys[i], key) && VALUE_EQUALS(values[i], value)) return i; - return -1; - } - -#endif -#if !TYPE_OBJECT - protected int findIndex(KEY_TYPE key) { - for(int i = size-1;i>=0;i--) - if(KEY_EQUALS(keys[i], key)) return i; - return -1; - } - -#endif -#if !VALUE_OBJECT - protected int findValue(VALUE_TYPE value) { - for(int i = size-1;i>=0;i--) - if(VALUE_EQUALS(values[i], value)) return i; - return -1; - } - -#endif - protected int findIndex(Object key, Object value) { - for(int i = size-1;i>=0;i--) - if(EQUALS_KEY_TYPE(keys[i], key) && EQUALS_VALUE_TYPE(values[i], value)) return i; - return -1; - } - - protected int findIndex(Object key) { - for(int i = size-1;i>=0;i--) - if(EQUALS_KEY_TYPE(keys[i], key)) return i; - return -1; - } - - protected int findValue(Object value) { - for(int i = size-1;i>=0;i--) - if(EQUALS_VALUE_TYPE(values[i], value)) return i; - return -1; - } - - private class MapEntrySet extends AbstractObjectSet implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE { - @Override - public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } - @Override - public boolean addAndMoveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } - - @Override - public boolean moveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { - return ARRAY_MAP.this.moveToFirst(o.ENTRY_KEY()); - } - - @Override - public boolean moveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { - return ARRAY_MAP.this.moveToLast(o.ENTRY_KEY()); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE first() { - return new BasicEntryKV_BRACES(FIRST_ENTRY_KEY(), FIRST_ENTRY_VALUE()); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE last() { - return new BasicEntryKV_BRACES(LAST_ENTRY_KEY(), LAST_ENTRY_VALUE()); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirst() { - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(FIRST_ENTRY_KEY(), FIRST_ENTRY_VALUE()); - POLL_FIRST_ENTRY_KEY(); - return entry; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLast() { - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(LAST_ENTRY_KEY(), LAST_ENTRY_VALUE()); - POLL_LAST_ENTRY_KEY(); - return entry; - } - - @Override - public ObjectBidirectionalIterator iterator() { - return new EntryIterator(); - } - - @Override - public ObjectBidirectionalIterator iterator(MAP.Entry KEY_VALUE_GENERIC_TYPE fromElement) { - return new EntryIterator(fromElement.ENTRY_KEY()); - } - - @Override - public ObjectBidirectionalIterator fastIterator() { - return new FastEntryIterator(); - } - - @Override - public ObjectBidirectionalIterator fastIterator(KEY_TYPE fromElement) { - return new FastEntryIterator(fromElement); - } - - @Override - public MapEntrySet copy() { throw new UnsupportedOperationException(); } - - @Override - public void forEach(Consumer action) { - Objects.requireNonNull(action); - for(int i = 0;i action) { - Objects.requireNonNull(action); - if(size() <= 0) return; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - for(int i = 0;i action) { - Objects.requireNonNull(action); - for(int i = 0;i void forEach(E input, ObjectObjectConsumer action) { - Objects.requireNonNull(action); - for(int i = 0;i filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return false; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - for(int i = 0;i filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - for(int i = 0;i filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - for(int i = 0;i E reduce(E identity, BiFunction operator) { - Objects.requireNonNull(operator); - E state = identity; - for(int i = 0;i operator) { - Objects.requireNonNull(operator); - MAP.Entry KEY_VALUE_GENERIC_TYPE state = null; - boolean empty = true; - for(int i = 0;i filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return null; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - for(int i = 0;i filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return 0; - int result = 0; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - for(int i = 0;i= 0) return VALUE_EQUALS(entry.ENTRY_VALUE(), ARRAY_MAP.this.values[index]); - } - else { - Map.Entry entry = (Map.Entry)o; - int index = ARRAY_MAP.this.findIndex(entry.getKey()); - if(index >= 0) return Objects.equals(entry.getValue(), VALUE_TO_OBJ(ARRAY_MAP.this.values[index])); - } - } - return false; - } - - @Override - @Deprecated - public boolean remove(Object o) { - if(o instanceof Map.Entry) { - if(o instanceof MAP.Entry) { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; - return ARRAY_MAP.this.remove(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); - } - Map.Entry entry = (Map.Entry)o; - return ARRAY_MAP.this.remove(entry.getKey(), entry.getValue()); - } - return false; - } - - @Override - public int size() { - return ARRAY_MAP.this.size(); - } - - @Override - public void clear() { - ARRAY_MAP.this.clear(); - } - } - - private class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE { -#if TYPE_OBJECT - @Override - public boolean contains(Object e) { return containsKey(e); } - - @Override - public boolean remove(Object o) { - int oldSize = size; - ARRAY_MAP.this.remove(o); - return size != oldSize; - } - -#else - @Override - public boolean contains(KEY_TYPE e) { return containsKey(e); } - - @Override - public boolean remove(KEY_TYPE o) { - int oldSize = size; - ARRAY_MAP.this.remove(o); - return size != oldSize; - } - -#endif - @Override - public boolean add(KEY_TYPE o) { throw new UnsupportedOperationException(); } - @Override - public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); } - @Override - public boolean addAndMoveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); } - @Override - public boolean moveToFirst(KEY_TYPE o) { return ARRAY_MAP.this.moveToFirst(o); } - @Override - public boolean moveToLast(KEY_TYPE o) { return ARRAY_MAP.this.moveToLast(o); } - @Override - public LIST_ITERATOR KEY_GENERIC_TYPE iterator() { return new KeyIterator(); } - @Override - public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { return new KeyIterator(fromElement); } - @Override - public int size() { return ARRAY_MAP.this.size(); } - @Override - public void clear() { ARRAY_MAP.this.clear(); } - @Override - public KEY_TYPE FIRST_KEY() { return FIRST_ENTRY_KEY(); } - @Override - public KEY_TYPE POLL_FIRST_KEY() { return POLL_FIRST_ENTRY_KEY(); } - @Override - public KEY_TYPE LAST_KEY() { return LAST_ENTRY_KEY(); } - @Override - public KEY_TYPE POLL_LAST_KEY() { return POLL_LAST_ENTRY_KEY(); } - - @Override - public KeySet copy() { throw new UnsupportedOperationException(); } - - @Override - public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { - Objects.requireNonNull(action); - for(int i = 0;i void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { - Objects.requireNonNull(action); - for(int i = 0;i KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) { - Objects.requireNonNull(operator); - KEY_SPECIAL_TYPE state = identity; - for(int i = 0;i VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction operator) { - Objects.requireNonNull(operator); - VALUE_SPECIAL_TYPE state = identity; - for(int i = 0;i { - MapEntry entry = new MapEntry(); - - public FastEntryIterator() {} - public FastEntryIterator(KEY_TYPE from) { - index = findIndex(from); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { - entry.index = nextEntry(); - return entry; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { - entry.index = previousEntry(); - return entry; - } - - @Override - public void set(MAP.Entry KEY_VALUE_GENERIC_TYPE e) { throw new UnsupportedOperationException(); } - @Override - public void add(MAP.Entry KEY_VALUE_GENERIC_TYPE e) { throw new UnsupportedOperationException(); } - } - - private class EntryIterator extends MapIterator implements ObjectListIterator { - MapEntry entry = null; - - public EntryIterator() {} - public EntryIterator(KEY_TYPE from) { - index = findIndex(from); - if(index == -1) throw new NoSuchElementException(); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { - return entry = new MapEntry(nextEntry()); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { - return entry = new MapEntry(previousEntry()); - } - - @Override - public void remove() { - super.remove(); - if(entry != null && entry.index != -1) { - entry.index = -1; - } - } - - @Override - public void set(MAP.Entry KEY_VALUE_GENERIC_TYPE e) { throw new UnsupportedOperationException(); } - @Override - public void add(MAP.Entry KEY_VALUE_GENERIC_TYPE e) { throw new UnsupportedOperationException(); } - } - - private class KeyIterator extends MapIterator implements LIST_ITERATOR KEY_GENERIC_TYPE { - public KeyIterator() {} - public KeyIterator(KEY_TYPE element) { - index = findIndex(element); - if(index == -1) throw new NoSuchElementException(); - } - - @Override - public KEY_TYPE PREVIOUS() { - return keys[previousEntry()]; - } - - @Override - public KEY_TYPE NEXT() { - return keys[nextEntry()]; - } - - @Override - public void set(KEY_TYPE e) { throw new UnsupportedOperationException(); } - - @Override - public void add(KEY_TYPE e) { throw new UnsupportedOperationException(); } - } - - private class ValueIterator extends MapIterator implements VALUE_LIST_ITERATOR VALUE_GENERIC_TYPE { - @Override - public VALUE_TYPE VALUE_PREVIOUS() { - return values[previousEntry()]; - } - - @Override - public VALUE_TYPE VALUE_NEXT() { - return values[nextEntry()]; - } - - @Override - public void set(VALUE_TYPE e) { throw new UnsupportedOperationException(); } - - @Override - public void add(VALUE_TYPE e) { throw new UnsupportedOperationException(); } - } - - private class MapIterator { - int index; - int lastReturned = -1; - - public boolean hasNext() { - return index < size; - } - - public boolean hasPrevious() { - return index > 0; - } - - public int nextIndex() { - return index; - } - - public int previousIndex() { - return index-1; - } - - public void remove() { - if(lastReturned == -1) throw new IllegalStateException(); - removeIndex(lastReturned); - if(lastReturned < index) - index--; - lastReturned = -1; - } - - public int previousEntry() { - if(!hasPrevious()) throw new NoSuchElementException(); - index--; - return (lastReturned = index); - } - - public int nextEntry() { - if(!hasNext()) throw new NoSuchElementException(); - lastReturned = index; - return index++; - } - - public int skip(int amount) { - if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed"); - int steps = Math.min(amount, size() - index); - index += steps; - if(steps > 0) lastReturned = Math.min(index-1, size()-1); - return steps; - } - - public int back(int amount) { - if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed"); - int steps = Math.min(amount, index); - index -= steps; - if(steps > 0) lastReturned = Math.min(index, size()-1); - return steps; - } - } - - private class MapEntry implements MAP.Entry KEY_VALUE_GENERIC_TYPE, Map.Entry { - int index = -1; - - public MapEntry() {} - public MapEntry(int index) { - this.index = index; - } - - @Override - public KEY_TYPE ENTRY_KEY() { - return keys[index]; - } - - @Override - public VALUE_TYPE ENTRY_VALUE() { - return values[index]; - } - - @Override - public VALUE_TYPE setValue(VALUE_TYPE value) { - VALUE_TYPE oldValue = values[index]; - values[index] = value; - return oldValue; - } - - @Override - public boolean equals(Object obj) { - if(obj instanceof Map.Entry) { - if(obj instanceof MAP.Entry) { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)obj; - return KEY_EQUALS(keys[index], entry.ENTRY_KEY()) && VALUE_EQUALS(values[index], entry.ENTRY_VALUE()); - } - Map.Entry entry = (Map.Entry)obj; - Object key = entry.getKey(); - Object value = entry.getValue(); -#if TYPE_OBJECT && VALUE_OBJECT - return KEY_EQUALS(keys[index], key) && VALUE_EQUALS(values[index], value); -#else if TYPE_OBJECT - return value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(keys[index], key) && VALUE_EQUALS(values[index], CLASS_TO_VALUE(value)); -#else if VALUE_OBJECT - return key instanceof CLASS_TYPE && KEY_EQUALS(keys[index], CLASS_TO_KEY(key)) && VALUE_EQUALS(values[index], value); -#else - return key instanceof CLASS_TYPE && value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(keys[index], CLASS_TO_KEY(key)) && VALUE_EQUALS(values[index], CLASS_TO_VALUE(value)); -#endif - } - return false; - } - - @Override - public int hashCode() { - return KEY_TO_HASH(keys[index]) ^ VALUE_TO_HASH(values[index]); - } - - @Override - public String toString() { - return KEY_TO_STRING(keys[index]) + "=" + VALUE_TO_STRING(values[index]); - } - } +package speiger.src.collections.PACKAGE.maps.impl.misc; + +import java.util.Arrays; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Objects; +import java.util.function.Consumer; +import java.util.function.BiFunction; +import java.util.function.Predicate; +#if !TYPE_OBJECT && JDK_TYPE +import java.util.function.PREDICATE; +#endif +#if !SAME_TYPE && JDK_VALUE && !VALUE_OBJECT +import java.util.function.VALUE_PREDICATE; +#endif + +import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.functions.CONSUMER; +import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; +#endif +import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER; +#if !TYPE_OBJECT && !VALUE_OBJECT +import speiger.src.collections.ints.functions.consumer.IntObjectConsumer; +#endif +#if !SAME_TYPE && !TYPE_INT +import speiger.src.collections.ints.functions.consumer.VALUE_BI_FROM_INT_CONSUMER; +#endif +#if !TYPE_OBJECT && !VALUE_BOOLEAN && !JDK_TYPE +import speiger.src.collections.PACKAGE.functions.function.PREDICATE; +#endif +#if !TYPE_INT || !SAME_TYPE +import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; +#endif +#if !VALUE_BOOLEAN || !JDK_TYPE +import speiger.src.collections.PACKAGE.functions.function.FUNCTION; +#endif +import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; +#if !SAME_TYPE +import speiger.src.collections.PACKAGE.functions.function.SINGLE_UNARY_OPERATOR; +#endif +import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; +import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP; +import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET; +import speiger.src.collections.PACKAGE.sets.ORDERED_SET; +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; +import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_SUPPLIER; +#if !SAME_TYPE +import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR; +#if !VALUE_OBJECT +import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER; +import speiger.src.collections.VALUE_PACKAGE.lists.VALUE_LIST_ITERATOR; +#endif +#endif +#if !TYPE_OBJECT && !VALUE_OBJECT || !VALUE_OBJECT +import speiger.src.collections.objects.functions.consumer.ObjectObjectConsumer; +#endif +#if !SAME_TYPE +#if VALUE_OBJECT +import speiger.src.collections.objects.functions.consumer.VALUE_BI_FROM_OBJECT_CONSUMER; + +#endif +#if !JDK_VALUE +import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE; +#endif +#endif +#if !VALUE_OBJECT +import speiger.src.collections.objects.collections.ObjectIterator; +#endif +#if !TYPE_OBJECT +#if !VALUE_OBJECT +import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator; + +#endif +import speiger.src.collections.objects.collections.ObjectBidirectionalIterator; +import speiger.src.collections.objects.lists.ObjectListIterator; +import speiger.src.collections.objects.sets.AbstractObjectSet; +import speiger.src.collections.objects.sets.ObjectOrderedSet; +#endif +import speiger.src.collections.utils.HashUtil; + +/** + * A Very Specific Type Specific implementation of a ArrayMap. + * This type of map is for very specific use cases that usaully would have lead to Tupled Lists otherwise. + * It also does not allow duplication (except for array constructors) and checks from last to first. + * It is not designed to be used as a HashMap replacement due to the poor performance it would cause. + * @note in this implementation SubMaps do NOT keep track of parent changes fully. For performance reasons it will just have a start/end index and not values + * Anything within that range will be updated appropiatly a shrink/growth of elements will break SubMaps in some ways. This can be useful but be careful + * @note this implementation does not shrink and only grows. + * @Type(T) + * @ValueType(V) + */ +public class ARRAY_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements ORDERED_MAP KEY_VALUE_GENERIC_TYPE +{ + /** The Backing keys array */ + protected transient KEY_TYPE[] keys; + /** The Backing values array */ + protected transient VALUE_TYPE[] values; + /** Amount of Elements stored in the ArrayMap */ + protected int size = 0; + /** KeySet cache */ + protected ORDERED_SET KEY_GENERIC_TYPE keySet; + /** Values cache */ + protected VALUE_COLLECTION VALUE_GENERIC_TYPE valuesC; + /** EntrySet cache */ + protected FastOrderedSet KEY_VALUE_GENERIC_TYPE entrySet; + + /** + * Default Constructor + */ + public ARRAY_MAP() { + this(HashUtil.DEFAULT_MIN_CAPACITY); + } + + /** + * Constructor that defines the minimum capacity + * @param minCapacity the minimum capacity the HashMap is allowed to be. + * @throws IllegalStateException if the minimum capacity is negative + */ + public ARRAY_MAP(int minCapacity) { + if(minCapacity < 0) throw new IllegalStateException("Minimum Capacity is negative. This is not allowed"); + keys = NEW_KEY_ARRAY(minCapacity); + values = NEW_VALUE_ARRAY(minCapacity); + } + +#if !TYPE_OBJECT || !VALUE_OBJECT + /** + * Helper constructor that allow to create a map from boxed values (it will unbox them) + * @param keys the keys that should be put into the map + * @param values the values that should be put into the map. + * @throws IllegalStateException if the keys and values do not match in length + */ + public ARRAY_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values) { + this(keys, values, keys.length); + } + + /** + * Helper constructor that allow to create a map from boxed values (it will unbox them) with a custom length + * @param keys the keys that should be put into the map + * @param values the values that should be put into the map. + * @param length the amount of values that should be pulled from the array + * @throws IllegalStateException if the keys and values do not match in length + */ + public ARRAY_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, int length) { + this(length); + if(keys.length != values.length) throw new IllegalStateException("Input Arrays are not equal size"); + putAll(keys, values, 0, length); + } + +#endif + /** + * Helper constructor that allow to create a map from unboxed values + * @param keys the keys that should be put into the map + * @param values the values that should be put into the map. + * @throws IllegalStateException if the keys and values do not match in lenght + */ + public ARRAY_MAP(KEY_TYPE[] keys, VALUE_TYPE[] values) { + this(keys, values, keys.length); + } + + /** + * Helper constructor that allow to create a map from unboxed values + * @param keys the keys that should be put into the map + * @param values the values that should be put into the map. + * @param length the amount of values that should be pulled from the array + * @throws IllegalStateException if the keys and values do not match in lenght + */ + public ARRAY_MAP(KEY_TYPE[] keys, VALUE_TYPE[] values, int length) { + this(length); + if(keys.length != values.length) throw new IllegalStateException("Input Arrays are not equal size"); + putAll(keys, values, 0, length); + } + + /** + * A Helper constructor that allows to create a Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + */ + public ARRAY_MAP(Map map) { + this(map.size()); + putAll(map); + } + + /** + * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + */ + public ARRAY_MAP(MAP KEY_VALUE_GENERIC_TYPE map) { + this(map.size()); + for(ObjectIterator iter = getFastIterator(map);iter.hasNext();size++) { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = iter.next(); + keys[size] = entry.ENTRY_KEY(); + values[size] = entry.ENTRY_VALUE(); + } + } + + @Override + public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { + int index = findIndex(key); + if(index < 0) { + insertIndex(size++, key, value); + return getDefaultReturnValue(); + } + VALUE_TYPE oldValue = values[index]; + values[index] = value; + return oldValue; + } + + @Override + public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { + int index = findIndex(key); + if(index < 0) { + insertIndex(size++, key, value); + return getDefaultReturnValue(); + } + else if(VALUE_EQUALS(values[index], getDefaultReturnValue())) { + VALUE_TYPE oldValue = values[index]; + values[index] = value; + return oldValue; + } + return values[index]; + } + +#if VALUE_PRIMITIVES + @Override + public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { + int index = findIndex(key); + if(index < 0) { + insertIndex(size++, key, value); + return getDefaultReturnValue(); + } + VALUE_TYPE oldValue = values[index]; + values[index] += value; + return oldValue; + } + + @Override + public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { + int slot = findIndex(key); + if(slot < 0) return getDefaultReturnValue(); + VALUE_TYPE oldValue = values[slot]; + values[slot] -= value; + if(value < 0 ? (values[slot] >= getDefaultReturnValue()) : (values[slot] <= getDefaultReturnValue())) removeIndex(slot); + return oldValue; + } + +#endif + @Override + public VALUE_TYPE putAndMoveToFirst(KEY_TYPE key, VALUE_TYPE value) { + int index = findIndex(key); + if(index < 0) { + insertIndex(0, key, value); + size++; + return getDefaultReturnValue(); + } + VALUE_TYPE lastValue = values[index]; + values[index] = value; + moveIndexToFirst(index); + return lastValue; + } + + @Override + public VALUE_TYPE putAndMoveToLast(KEY_TYPE key, VALUE_TYPE value) { + int index = findIndex(key); + if(index < 0) { + insertIndex(size++, key, value); + return getDefaultReturnValue(); + } + VALUE_TYPE lastValue = values[index]; + values[index] = value; + moveIndexToLast(index); + return lastValue; + } + + @Override + public boolean moveToFirst(KEY_TYPE key) { + int index = findIndex(key); + if(index > 0) { + moveIndexToFirst(index); + return true; + } + return false; + } + + @Override + public boolean moveToLast(KEY_TYPE key) { + int index = findIndex(key); + if(index >= 0 && index < size-1) { + moveIndexToLast(index); + return true; + } + return false; + } + +#if !TYPE_OBJECT + @Override + public boolean containsKey(KEY_TYPE key) { + return findIndex(key) >= 0; + } + +#endif +#if !VALUE_OBJECT + @Override + public boolean containsValue(VALUE_TYPE value) { + return findValue(value) >= 0; + } + +#endif + @Override + public boolean containsKey(Object key) { + return findIndex(key) >= 0; + } + + @Override + public boolean containsValue(Object value) { + return findValue(value) >= 0; + } + + @Override + public VALUE_TYPE GET_VALUE(KEY_TYPE key) { + int index = findIndex(key); + return index < 0 ? getDefaultReturnValue() : values[index]; + } + +#if TYPE_OBJECT + @Override + public VALUE_TYPE getOrDefault(Object key, VALUE_TYPE defaultValue) { + int index = findIndex(key); + return index < 0 ? defaultValue : values[index]; + } + +#else + @Override + public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { + int index = findIndex(key); + return index < 0 ? defaultValue : values[index]; + } + +#endif + @Override + public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key) { + int index = findIndex(key); + if(index >= 0) { + VALUE_TYPE value = values[index]; + moveIndexToFirst(index); + return value; + } + return getDefaultReturnValue(); + } + + @Override + public VALUE_TYPE getAndMoveToLast(KEY_TYPE key) { + int index = findIndex(key); + if(index >= 0) { + VALUE_TYPE value = values[index]; + moveIndexToLast(index); + return value; + } + return getDefaultReturnValue(); + } + + @Override + public KEY_TYPE FIRST_ENTRY_KEY() { + if(size <= 0) throw new NoSuchElementException(); + return keys[0]; + } + + @Override + public KEY_TYPE LAST_ENTRY_KEY() { + if(size <= 0) throw new NoSuchElementException(); + return keys[size-1]; + } + + @Override + public VALUE_TYPE FIRST_ENTRY_VALUE() { + if(size <= 0) throw new NoSuchElementException(); + return values[0]; + } + + @Override + public VALUE_TYPE LAST_ENTRY_VALUE() { + if(size <= 0) throw new NoSuchElementException(); + return values[size-1]; + } + + @Override + public KEY_TYPE POLL_FIRST_ENTRY_KEY() { + if(size == 0) throw new NoSuchElementException(); + KEY_TYPE result = keys[0]; + removeIndex(0); + return result; + } + + @Override + public KEY_TYPE POLL_LAST_ENTRY_KEY() { + if(size == 0) throw new NoSuchElementException(); + KEY_TYPE result = keys[size-1]; + removeIndex(size-1); + return result; + } + + @Override + public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { + int index = findIndex(key); + if(index < 0) return getDefaultReturnValue(); + VALUE_TYPE value = values[index]; + removeIndex(index); + return value; + } + + @Override + public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { + int index = findIndex(key); + if(index < 0) return defaultValue; + VALUE_TYPE value = values[index]; + removeIndex(index); + return value; + } + +#if !TYPE_OBJECT || !VALUE_OBJECT + @Override + public boolean remove(KEY_TYPE key, VALUE_TYPE value) { + int index = findIndex(key, value); + if(index < 0) return false; + removeIndex(index); + return true; + } + +#endif + @Override + public CLASS_VALUE_TYPE remove(Object key) { + int index = findIndex(key); + if(index < 0) return VALUE_TO_OBJ(getDefaultReturnValue()); + VALUE_TYPE value = values[index]; + removeIndex(index); + return VALUE_TO_OBJ(value); + } + + @Override + public boolean remove(Object key, Object value) { + int index = findIndex(key, value); + if(index < 0) return false; + removeIndex(index); + return true; + } + + @Override + public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { + if(size() <= 0) return; + for(int i = 0;i ENTRY_SET() { + if(entrySet == null) entrySet = new MapEntrySet(); + return entrySet; + } + + @Override + public boolean replace(KEY_TYPE key, VALUE_TYPE oldValue, VALUE_TYPE newValue) { + int index = findIndex(key); + if(index < 0 || values[index] != oldValue) return false; + values[index] = newValue; + return true; + } + + @Override + public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value) { + int index = findIndex(key); + if(index < 0) return getDefaultReturnValue(); + VALUE_TYPE oldValue = values[index]; + values[index] = value; + return oldValue; + } + + @Override + public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); + int index = findIndex(key); + if(index == -1) { + VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, getDefaultReturnValue()); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + insertIndex(size++, key, newValue); + return newValue; + } + VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, values[index]); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + removeIndex(index); + return newValue; + } + values[index] = newValue; + return newValue; + } + + @Override + public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); + int index = findIndex(key); + if(index == -1) { + VALUE_TYPE newValue = mappingFunction.APPLY(key); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + insertIndex(size++, key, newValue); + return newValue; + } + VALUE_TYPE newValue = values[index]; + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + newValue = mappingFunction.APPLY(key); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + values[index] = newValue; + } + return newValue; + } + + @Override + public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) { + Objects.requireNonNull(valueProvider); + int index = findIndex(key); + if(index == -1) { + VALUE_TYPE newValue = valueProvider.VALUE_SUPPLY_GET(); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + insertIndex(size++, key, newValue); + return newValue; + } + VALUE_TYPE newValue = values[index]; + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + newValue = valueProvider.VALUE_SUPPLY_GET(); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + values[index] = newValue; + } + return newValue; + } + + @Override + public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); + int index = findIndex(key); + if(index == -1 || VALUE_EQUALS(values[index], getDefaultReturnValue())) return getDefaultReturnValue(); + VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, values[index]); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + removeIndex(index); + return newValue; + } + values[index] = newValue; + return newValue; + } + + @Override + public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); +#if VALUE_OBJECT + Objects.requireNonNull(value); +#endif + int index = findIndex(key); + VALUE_TYPE newValue = index == -1 || VALUE_EQUALS(values[index], getDefaultReturnValue()) ? value : mappingFunction.APPLY_VALUE(values[index], value); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + if(index >= 0) + removeIndex(index); + } + else if(index == -1) insertIndex(size++, key, newValue); + else values[index] = newValue; + return newValue; + } + + @Override + public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); + for(MAP.Entry KEY_VALUE_GENERIC_TYPE entry : getFastIterable(m)) { + KEY_TYPE key = entry.ENTRY_KEY(); + int index = findIndex(key); + VALUE_TYPE newValue = index == -1 || VALUE_EQUALS(values[index], getDefaultReturnValue()) ? entry.ENTRY_VALUE() : mappingFunction.APPLY_VALUE(values[index], entry.ENTRY_VALUE()); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + if(index >= 0) + removeIndex(index); + } + else if(index == -1) insertIndex(size++, key, newValue); + else values[index] = newValue; + } + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { + Arrays.fill(keys, 0, size, EMPTY_KEY_VALUE); + Arrays.fill(values, 0, size, EMPTY_VALUE); + size = 0; + } + + public ARRAY_MAP KEY_VALUE_GENERIC_TYPE copy() { + ARRAY_MAP KEY_VALUE_GENERIC_TYPE map = new ARRAY_MAPKV_BRACES(); + map.size = size; + map.keys = Arrays.copyOf(keys, keys.length); + map.values = Arrays.copyOf(values, keys.length); + return map; + } + + protected void moveIndexToFirst(int index) { + if(index == 0) return; + KEY_TYPE key = keys[index]; + VALUE_TYPE value = values[index]; + System.arraycopy(keys, 0, keys, 1, index); + System.arraycopy(values, 0, values, 1, index); + keys[0] = key; + values[0] = value; + } + + protected void moveIndexToLast(int index) { + if(index == size-1) return; + KEY_TYPE key = keys[index]; + VALUE_TYPE value = values[index]; + System.arraycopy(keys, index+1, keys, index, size-index-1); + System.arraycopy(values, index+1, values, index, size-index-1); + keys[size-1] = key; + values[size-1] = value; + } + + protected void grow(int newSize) { + if(newSize < keys.length) return; + newSize = Math.max(newSize, keys.length == 0 ? 2 : keys.length * 2); + keys = Arrays.copyOf(keys, newSize); + values = Arrays.copyOf(values, newSize); + } + + protected void insertIndex(int index, KEY_TYPE key, VALUE_TYPE value) { + grow(size+1); + if(index != size) { + System.arraycopy(keys, index, keys, index+1, size-index); + System.arraycopy(values, index, values, index+1, size-index); + } + keys[index] = key; + values[index] = value; + } + + protected void removeRange(int from, int to) { + if(from < 0 || from >= size) throw new IllegalStateException("From Element "); + int length = to - from; + if(length <= 0) return; + if(to != size) { + System.arraycopy(keys, to, keys, from, size - to); + System.arraycopy(values, to, values, from, size - to); + } + for(int i = 0;i=0;i--) + if(KEY_EQUALS(keys[i], key) && VALUE_EQUALS(values[i], value)) return i; + return -1; + } + +#endif +#if !TYPE_OBJECT + protected int findIndex(KEY_TYPE key) { + for(int i = size-1;i>=0;i--) + if(KEY_EQUALS(keys[i], key)) return i; + return -1; + } + +#endif +#if !VALUE_OBJECT + protected int findValue(VALUE_TYPE value) { + for(int i = size-1;i>=0;i--) + if(VALUE_EQUALS(values[i], value)) return i; + return -1; + } + +#endif + protected int findIndex(Object key, Object value) { + for(int i = size-1;i>=0;i--) + if(EQUALS_KEY_TYPE(keys[i], key) && EQUALS_VALUE_TYPE(values[i], value)) return i; + return -1; + } + + protected int findIndex(Object key) { + for(int i = size-1;i>=0;i--) + if(EQUALS_KEY_TYPE(keys[i], key)) return i; + return -1; + } + + protected int findValue(Object value) { + for(int i = size-1;i>=0;i--) + if(EQUALS_VALUE_TYPE(values[i], value)) return i; + return -1; + } + + private class MapEntrySet extends AbstractObjectSet implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE { + @Override + public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } + @Override + public boolean addAndMoveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } + + @Override + public boolean moveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { + return ARRAY_MAP.this.moveToFirst(o.ENTRY_KEY()); + } + + @Override + public boolean moveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { + return ARRAY_MAP.this.moveToLast(o.ENTRY_KEY()); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE first() { + return new BasicEntryKV_BRACES(FIRST_ENTRY_KEY(), FIRST_ENTRY_VALUE()); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE last() { + return new BasicEntryKV_BRACES(LAST_ENTRY_KEY(), LAST_ENTRY_VALUE()); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirst() { + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(FIRST_ENTRY_KEY(), FIRST_ENTRY_VALUE()); + POLL_FIRST_ENTRY_KEY(); + return entry; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLast() { + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(LAST_ENTRY_KEY(), LAST_ENTRY_VALUE()); + POLL_LAST_ENTRY_KEY(); + return entry; + } + + @Override + public ObjectBidirectionalIterator iterator() { + return new EntryIterator(); + } + + @Override + public ObjectBidirectionalIterator iterator(MAP.Entry KEY_VALUE_GENERIC_TYPE fromElement) { + return new EntryIterator(fromElement.ENTRY_KEY()); + } + + @Override + public ObjectBidirectionalIterator fastIterator() { + return new FastEntryIterator(); + } + + @Override + public ObjectBidirectionalIterator fastIterator(KEY_TYPE fromElement) { + return new FastEntryIterator(fromElement); + } + + @Override + public MapEntrySet copy() { throw new UnsupportedOperationException(); } + + @Override + public void forEach(Consumer action) { + Objects.requireNonNull(action); + for(int i = 0;i action) { + Objects.requireNonNull(action); + if(size() <= 0) return; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + for(int i = 0;i action) { + Objects.requireNonNull(action); + for(int i = 0;i void forEach(E input, ObjectObjectConsumer action) { + Objects.requireNonNull(action); + for(int i = 0;i filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return false; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + for(int i = 0;i filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + for(int i = 0;i filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + for(int i = 0;i E reduce(E identity, BiFunction operator) { + Objects.requireNonNull(operator); + E state = identity; + for(int i = 0;i operator) { + Objects.requireNonNull(operator); + MAP.Entry KEY_VALUE_GENERIC_TYPE state = null; + boolean empty = true; + for(int i = 0;i filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return null; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + for(int i = 0;i filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return 0; + int result = 0; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + for(int i = 0;i= 0) return VALUE_EQUALS(entry.ENTRY_VALUE(), ARRAY_MAP.this.values[index]); + } + else { + Map.Entry entry = (Map.Entry)o; + int index = ARRAY_MAP.this.findIndex(entry.getKey()); + if(index >= 0) return Objects.equals(entry.getValue(), VALUE_TO_OBJ(ARRAY_MAP.this.values[index])); + } + } + return false; + } + + @Override + @Deprecated + public boolean remove(Object o) { + if(o instanceof Map.Entry) { + if(o instanceof MAP.Entry) { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; + return ARRAY_MAP.this.remove(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); + } + Map.Entry entry = (Map.Entry)o; + return ARRAY_MAP.this.remove(entry.getKey(), entry.getValue()); + } + return false; + } + + @Override + public int size() { + return ARRAY_MAP.this.size(); + } + + @Override + public void clear() { + ARRAY_MAP.this.clear(); + } + } + + private class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE { +#if TYPE_OBJECT + @Override + public boolean contains(Object e) { return containsKey(e); } + + @Override + public boolean remove(Object o) { + int oldSize = size; + ARRAY_MAP.this.remove(o); + return size != oldSize; + } + +#else + @Override + public boolean contains(KEY_TYPE e) { return containsKey(e); } + + @Override + public boolean remove(KEY_TYPE o) { + int oldSize = size; + ARRAY_MAP.this.remove(o); + return size != oldSize; + } + +#endif + @Override + public boolean add(KEY_TYPE o) { throw new UnsupportedOperationException(); } + @Override + public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); } + @Override + public boolean addAndMoveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); } + @Override + public boolean moveToFirst(KEY_TYPE o) { return ARRAY_MAP.this.moveToFirst(o); } + @Override + public boolean moveToLast(KEY_TYPE o) { return ARRAY_MAP.this.moveToLast(o); } + @Override + public LIST_ITERATOR KEY_GENERIC_TYPE iterator() { return new KeyIterator(); } + @Override + public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { return new KeyIterator(fromElement); } + @Override + public int size() { return ARRAY_MAP.this.size(); } + @Override + public void clear() { ARRAY_MAP.this.clear(); } + @Override + public KEY_TYPE FIRST_KEY() { return FIRST_ENTRY_KEY(); } + @Override + public KEY_TYPE POLL_FIRST_KEY() { return POLL_FIRST_ENTRY_KEY(); } + @Override + public KEY_TYPE LAST_KEY() { return LAST_ENTRY_KEY(); } + @Override + public KEY_TYPE POLL_LAST_KEY() { return POLL_LAST_ENTRY_KEY(); } + + @Override + public KeySet copy() { throw new UnsupportedOperationException(); } + + @Override + public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { + Objects.requireNonNull(action); + for(int i = 0;i void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { + Objects.requireNonNull(action); + for(int i = 0;i KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) { + Objects.requireNonNull(operator); + KEY_SPECIAL_TYPE state = identity; + for(int i = 0;i VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction operator) { + Objects.requireNonNull(operator); + VALUE_SPECIAL_TYPE state = identity; + for(int i = 0;i { + MapEntry entry = new MapEntry(); + + public FastEntryIterator() {} + public FastEntryIterator(KEY_TYPE from) { + index = findIndex(from); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { + entry.index = nextEntry(); + return entry; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { + entry.index = previousEntry(); + return entry; + } + + @Override + public void set(MAP.Entry KEY_VALUE_GENERIC_TYPE e) { throw new UnsupportedOperationException(); } + @Override + public void add(MAP.Entry KEY_VALUE_GENERIC_TYPE e) { throw new UnsupportedOperationException(); } + } + + private class EntryIterator extends MapIterator implements ObjectListIterator { + MapEntry entry = null; + + public EntryIterator() {} + public EntryIterator(KEY_TYPE from) { + index = findIndex(from); + if(index == -1) throw new NoSuchElementException(); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { + return entry = new MapEntry(nextEntry()); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { + return entry = new MapEntry(previousEntry()); + } + + @Override + public void remove() { + super.remove(); + if(entry != null && entry.index != -1) { + entry.index = -1; + } + } + + @Override + public void set(MAP.Entry KEY_VALUE_GENERIC_TYPE e) { throw new UnsupportedOperationException(); } + @Override + public void add(MAP.Entry KEY_VALUE_GENERIC_TYPE e) { throw new UnsupportedOperationException(); } + } + + private class KeyIterator extends MapIterator implements LIST_ITERATOR KEY_GENERIC_TYPE { + public KeyIterator() {} + public KeyIterator(KEY_TYPE element) { + index = findIndex(element); + if(index == -1) throw new NoSuchElementException(); + } + + @Override + public KEY_TYPE PREVIOUS() { + return keys[previousEntry()]; + } + + @Override + public KEY_TYPE NEXT() { + return keys[nextEntry()]; + } + + @Override + public void set(KEY_TYPE e) { throw new UnsupportedOperationException(); } + + @Override + public void add(KEY_TYPE e) { throw new UnsupportedOperationException(); } + } + + private class ValueIterator extends MapIterator implements VALUE_LIST_ITERATOR VALUE_GENERIC_TYPE { + @Override + public VALUE_TYPE VALUE_PREVIOUS() { + return values[previousEntry()]; + } + + @Override + public VALUE_TYPE VALUE_NEXT() { + return values[nextEntry()]; + } + + @Override + public void set(VALUE_TYPE e) { throw new UnsupportedOperationException(); } + + @Override + public void add(VALUE_TYPE e) { throw new UnsupportedOperationException(); } + } + + private class MapIterator { + int index; + int lastReturned = -1; + + public boolean hasNext() { + return index < size; + } + + public boolean hasPrevious() { + return index > 0; + } + + public int nextIndex() { + return index; + } + + public int previousIndex() { + return index-1; + } + + public void remove() { + if(lastReturned == -1) throw new IllegalStateException(); + removeIndex(lastReturned); + if(lastReturned < index) + index--; + lastReturned = -1; + } + + public int previousEntry() { + if(!hasPrevious()) throw new NoSuchElementException(); + index--; + return (lastReturned = index); + } + + public int nextEntry() { + if(!hasNext()) throw new NoSuchElementException(); + lastReturned = index; + return index++; + } + + public int skip(int amount) { + if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed"); + int steps = Math.min(amount, size() - index); + index += steps; + if(steps > 0) lastReturned = Math.min(index-1, size()-1); + return steps; + } + + public int back(int amount) { + if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed"); + int steps = Math.min(amount, index); + index -= steps; + if(steps > 0) lastReturned = Math.min(index, size()-1); + return steps; + } + } + + private class MapEntry implements MAP.Entry KEY_VALUE_GENERIC_TYPE, Map.Entry { + int index = -1; + + public MapEntry() {} + public MapEntry(int index) { + this.index = index; + } + + @Override + public KEY_TYPE ENTRY_KEY() { + return keys[index]; + } + + @Override + public VALUE_TYPE ENTRY_VALUE() { + return values[index]; + } + + @Override + public VALUE_TYPE setValue(VALUE_TYPE value) { + VALUE_TYPE oldValue = values[index]; + values[index] = value; + return oldValue; + } + + @Override + public boolean equals(Object obj) { + if(obj instanceof Map.Entry) { + if(obj instanceof MAP.Entry) { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)obj; + return KEY_EQUALS(keys[index], entry.ENTRY_KEY()) && VALUE_EQUALS(values[index], entry.ENTRY_VALUE()); + } + Map.Entry entry = (Map.Entry)obj; + Object key = entry.getKey(); + Object value = entry.getValue(); +#if TYPE_OBJECT && VALUE_OBJECT + return KEY_EQUALS(keys[index], key) && VALUE_EQUALS(values[index], value); +#else if TYPE_OBJECT + return value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(keys[index], key) && VALUE_EQUALS(values[index], CLASS_TO_VALUE(value)); +#else if VALUE_OBJECT + return key instanceof CLASS_TYPE && KEY_EQUALS(keys[index], CLASS_TO_KEY(key)) && VALUE_EQUALS(values[index], value); +#else + return key instanceof CLASS_TYPE && value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(keys[index], CLASS_TO_KEY(key)) && VALUE_EQUALS(values[index], CLASS_TO_VALUE(value)); +#endif + } + return false; + } + + @Override + public int hashCode() { + return KEY_TO_HASH(keys[index]) ^ VALUE_TO_HASH(values[index]); + } + + @Override + public String toString() { + return KEY_TO_STRING(keys[index]) + "=" + VALUE_TO_STRING(values[index]); + } + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/collections/templates/maps/impl/misc/EnumMap.template b/src/builder/resources/speiger/assets/collections/templates/maps/impl/misc/EnumMap.template index 0b8494a..345d19c 100644 --- a/src/builder/resources/speiger/assets/collections/templates/maps/impl/misc/EnumMap.template +++ b/src/builder/resources/speiger/assets/collections/templates/maps/impl/misc/EnumMap.template @@ -1,738 +1,738 @@ -package speiger.src.collections.PACKAGE.maps.impl.misc; - -import java.util.Arrays; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Objects; -import java.util.function.Consumer; -#if VALUE_BOOLEAN -import java.util.function.Predicate; -#endif - - -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; -#if !VALUE_OBJECT -import speiger.src.collections.objects.collections.ObjectIterator; -#endif -import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_SUPPLIER; -import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR; -import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; -#if !VALUE_OBJECT -import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; -#endif -#if !VALUE_BOOLEAN -import speiger.src.collections.PACKAGE.functions.function.FUNCTION; -#endif -import speiger.src.collections.objects.maps.abstracts.ABSTRACT_MAP; -import speiger.src.collections.objects.maps.interfaces.MAP; -import speiger.src.collections.objects.sets.AbstractObjectSet; -import speiger.src.collections.objects.sets.ObjectSet; - -/** - * A Type Specific EnumMap implementation that allows for Primitive Values. - * Unlike javas implementation this one does not jump around between a single long or long array implementation based around the enum size - * This will cause a bit more memory usage but allows for a simpler implementation. - * @Type(T) - * @ValueType(V) - */ -public class ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE -{ - /** Enum Type that is being used */ - protected Class keyType; - /** The Backing keys array. */ - protected transient T[] keys; - /** The Backing values array */ - protected transient VALUE_TYPE[] values; - /** The Backing array that indicates which index is present or not */ - protected transient long[] present; - /** Amount of Elements stored in the ArrayMap */ - protected int size = 0; - /** EntrySet cache */ - protected transient ObjectSet entrySet; - /** KeySet cache */ - protected transient ObjectSet keySet; - /** Values cache */ - protected transient VALUE_COLLECTION VALUE_GENERIC_TYPE valuesC; - - protected ENUM_MAP() { - - } - /** - * Default Constructor - * @param keyType the type of Enum that should be used - */ - public ENUM_MAP(Class keyType) { - this.keyType = keyType; - keys = getKeyUniverse(keyType); - values = NEW_VALUE_ARRAY(keys.length); - present = new long[((keys.length - 1) >> 6) + 1]; - } - -#if !VALUE_OBJECT - /** - * Helper constructor that allow to create a EnumMap from boxed values (it will unbox them) - * @param keys the keys that should be put into the EnumMap - * @param values the values that should be put into the EnumMap. - * @throws IllegalStateException if the keys and values do not match in lenght - */ - public ENUM_MAP(T[] keys, CLASS_VALUE_TYPE[] values) { - if(keys.length <= 0) throw new IllegalArgumentException("Empty Array are not allowed"); - if(keys.length != values.length) throw new IllegalArgumentException("Keys and Values have to be the same size"); - keyType = keys[0].getDeclaringClass(); - this.keys = getKeyUniverse(keyType); - this.values = NEW_VALUE_ARRAY(this.keys.length); - present = new long[((this.keys.length - 1) >> 6) + 1]; - putAll(keys, values); - } - -#endif - /** - * Helper constructor that allow to create a EnumMap from unboxed values - * @param keys the keys that should be put into the map - * @param values the values that should be put into the map. - * @throws IllegalStateException if the keys and values do not match in lenght - */ - public ENUM_MAP(T[] keys, VALUE_TYPE[] values) { - if(keys.length <= 0) throw new IllegalArgumentException("Empty Array are not allowed"); - if(keys.length != values.length) throw new IllegalArgumentException("Keys and Values have to be the same size"); - keyType = keys[0].getDeclaringClass(); - this.keys = getKeyUniverse(keyType); - this.values = NEW_VALUE_ARRAY(this.keys.length); - present = new long[((this.keys.length - 1) >> 6) + 1]; - putAll(keys, values); - } - - /** - * A Helper constructor that allows to create a EnumMap with exactly the same values as the provided map. - * @param map the values that should be present in the map - */ - public ENUM_MAP(Map map) { - if(map instanceof ENUM_MAP) { - ENUM_MAP KEY_VALUE_GENERIC_TYPE enumMap = (ENUM_MAP KEY_VALUE_GENERIC_TYPE)map; - keyType = enumMap.keyType; - keys = enumMap.keys; - values = enumMap.values.clone(); - present = enumMap.present.clone(); - size = enumMap.size; - } - else if(map.isEmpty()) throw new IllegalArgumentException("Empty Maps are not allowed"); - else { - keyType = map.keySet().iterator().next().getDeclaringClass(); - this.keys = getKeyUniverse(keyType); - this.values = NEW_VALUE_ARRAY(keys.length); - present = new long[((keys.length - 1) >> 6) + 1]; - putAll(map); - } - } - - /** - * A Type Specific Helper function that allows to create a new EnumMap with exactly the same values as the provided map. - * @param map the values that should be present in the map - */ - public ENUM_MAP(MAP KEY_VALUE_GENERIC_TYPE map) { - if(map instanceof ENUM_MAP) { - ENUM_MAP KEY_VALUE_GENERIC_TYPE enumMap = (ENUM_MAP KEY_VALUE_GENERIC_TYPE)map; - keyType = enumMap.keyType; - keys = enumMap.keys; - values = enumMap.values.clone(); - present = enumMap.present.clone(); - size = enumMap.size; - } - else if(map.isEmpty()) throw new IllegalArgumentException("Empty Maps are not allowed"); - else { - keyType = map.keySet().iterator().next().getDeclaringClass(); - this.keys = getKeyUniverse(keyType); - this.values = NEW_VALUE_ARRAY(keys.length); - present = new long[((keys.length - 1) >> 6) + 1]; - putAll(map); - } - } - - @Override - public VALUE_TYPE put(T key, VALUE_TYPE value) { - int index = key.ordinal(); - if(isSet(index)) { - VALUE_TYPE result = values[index]; - values[index] = value; - return result; - } - set(index); - values[index] = value; - return getDefaultReturnValue(); - } - - @Override - public VALUE_TYPE putIfAbsent(T key, VALUE_TYPE value) { - int index = key.ordinal(); - if(isSet(index)) { - if(VALUE_EQUALS(values[index], getDefaultReturnValue())) { - VALUE_TYPE oldValue = values[index]; - values[index] = value; - return oldValue; - } - return values[index]; - } - set(index); - values[index] = value; - return getDefaultReturnValue(); - } - -#if VALUE_PRIMITIVES - @Override - public VALUE_TYPE addTo(T key, VALUE_TYPE value) { - int index = key.ordinal(); - if(isSet(index)) { - VALUE_TYPE result = values[index]; - values[index] += value; - return result; - } - set(index); - values[index] = value; - return getDefaultReturnValue(); - } - - @Override - public VALUE_TYPE subFrom(T key, VALUE_TYPE value) { - int index = key.ordinal(); - if(!isSet(index)) return getDefaultReturnValue(); - VALUE_TYPE oldValue = values[index]; - values[index] -= value; - if(value < 0 ? (values[index] >= getDefaultReturnValue()) : (values[index] <= getDefaultReturnValue())) { - clear(index); - values[index] = EMPTY_VALUE; - } - return oldValue; - } -#endif - @Override - public boolean containsKey(Object key) { - if(!keyType.isInstance(key)) return false; - return isSet(((T)key).ordinal()); - } - -#if VALUE_OBJECT - @Override - public boolean containsValue(Object value) { - for(int i = 0;i ENTRY_SET() { - if(entrySet == null) entrySet = new EntrySet(); - return entrySet; - } - - @Override - public ObjectSet keySet() { - if(keySet == null) keySet = new KeySet(); - return keySet; - } - - @Override - public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { - if(valuesC == null) valuesC = new Values(); - return valuesC; - } - - @Override - public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { - if(size() <= 0) return; - for(int i = 0,m=keys.length;i> 6] |= (1L << index); - size++; - } - protected void clear(int index) { - size--; - present[index >> 6] &= ~(1L << index); - onNodeRemoved(index); - } - protected boolean isSet(int index) { return (present[index >> 6] & (1L << index)) != 0; } - - protected static > K[] getKeyUniverse(Class keyType) { - return keyType.getEnumConstants(); - } - - class EntrySet extends AbstractObjectSet { - - @Override - public boolean contains(Object o) { - if(o instanceof Map.Entry) { - if(o instanceof MAP.Entry) { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; - if(!keyType.isInstance(entry.ENTRY_KEY())) return false; - int index = ((T)entry.ENTRY_KEY()).ordinal(); - if(index >= 0 && ENUM_MAP.this.isSet(index)) return VALUE_EQUALS(entry.ENTRY_VALUE(), ENUM_MAP.this.values[index]); - } - else { - Map.Entry entry = (Map.Entry)o; - if(!keyType.isInstance(entry.getKey())) return false; - int index = ((T)entry.getKey()).ordinal(); - if(index >= 0 && ENUM_MAP.this.isSet(index)) return Objects.equals(entry.getValue(), VALUE_TO_OBJ(ENUM_MAP.this.values[index])); - } - } - return false; - } - - @Override - public boolean remove(Object o) { - if(o instanceof Map.Entry) { - if(o instanceof MAP.Entry) { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; - return ENUM_MAP.this.remove(entry.getKey(), entry.ENTRY_VALUE()); - } - Map.Entry entry = (java.util.Map.Entry)o; - return ENUM_MAP.this.remove(entry.getKey(), entry.getValue()); - } - return false; - } - - @Override - public void forEach(Consumer action) { - if(size() <= 0) return; - for(int i = 0,m=keys.length;i iterator() { - return new EntryIterator(); - } - - @Override - public int size() { - return ENUM_MAP.this.size(); - } - - @Override - public void clear() { - ENUM_MAP.this.clear(); - } - } - - class KeySet extends AbstractObjectSet { - - @Override - public boolean contains(Object o) { - return containsKey(o); - } - - @Override - public boolean remove(Object o) { - int size = size(); - ENUM_MAP.this.remove(o); - return size != size(); - } - - @Override - public ObjectIterator iterator() { - return new KeyIterator(); - } - - @Override - public int size() { - return ENUM_MAP.this.size(); - } - - @Override - public void clear() { - ENUM_MAP.this.clear(); - } - } - - class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { - - @Override - public boolean add(VALUE_TYPE o) { throw new UnsupportedOperationException(); } - -#if TYPE_OBJECT - @Override - public boolean contains(Object e) { return containsValue(e); } - -#else - @Override - public boolean contains(VALUE_TYPE e) { return containsValue(e); } - -#endif - @Override - public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() { - return new ValueIterator(); - } - - @Override - public int size() { - return ENUM_MAP.this.size(); - } - - @Override - public void clear() { - ENUM_MAP.this.clear(); - } - } - - class EntryIterator extends MapIterator implements ObjectIterator { - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { - return new MapEntry(nextEntry()); - } - } - - class KeyIterator extends MapIterator implements ObjectIterator { - @Override - public T next() { - return keys[nextEntry()]; - } - } - - class ValueIterator extends MapIterator implements VALUE_ITERATOR VALUE_GENERIC_TYPE { - @Override - public VALUE_TYPE VALUE_NEXT() { - return values[nextEntry()]; - } - } - - class MapIterator { - int index; - int lastReturnValue = -1; - int nextIndex = -1; - - public boolean hasNext() { - if(nextIndex == -1 && index < values.length) { - while(index < values.length && !isSet(index++)); - nextIndex = index-1; - if(!isSet(nextIndex)) nextIndex = -1; - } - return nextIndex != -1; - } - - public int nextEntry() { - if(!hasNext()) throw new NoSuchElementException(); - lastReturnValue = nextIndex; - nextIndex = -1; - return lastReturnValue; - } - - public void remove() { - if(lastReturnValue == -1) throw new IllegalStateException(); - clear(lastReturnValue); - values[lastReturnValue] = EMPTY_VALUE; - lastReturnValue = -1; - } - } - - protected class MapEntry implements MAP.Entry KEY_VALUE_GENERIC_TYPE, Map.Entry { - public int index = -1; - - public MapEntry() {} - public MapEntry(int index) { - this.index = index; - } - - @Override - public KEY_TYPE ENTRY_KEY() { - return keys[index]; - } - - @Override - public VALUE_TYPE ENTRY_VALUE() { - return values[index]; - } - - @Override - public VALUE_TYPE setValue(VALUE_TYPE value) { - VALUE_TYPE oldValue = values[index]; - values[index] = value; - return oldValue; - } - - @Override - public boolean equals(Object obj) { - if(obj instanceof Map.Entry) { - if(obj instanceof MAP.Entry) { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)obj; - return KEY_EQUALS(keys[index], entry.ENTRY_KEY()) && VALUE_EQUALS(values[index], entry.ENTRY_VALUE()); - } - Map.Entry entry = (Map.Entry)obj; - Object key = entry.getKey(); - Object value = entry.getValue(); -#if TYPE_OBJECT && VALUE_OBJECT - return KEY_EQUALS(keys[index], key) && VALUE_EQUALS(values[index], value); -#else if TYPE_OBJECT - return value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(keys[index], key) && VALUE_EQUALS(values[index], CLASS_TO_VALUE(value)); -#else if VALUE_OBJECT - return key instanceof CLASS_TYPE && KEY_EQUALS(keys[index], CLASS_TO_KEY(key)) && VALUE_EQUALS(values[index], value); -#else - return key instanceof CLASS_TYPE && value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(keys[index], CLASS_TO_KEY(key)) && VALUE_EQUALS(values[index], CLASS_TO_VALUE(value)); -#endif - } - return false; - } - - @Override - public int hashCode() { - return KEY_TO_HASH(keys[index]) ^ VALUE_TO_HASH(values[index]); - } - - @Override - public String toString() { - return KEY_TO_STRING(keys[index]) + "=" + VALUE_TO_STRING(values[index]); - } - } -} +package speiger.src.collections.PACKAGE.maps.impl.misc; + +import java.util.Arrays; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Objects; +import java.util.function.Consumer; +#if VALUE_BOOLEAN +import java.util.function.Predicate; +#endif + + +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; +#if !VALUE_OBJECT +import speiger.src.collections.objects.collections.ObjectIterator; +#endif +import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_SUPPLIER; +import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR; +import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; +#if !VALUE_OBJECT +import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; +#endif +#if !VALUE_BOOLEAN +import speiger.src.collections.PACKAGE.functions.function.FUNCTION; +#endif +import speiger.src.collections.objects.maps.abstracts.ABSTRACT_MAP; +import speiger.src.collections.objects.maps.interfaces.MAP; +import speiger.src.collections.objects.sets.AbstractObjectSet; +import speiger.src.collections.objects.sets.ObjectSet; + +/** + * A Type Specific EnumMap implementation that allows for Primitive Values. + * Unlike javas implementation this one does not jump around between a single long or long array implementation based around the enum size + * This will cause a bit more memory usage but allows for a simpler implementation. + * @Type(T) + * @ValueType(V) + */ +public class ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE +{ + /** Enum Type that is being used */ + protected Class keyType; + /** The Backing keys array. */ + protected transient T[] keys; + /** The Backing values array */ + protected transient VALUE_TYPE[] values; + /** The Backing array that indicates which index is present or not */ + protected transient long[] present; + /** Amount of Elements stored in the ArrayMap */ + protected int size = 0; + /** EntrySet cache */ + protected transient ObjectSet entrySet; + /** KeySet cache */ + protected transient ObjectSet keySet; + /** Values cache */ + protected transient VALUE_COLLECTION VALUE_GENERIC_TYPE valuesC; + + protected ENUM_MAP() { + + } + /** + * Default Constructor + * @param keyType the type of Enum that should be used + */ + public ENUM_MAP(Class keyType) { + this.keyType = keyType; + keys = getKeyUniverse(keyType); + values = NEW_VALUE_ARRAY(keys.length); + present = new long[((keys.length - 1) >> 6) + 1]; + } + +#if !VALUE_OBJECT + /** + * Helper constructor that allow to create a EnumMap from boxed values (it will unbox them) + * @param keys the keys that should be put into the EnumMap + * @param values the values that should be put into the EnumMap. + * @throws IllegalStateException if the keys and values do not match in lenght + */ + public ENUM_MAP(T[] keys, CLASS_VALUE_TYPE[] values) { + if(keys.length <= 0) throw new IllegalArgumentException("Empty Array are not allowed"); + if(keys.length != values.length) throw new IllegalArgumentException("Keys and Values have to be the same size"); + keyType = keys[0].getDeclaringClass(); + this.keys = getKeyUniverse(keyType); + this.values = NEW_VALUE_ARRAY(this.keys.length); + present = new long[((this.keys.length - 1) >> 6) + 1]; + putAll(keys, values); + } + +#endif + /** + * Helper constructor that allow to create a EnumMap from unboxed values + * @param keys the keys that should be put into the map + * @param values the values that should be put into the map. + * @throws IllegalStateException if the keys and values do not match in lenght + */ + public ENUM_MAP(T[] keys, VALUE_TYPE[] values) { + if(keys.length <= 0) throw new IllegalArgumentException("Empty Array are not allowed"); + if(keys.length != values.length) throw new IllegalArgumentException("Keys and Values have to be the same size"); + keyType = keys[0].getDeclaringClass(); + this.keys = getKeyUniverse(keyType); + this.values = NEW_VALUE_ARRAY(this.keys.length); + present = new long[((this.keys.length - 1) >> 6) + 1]; + putAll(keys, values); + } + + /** + * A Helper constructor that allows to create a EnumMap with exactly the same values as the provided map. + * @param map the values that should be present in the map + */ + public ENUM_MAP(Map map) { + if(map instanceof ENUM_MAP) { + ENUM_MAP KEY_VALUE_GENERIC_TYPE enumMap = (ENUM_MAP KEY_VALUE_GENERIC_TYPE)map; + keyType = enumMap.keyType; + keys = enumMap.keys; + values = enumMap.values.clone(); + present = enumMap.present.clone(); + size = enumMap.size; + } + else if(map.isEmpty()) throw new IllegalArgumentException("Empty Maps are not allowed"); + else { + keyType = map.keySet().iterator().next().getDeclaringClass(); + this.keys = getKeyUniverse(keyType); + this.values = NEW_VALUE_ARRAY(keys.length); + present = new long[((keys.length - 1) >> 6) + 1]; + putAll(map); + } + } + + /** + * A Type Specific Helper function that allows to create a new EnumMap with exactly the same values as the provided map. + * @param map the values that should be present in the map + */ + public ENUM_MAP(MAP KEY_VALUE_GENERIC_TYPE map) { + if(map instanceof ENUM_MAP) { + ENUM_MAP KEY_VALUE_GENERIC_TYPE enumMap = (ENUM_MAP KEY_VALUE_GENERIC_TYPE)map; + keyType = enumMap.keyType; + keys = enumMap.keys; + values = enumMap.values.clone(); + present = enumMap.present.clone(); + size = enumMap.size; + } + else if(map.isEmpty()) throw new IllegalArgumentException("Empty Maps are not allowed"); + else { + keyType = map.keySet().iterator().next().getDeclaringClass(); + this.keys = getKeyUniverse(keyType); + this.values = NEW_VALUE_ARRAY(keys.length); + present = new long[((keys.length - 1) >> 6) + 1]; + putAll(map); + } + } + + @Override + public VALUE_TYPE put(T key, VALUE_TYPE value) { + int index = key.ordinal(); + if(isSet(index)) { + VALUE_TYPE result = values[index]; + values[index] = value; + return result; + } + set(index); + values[index] = value; + return getDefaultReturnValue(); + } + + @Override + public VALUE_TYPE putIfAbsent(T key, VALUE_TYPE value) { + int index = key.ordinal(); + if(isSet(index)) { + if(VALUE_EQUALS(values[index], getDefaultReturnValue())) { + VALUE_TYPE oldValue = values[index]; + values[index] = value; + return oldValue; + } + return values[index]; + } + set(index); + values[index] = value; + return getDefaultReturnValue(); + } + +#if VALUE_PRIMITIVES + @Override + public VALUE_TYPE addTo(T key, VALUE_TYPE value) { + int index = key.ordinal(); + if(isSet(index)) { + VALUE_TYPE result = values[index]; + values[index] += value; + return result; + } + set(index); + values[index] = value; + return getDefaultReturnValue(); + } + + @Override + public VALUE_TYPE subFrom(T key, VALUE_TYPE value) { + int index = key.ordinal(); + if(!isSet(index)) return getDefaultReturnValue(); + VALUE_TYPE oldValue = values[index]; + values[index] -= value; + if(value < 0 ? (values[index] >= getDefaultReturnValue()) : (values[index] <= getDefaultReturnValue())) { + clear(index); + values[index] = EMPTY_VALUE; + } + return oldValue; + } +#endif + @Override + public boolean containsKey(Object key) { + if(!keyType.isInstance(key)) return false; + return isSet(((T)key).ordinal()); + } + +#if VALUE_OBJECT + @Override + public boolean containsValue(Object value) { + for(int i = 0;i ENTRY_SET() { + if(entrySet == null) entrySet = new EntrySet(); + return entrySet; + } + + @Override + public ObjectSet keySet() { + if(keySet == null) keySet = new KeySet(); + return keySet; + } + + @Override + public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { + if(valuesC == null) valuesC = new Values(); + return valuesC; + } + + @Override + public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { + if(size() <= 0) return; + for(int i = 0,m=keys.length;i> 6] |= (1L << index); + size++; + } + protected void clear(int index) { + size--; + present[index >> 6] &= ~(1L << index); + onNodeRemoved(index); + } + protected boolean isSet(int index) { return (present[index >> 6] & (1L << index)) != 0; } + + protected static > K[] getKeyUniverse(Class keyType) { + return keyType.getEnumConstants(); + } + + class EntrySet extends AbstractObjectSet { + + @Override + public boolean contains(Object o) { + if(o instanceof Map.Entry) { + if(o instanceof MAP.Entry) { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; + if(!keyType.isInstance(entry.ENTRY_KEY())) return false; + int index = ((T)entry.ENTRY_KEY()).ordinal(); + if(index >= 0 && ENUM_MAP.this.isSet(index)) return VALUE_EQUALS(entry.ENTRY_VALUE(), ENUM_MAP.this.values[index]); + } + else { + Map.Entry entry = (Map.Entry)o; + if(!keyType.isInstance(entry.getKey())) return false; + int index = ((T)entry.getKey()).ordinal(); + if(index >= 0 && ENUM_MAP.this.isSet(index)) return Objects.equals(entry.getValue(), VALUE_TO_OBJ(ENUM_MAP.this.values[index])); + } + } + return false; + } + + @Override + public boolean remove(Object o) { + if(o instanceof Map.Entry) { + if(o instanceof MAP.Entry) { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; + return ENUM_MAP.this.remove(entry.getKey(), entry.ENTRY_VALUE()); + } + Map.Entry entry = (java.util.Map.Entry)o; + return ENUM_MAP.this.remove(entry.getKey(), entry.getValue()); + } + return false; + } + + @Override + public void forEach(Consumer action) { + if(size() <= 0) return; + for(int i = 0,m=keys.length;i iterator() { + return new EntryIterator(); + } + + @Override + public int size() { + return ENUM_MAP.this.size(); + } + + @Override + public void clear() { + ENUM_MAP.this.clear(); + } + } + + class KeySet extends AbstractObjectSet { + + @Override + public boolean contains(Object o) { + return containsKey(o); + } + + @Override + public boolean remove(Object o) { + int size = size(); + ENUM_MAP.this.remove(o); + return size != size(); + } + + @Override + public ObjectIterator iterator() { + return new KeyIterator(); + } + + @Override + public int size() { + return ENUM_MAP.this.size(); + } + + @Override + public void clear() { + ENUM_MAP.this.clear(); + } + } + + class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { + + @Override + public boolean add(VALUE_TYPE o) { throw new UnsupportedOperationException(); } + +#if TYPE_OBJECT + @Override + public boolean contains(Object e) { return containsValue(e); } + +#else + @Override + public boolean contains(VALUE_TYPE e) { return containsValue(e); } + +#endif + @Override + public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() { + return new ValueIterator(); + } + + @Override + public int size() { + return ENUM_MAP.this.size(); + } + + @Override + public void clear() { + ENUM_MAP.this.clear(); + } + } + + class EntryIterator extends MapIterator implements ObjectIterator { + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { + return new MapEntry(nextEntry()); + } + } + + class KeyIterator extends MapIterator implements ObjectIterator { + @Override + public T next() { + return keys[nextEntry()]; + } + } + + class ValueIterator extends MapIterator implements VALUE_ITERATOR VALUE_GENERIC_TYPE { + @Override + public VALUE_TYPE VALUE_NEXT() { + return values[nextEntry()]; + } + } + + class MapIterator { + int index; + int lastReturnValue = -1; + int nextIndex = -1; + + public boolean hasNext() { + if(nextIndex == -1 && index < values.length) { + while(index < values.length && !isSet(index++)); + nextIndex = index-1; + if(!isSet(nextIndex)) nextIndex = -1; + } + return nextIndex != -1; + } + + public int nextEntry() { + if(!hasNext()) throw new NoSuchElementException(); + lastReturnValue = nextIndex; + nextIndex = -1; + return lastReturnValue; + } + + public void remove() { + if(lastReturnValue == -1) throw new IllegalStateException(); + clear(lastReturnValue); + values[lastReturnValue] = EMPTY_VALUE; + lastReturnValue = -1; + } + } + + protected class MapEntry implements MAP.Entry KEY_VALUE_GENERIC_TYPE, Map.Entry { + public int index = -1; + + public MapEntry() {} + public MapEntry(int index) { + this.index = index; + } + + @Override + public KEY_TYPE ENTRY_KEY() { + return keys[index]; + } + + @Override + public VALUE_TYPE ENTRY_VALUE() { + return values[index]; + } + + @Override + public VALUE_TYPE setValue(VALUE_TYPE value) { + VALUE_TYPE oldValue = values[index]; + values[index] = value; + return oldValue; + } + + @Override + public boolean equals(Object obj) { + if(obj instanceof Map.Entry) { + if(obj instanceof MAP.Entry) { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)obj; + return KEY_EQUALS(keys[index], entry.ENTRY_KEY()) && VALUE_EQUALS(values[index], entry.ENTRY_VALUE()); + } + Map.Entry entry = (Map.Entry)obj; + Object key = entry.getKey(); + Object value = entry.getValue(); +#if TYPE_OBJECT && VALUE_OBJECT + return KEY_EQUALS(keys[index], key) && VALUE_EQUALS(values[index], value); +#else if TYPE_OBJECT + return value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(keys[index], key) && VALUE_EQUALS(values[index], CLASS_TO_VALUE(value)); +#else if VALUE_OBJECT + return key instanceof CLASS_TYPE && KEY_EQUALS(keys[index], CLASS_TO_KEY(key)) && VALUE_EQUALS(values[index], value); +#else + return key instanceof CLASS_TYPE && value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(keys[index], CLASS_TO_KEY(key)) && VALUE_EQUALS(values[index], CLASS_TO_VALUE(value)); +#endif + } + return false; + } + + @Override + public int hashCode() { + return KEY_TO_HASH(keys[index]) ^ VALUE_TO_HASH(values[index]); + } + + @Override + public String toString() { + return KEY_TO_STRING(keys[index]) + "=" + VALUE_TO_STRING(values[index]); + } + } +} diff --git a/src/builder/resources/speiger/assets/collections/templates/maps/impl/misc/LinkedEnumMap.template b/src/builder/resources/speiger/assets/collections/templates/maps/impl/misc/LinkedEnumMap.template index 9531720..6cdaa9e 100644 --- a/src/builder/resources/speiger/assets/collections/templates/maps/impl/misc/LinkedEnumMap.template +++ b/src/builder/resources/speiger/assets/collections/templates/maps/impl/misc/LinkedEnumMap.template @@ -1,964 +1,964 @@ -package speiger.src.collections.PACKAGE.maps.impl.misc; - -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.function.Consumer; -#if TYPE_OBJECT -import java.util.Objects; -#endif - -import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.functions.CONSUMER; -#endif -import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; -import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP; -import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET; -import speiger.src.collections.PACKAGE.sets.ORDERED_SET; -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; -#if !VALUE_OBJECT && !SAME_TYPE -import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER; -import speiger.src.collections.VALUE_PACKAGE.lists.VALUE_LIST_ITERATOR; -#endif -#if !TYPE_OBJECT -import speiger.src.collections.objects.collections.ObjectBidirectionalIterator; -import speiger.src.collections.objects.lists.ObjectListIterator; -import speiger.src.collections.objects.sets.AbstractObjectSet; -#endif - -/** - * A Type Specific LinkedEnumMap implementation that allows for Primitive Values and faster iteration. - * Unlike javas implementation this one does not jump around between a single long or long array implementation based around the enum size - * This will cause a bit more memory usage but allows for a simpler implementation. - * @Type(T) - * @ValueType(V) - */ -public class LINKED_ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ENUM_MAP KEY_VALUE_GENERIC_TYPE implements ORDERED_MAP KEY_VALUE_GENERIC_TYPE -{ - /** The Backing array for links between nodes. Left 32 Bits => Previous Entry, Right 32 Bits => Next Entry */ - protected long[] links; - /** The First Index in the Map */ - protected int firstIndex = -1; - /** The Last Index in the Map */ - protected int lastIndex = -1; - /** - * Default Constructor - * @param keyType the type of Enum that should be used - */ - public LINKED_ENUM_MAP(Class keyType) { - super(keyType); - links = new long[keys.length]; - } - -#if !VALUE_OBJECT - /** - * Helper constructor that allow to create a EnumMap from boxed values (it will unbox them) - * @param keys the keys that should be put into the EnumMap - * @param values the values that should be put into the EnumMap. - * @throws IllegalStateException if the keys and values do not match in lenght - */ - public LINKED_ENUM_MAP(T[] keys, CLASS_VALUE_TYPE[] values) { - if(keys.length <= 0) throw new IllegalArgumentException("Empty Array are not allowed"); - if(keys.length != values.length) throw new IllegalArgumentException("Keys and Values have to be the same size"); - keyType = keys[0].getDeclaringClass(); - this.keys = getKeyUniverse(keyType); - this.values = NEW_VALUE_ARRAY(this.keys.length); - present = new long[((this.keys.length - 1) >> 6) + 1]; - links = new long[this.keys.length]; - putAll(keys, values); - } - -#endif - /** - * Helper constructor that allow to create a EnumMap from unboxed values - * @param keys the keys that should be put into the map - * @param values the values that should be put into the map. - * @throws IllegalStateException if the keys and values do not match in lenght - */ - public LINKED_ENUM_MAP(T[] keys, VALUE_TYPE[] values) { - if(keys.length <= 0) throw new IllegalArgumentException("Empty Array are not allowed"); - if(keys.length != values.length) throw new IllegalArgumentException("Keys and Values have to be the same size"); - keyType = keys[0].getDeclaringClass(); - this.keys = getKeyUniverse(keyType); - this.values = NEW_VALUE_ARRAY(this.keys.length); - present = new long[((this.keys.length - 1) >> 6) + 1]; - links = new long[this.keys.length]; - putAll(keys, values); - } - - /** - * A Helper constructor that allows to create a EnumMap with exactly the same values as the provided map. - * @param map the values that should be present in the map - */ - public LINKED_ENUM_MAP(Map map) { - if(map instanceof LINKED_ENUM_MAP) { - LINKED_ENUM_MAP KEY_VALUE_GENERIC_TYPE enumMap = (LINKED_ENUM_MAP KEY_VALUE_GENERIC_TYPE)map; - keyType = enumMap.keyType; - keys = enumMap.keys; - values = enumMap.values.clone(); - present = enumMap.present.clone(); - links = enumMap.links.clone(); - size = enumMap.size; - } - else if(map instanceof ENUM_MAP) { - ENUM_MAP KEY_VALUE_GENERIC_TYPE enumMap = (ENUM_MAP KEY_VALUE_GENERIC_TYPE)map; - keyType = enumMap.keyType; - keys = enumMap.keys; - values = enumMap.values.clone(); - present = enumMap.present.clone(); - links = new long[keys.length]; - for(int i = 0,m=keys.length;i> 6) + 1]; - links = new long[keys.length]; - putAll(map); - } - } - - /** - * A Type Specific Helper function that allows to create a new EnumMap with exactly the same values as the provided map. - * @param map the values that should be present in the map - */ - public LINKED_ENUM_MAP(MAP KEY_VALUE_GENERIC_TYPE map) { - if(map instanceof LINKED_ENUM_MAP) { - LINKED_ENUM_MAP KEY_VALUE_GENERIC_TYPE enumMap = (LINKED_ENUM_MAP KEY_VALUE_GENERIC_TYPE)map; - keyType = enumMap.keyType; - keys = enumMap.keys; - values = enumMap.values.clone(); - present = enumMap.present.clone(); - links = enumMap.links.clone(); - size = enumMap.size; - } - else if(map instanceof ENUM_MAP) { - ENUM_MAP KEY_VALUE_GENERIC_TYPE enumMap = (ENUM_MAP KEY_VALUE_GENERIC_TYPE)map; - keyType = enumMap.keyType; - keys = enumMap.keys; - values = enumMap.values.clone(); - present = enumMap.present.clone(); - links = new long[keys.length]; - for(int i = 0,m=keys.length;i> 6) + 1]; - links = new long[keys.length]; - putAll(map); - } - } - - @Override - public VALUE_TYPE putAndMoveToFirst(T key, VALUE_TYPE value) { - int index = key.ordinal(); - if(isSet(index)) { - VALUE_TYPE result = values[index]; - values[index] = value; - moveToFirstIndex(index); - return result; - } - set(index); - values[index] = value; - onNodeAdded(index); - moveToFirstIndex(index); - return getDefaultReturnValue(); - } - - @Override - public VALUE_TYPE putAndMoveToLast(T key, VALUE_TYPE value) { - int index = key.ordinal(); - if(isSet(index)) { - VALUE_TYPE result = values[index]; - values[index] = value; - moveToLastIndex(index); - return result; - } - set(index); - values[index] = value; - onNodeAdded(index); - moveToLastIndex(index); - return getDefaultReturnValue(); - } - - @Override - public boolean moveToFirst(T key) { - int index = key.ordinal(); - if(isSet(index)) { - moveToFirstIndex(index); - return true; - } - return false; - } - - @Override - public boolean moveToLast(T key) { - int index = key.ordinal(); - if(isSet(index)) { - moveToLastIndex(index); - return true; - } - return false; - } - - @Override - public VALUE_TYPE getAndMoveToFirst(T key) { - int index = key.ordinal(); - if(!isSet(index)) return getDefaultReturnValue(); - moveToFirstIndex(index); - return values[index]; - } - - @Override - public VALUE_TYPE getAndMoveToLast(T key) { - int index = key.ordinal(); - if(!isSet(index)) return getDefaultReturnValue(); - moveToLastIndex(index); - return values[index]; - } - - @Override - public LINKED_ENUM_MAP KEY_VALUE_GENERIC_TYPE copy() { - LINKED_ENUM_MAP KEY_VALUE_GENERIC_TYPE map = new LINKED_ENUM_MAPKV_BRACES(keyType); - map.size = size; - System.arraycopy(present, 0, map.present, 0, Math.min(present.length, map.present.length)); - System.arraycopy(values, 0, map.values, 0, Math.min(values.length, map.values.length)); - System.arraycopy(links, 0, map.links, 0, Math.min(links.length, map.links.length)); - map.firstIndex = firstIndex; - map.lastIndex = lastIndex; - return map; - } - - @Override - public T FIRST_ENTRY_KEY() { - if(size == 0) throw new NoSuchElementException(); - return keys[firstIndex]; - } - - @Override - public T POLL_FIRST_ENTRY_KEY() { - if(size == 0) throw new NoSuchElementException(); - int pos = firstIndex; - firstIndex = (int)links[pos]; - if(0 <= firstIndex) links[firstIndex] |= 0xFFFFFFFF00000000L; - T result = keys[pos]; - size--; - values[result.ordinal()] = EMPTY_VALUE; - return result; - } - - @Override - public T LAST_ENTRY_KEY() { - if(size == 0) throw new NoSuchElementException(); - return keys[lastIndex]; - } - - @Override - public T POLL_LAST_ENTRY_KEY() { - if(size == 0) throw new NoSuchElementException(); - int pos = lastIndex; - lastIndex = (int)(links[pos] >>> 32); - if(0 <= lastIndex) links[lastIndex] |= 0xFFFFFFFFL; - T result = keys[pos]; - size--; - values[result.ordinal()] = EMPTY_VALUE; - return result; - } - - @Override - public VALUE_TYPE FIRST_ENTRY_VALUE() { - if(size == 0) throw new NoSuchElementException(); - return values[firstIndex]; - } - - @Override - public VALUE_TYPE LAST_ENTRY_VALUE() { - if(size == 0) throw new NoSuchElementException(); - return values[lastIndex]; - } - - @Override - public ObjectOrderedSet ENTRY_SET() { - if(entrySet == null) entrySet = new MapEntrySet(); - return (ObjectOrderedSet)entrySet; - } - - @Override - public ORDERED_SET KEY_GENERIC_TYPE keySet() { - if(keySet == null) keySet = new KeySet(); - return (ORDERED_SET KEY_GENERIC_TYPE)keySet; - } - - @Override - public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { - if(valuesC == null) valuesC = new Values(); - return valuesC; - } - - @Override - public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { - int index = firstIndex; - while(index != -1){ - action.accept(keys[index], values[index]); - index = (int)links[index]; - } - } - - @Override - public void clear() { - super.clear(); - firstIndex = lastIndex = -1; - } - - protected void moveToFirstIndex(int startPos) { - if(size == 1 || firstIndex == startPos) return; - if(lastIndex == startPos) { - lastIndex = (int)(links[startPos] >>> 32); - links[lastIndex] |= 0xFFFFFFFFL; - } - else { - long link = links[startPos]; - int prev = (int)(link >>> 32); - int next = (int)link; - links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L); - } - links[firstIndex] ^= ((links[firstIndex] ^ ((startPos & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); - links[startPos] = 0xFFFFFFFF00000000L | (firstIndex & 0xFFFFFFFFL); - firstIndex = startPos; - } - - protected void moveToLastIndex(int startPos) { - if(size == 1 || lastIndex == startPos) return; - if(firstIndex == startPos) { - firstIndex = (int)links[startPos]; - links[lastIndex] |= 0xFFFFFFFF00000000L; - } - else { - long link = links[startPos]; - int prev = (int)(link >>> 32); - int next = (int)link; - links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L); - } - links[lastIndex] ^= ((links[lastIndex] ^ (startPos & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - links[startPos] = ((lastIndex & 0xFFFFFFFFL) << 32) | 0xFFFFFFFFL; - lastIndex = startPos; - } - - @Override - protected void onNodeAdded(int pos) { - if(size == 0) { - firstIndex = lastIndex = pos; - links[pos] = -1L; - } - else { - links[lastIndex] ^= ((links[lastIndex] ^ (pos & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - links[pos] = ((lastIndex & 0xFFFFFFFFL) << 32) | 0xFFFFFFFFL; - lastIndex = pos; - } - } - - @Override - protected void onNodeRemoved(int pos) { - if(size == 0) firstIndex = lastIndex = -1; - else if(firstIndex == pos) { - firstIndex = (int)links[pos]; - if(0 <= firstIndex) links[firstIndex] |= 0xFFFFFFFF00000000L; - } - else if(lastIndex == pos) { - lastIndex = (int)(links[pos] >>> 32); - if(0 <= lastIndex) links[lastIndex] |= 0xFFFFFFFFL; - } - else { - long link = links[pos]; - int prev = (int)(link >>> 32); - int next = (int)link; - links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L); - } - } - - private class MapEntrySet extends AbstractObjectSet implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE { - @Override - public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } - @Override - public boolean addAndMoveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } - - @Override - public boolean moveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { - return LINKED_ENUM_MAP.this.moveToFirst(o.ENTRY_KEY()); - } - - @Override - public boolean moveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { - return LINKED_ENUM_MAP.this.moveToLast(o.ENTRY_KEY()); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE first() { - return new BasicEntryKV_BRACES(FIRST_ENTRY_KEY(), FIRST_ENTRY_VALUE()); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE last() { - return new BasicEntryKV_BRACES(LAST_ENTRY_KEY(), LAST_ENTRY_VALUE()); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirst() { - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(FIRST_ENTRY_KEY(), FIRST_ENTRY_VALUE()); - POLL_FIRST_ENTRY_KEY(); - return entry; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLast() { - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(LAST_ENTRY_KEY(), LAST_ENTRY_VALUE()); - POLL_LAST_ENTRY_KEY(); - return entry; - } - - @Override - public ObjectBidirectionalIterator iterator() { - return new EntryIterator(); - } - - @Override - public ObjectBidirectionalIterator iterator(MAP.Entry KEY_VALUE_GENERIC_TYPE fromElement) { - return new EntryIterator(fromElement.ENTRY_KEY()); - } - - @Override - public ObjectBidirectionalIterator fastIterator() { - return new FastEntryIterator(); - } - - @Override - public ObjectBidirectionalIterator fastIterator(T fromElement) { - return new FastEntryIterator(fromElement); - } - - public MapEntrySet copy() { throw new UnsupportedOperationException(); } - - @Override - public void forEach(Consumer action) { - int index = firstIndex; - while(index != -1){ - action.accept(new BasicEntryKV_BRACES(keys[index], values[index])); - index = (int)links[index]; - } - } - - @Override - public void fastForEach(Consumer action) { - BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); - int index = firstIndex; - while(index != -1){ - entry.set(keys[index], values[index]); - action.accept(entry); - index = (int)links[index]; - } - } - - @Override - @Deprecated - public boolean contains(Object o) { - if(o instanceof Map.Entry) { - if(o instanceof MAP.Entry) { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; - if(!keyType.isInstance(entry.ENTRY_KEY())) return false; - int index = ((T)entry.ENTRY_KEY()).ordinal(); - if(index >= 0 && LINKED_ENUM_MAP.this.isSet(index)) return VALUE_EQUALS(entry.ENTRY_VALUE(), LINKED_ENUM_MAP.this.values[index]); - } - else { - Map.Entry entry = (Map.Entry)o; - if(!keyType.isInstance(entry.getKey())) return false; - int index = ((T)entry.getKey()).ordinal(); - if(index >= 0 && LINKED_ENUM_MAP.this.isSet(index)) return Objects.equals(entry.getValue(), VALUE_TO_OBJ(LINKED_ENUM_MAP.this.values[index])); - } - } - return false; - } - - @Override - @Deprecated - public boolean remove(Object o) { - if(o instanceof Map.Entry) { - if(o instanceof MAP.Entry) { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; - return LINKED_ENUM_MAP.this.remove(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); - } - Map.Entry entry = (Map.Entry)o; - return LINKED_ENUM_MAP.this.remove(entry.getKey(), entry.getValue()); - } - return false; - } - - @Override - public int size() { - return LINKED_ENUM_MAP.this.size(); - } - - @Override - public void clear() { - LINKED_ENUM_MAP.this.clear(); - } - } - - private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE { -#if TYPE_OBJECT - @Override - @Deprecated - public boolean contains(Object e) { - return containsKey(e); - } - - @Override - public boolean remove(Object o) { - int oldSize = size; - LINKED_ENUM_MAP.this.remove(o); - return size != oldSize; - } - -#else - @Override - public boolean contains(T e) { - return containsKey(e); - } - - @Override - public boolean remove(T o) { - int oldSize = size; - LINKED_ENUM_MAP.this.remove(o); - return size != oldSize; - } - -#endif - @Override - public boolean add(T o) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean addAndMoveToFirst(T o) { throw new UnsupportedOperationException(); } - - @Override - public boolean addAndMoveToLast(T o) { throw new UnsupportedOperationException(); } - - @Override - public boolean moveToFirst(T o) { - return LINKED_ENUM_MAP.this.moveToFirst(o); - } - - @Override - public boolean moveToLast(T o) { - return LINKED_ENUM_MAP.this.moveToLast(o); - } - - @Override - public LIST_ITERATOR KEY_GENERIC_TYPE iterator() { - return new KeyIterator(); - } - - @Override - public BI_ITERATOR KEY_GENERIC_TYPE iterator(T fromElement) { - return new KeyIterator(fromElement); - } - - public KeySet copy() { throw new UnsupportedOperationException(); } - - @Override - public int size() { - return LINKED_ENUM_MAP.this.size(); - } - - @Override - public void clear() { - LINKED_ENUM_MAP.this.clear(); - } - - @Override - public T FIRST_KEY() { - return FIRST_ENTRY_KEY(); - } - - @Override - public T POLL_FIRST_KEY() { - return POLL_FIRST_ENTRY_KEY(); - } - - @Override - public T LAST_KEY() { - return LAST_ENTRY_KEY(); - } - - @Override - public T POLL_LAST_KEY() { - return POLL_LAST_ENTRY_KEY(); - } - -#if TYPE_OBJECT - @Override - public void forEach(Consumer KEY_SUPER_GENERIC_TYPE action) { - int index = firstIndex; - while(index != -1){ - action.accept(keys[index]); - index = (int)links[index]; - } - } - -#else - @Override - public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { - int index = firstIndex; - while(index != -1){ - action.accept(keys[index]); - index = (int)links[index]; - } - } - -#endif - } - - private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { -#if VALUE_OBJECT - @Override - @Deprecated - public boolean contains(Object e) { - return containsValue(e); - } - -#else - @Override - public boolean contains(VALUE_TYPE e) { - return containsValue(e); - } - -#endif - @Override - public boolean add(VALUE_TYPE o) { - throw new UnsupportedOperationException(); - } - - @Override - public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() { - return new ValueIterator(); - } - - @Override - public int size() { - return LINKED_ENUM_MAP.this.size(); - } - - @Override - public void clear() { - LINKED_ENUM_MAP.this.clear(); - } - -#if VALUE_OBJECT - @Override - public void forEach(Consumer VALUE_SUPER_GENERIC_TYPE action) { - int index = firstIndex; - while(index != -1){ - action.accept(values[index]); - index = (int)links[index]; - } - } -#else - @Override - public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) { - int index = firstIndex; - while(index != -1){ - action.accept(values[index]); - index = (int)links[index]; - } - } -#endif - } - - private class FastEntryIterator extends MapIterator implements ObjectListIterator { - MapEntry entry = new MapEntry(); - - public FastEntryIterator() {} - public FastEntryIterator(T from) { - super(from); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { - entry.index = nextEntry(); - return entry; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { - entry.index = previousEntry(); - return entry; - } - - @Override - public void set(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } - - @Override - public void add(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } - } - - private class EntryIterator extends MapIterator implements ObjectListIterator { - MapEntry entry; - - public EntryIterator() {} - public EntryIterator(T from) { - super(from); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { - return entry = new MapEntry(nextEntry()); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { - return entry = new MapEntry(previousEntry()); - } - - @Override - public void remove() { - super.remove(); - entry.index = -1; - } - - @Override - public void set(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } - - @Override - public void add(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } - } - - private class KeyIterator extends MapIterator implements LIST_ITERATOR KEY_GENERIC_TYPE { - - public KeyIterator() {} - public KeyIterator(T from) { - super(from); - } - - @Override - public T PREVIOUS() { - return keys[previousEntry()]; - } - - @Override - public T NEXT() { - return keys[nextEntry()]; - } - - @Override - public void set(T e) { throw new UnsupportedOperationException(); } - @Override - public void add(T e) { throw new UnsupportedOperationException(); } - } - - private class ValueIterator extends MapIterator implements VALUE_LIST_ITERATOR VALUE_GENERIC_TYPE { - public ValueIterator() {} - - @Override - public VALUE_TYPE VALUE_PREVIOUS() { - return values[previousEntry()]; - } - - @Override - public VALUE_TYPE VALUE_NEXT() { - return values[nextEntry()]; - } - - @Override - public void set(VALUE_TYPE e) { throw new UnsupportedOperationException(); } - - @Override - public void add(VALUE_TYPE e) { throw new UnsupportedOperationException(); } - - } - - private class MapIterator { - int previous = -1; - int next = -1; - int current = -1; - int index = 0; - - MapIterator() { - next = firstIndex; - } - - MapIterator(T from) { - previous = from.ordinal() - 1; - index = from.ordinal(); - next = from.ordinal(); - if(!isSet(index)) throw new NoSuchElementException(); - } - - public boolean hasNext() { - return next != -1; - } - - public boolean hasPrevious() { - return previous != -1; - } - - public int nextIndex() { - ensureIndexKnown(); - return index; - } - - public int previousIndex() { - ensureIndexKnown(); - return index - 1; - } - - public void remove() { - if(current == -1) throw new IllegalStateException(); - ensureIndexKnown(); - if(current == previous) { - index--; - previous = (int)(links[current] >>> 32); - } - else next = (int)links[current]; - - size--; - if(previous == -1) firstIndex = next; - else links[previous] ^= ((links[previous] ^ (next & 0xFFFFFFFFL)) & 0xFFFFFFFFL); - - if (next == -1) lastIndex = previous; - else links[next] ^= ((links[next] ^ ((previous & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); - values[current] = EMPTY_VALUE; - present[current >> 6] &= ~(1L << current); - current = -1; - } - - public int previousEntry() { - if(!hasPrevious()) throw new NoSuchElementException(); - current = previous; - previous = (int)(links[current] >> 32); - next = current; - if(index >= 0) index--; - return current; - } - - public int nextEntry() { - if(!hasNext()) throw new NoSuchElementException(); - current = next; - next = (int)(links[current]); - previous = current; - if(index >= 0) index++; - return current; - } - - private void ensureIndexKnown() { - if(index == -1) { - if(previous == -1) { - index = 0; - } - else if(next == -1) { - index = size; - } - else { - index = 1; - for(int pos = firstIndex;pos != previous;pos = (int)links[pos], index++); - } - } - } - } - - protected class MapEntry implements MAP.Entry KEY_VALUE_GENERIC_TYPE, Map.Entry { - public int index = -1; - - public MapEntry() {} - public MapEntry(int index) { - this.index = index; - } - - @Override - public KEY_TYPE ENTRY_KEY() { - return keys[index]; - } - - @Override - public VALUE_TYPE ENTRY_VALUE() { - return values[index]; - } - - @Override - public VALUE_TYPE setValue(VALUE_TYPE value) { - VALUE_TYPE oldValue = values[index]; - values[index] = value; - return oldValue; - } - - @Override - public boolean equals(Object obj) { - if(obj instanceof Map.Entry) { - if(obj instanceof MAP.Entry) { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)obj; - return KEY_EQUALS(keys[index], entry.ENTRY_KEY()) && VALUE_EQUALS(values[index], entry.ENTRY_VALUE()); - } - Map.Entry entry = (Map.Entry)obj; - Object key = entry.getKey(); - Object value = entry.getValue(); -#if TYPE_OBJECT && VALUE_OBJECT - return KEY_EQUALS(keys[index], key) && VALUE_EQUALS(values[index], value); -#else if TYPE_OBJECT - return value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(keys[index], key) && VALUE_EQUALS(values[index], CLASS_TO_VALUE(value)); -#else if VALUE_OBJECT - return key instanceof CLASS_TYPE && KEY_EQUALS(keys[index], CLASS_TO_KEY(key)) && VALUE_EQUALS(values[index], value); -#else - return key instanceof CLASS_TYPE && value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(keys[index], CLASS_TO_KEY(key)) && VALUE_EQUALS(values[index], CLASS_TO_VALUE(value)); -#endif - } - return false; - } - - @Override - public int hashCode() { - return KEY_TO_HASH(keys[index]) ^ VALUE_TO_HASH(values[index]); - } - - @Override - public String toString() { - return KEY_TO_STRING(keys[index]) + "=" + VALUE_TO_STRING(values[index]); - } - } +package speiger.src.collections.PACKAGE.maps.impl.misc; + +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.function.Consumer; +#if TYPE_OBJECT +import java.util.Objects; +#endif + +import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.functions.CONSUMER; +#endif +import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; +import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP; +import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET; +import speiger.src.collections.PACKAGE.sets.ORDERED_SET; +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; +#if !VALUE_OBJECT && !SAME_TYPE +import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER; +import speiger.src.collections.VALUE_PACKAGE.lists.VALUE_LIST_ITERATOR; +#endif +#if !TYPE_OBJECT +import speiger.src.collections.objects.collections.ObjectBidirectionalIterator; +import speiger.src.collections.objects.lists.ObjectListIterator; +import speiger.src.collections.objects.sets.AbstractObjectSet; +#endif + +/** + * A Type Specific LinkedEnumMap implementation that allows for Primitive Values and faster iteration. + * Unlike javas implementation this one does not jump around between a single long or long array implementation based around the enum size + * This will cause a bit more memory usage but allows for a simpler implementation. + * @Type(T) + * @ValueType(V) + */ +public class LINKED_ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ENUM_MAP KEY_VALUE_GENERIC_TYPE implements ORDERED_MAP KEY_VALUE_GENERIC_TYPE +{ + /** The Backing array for links between nodes. Left 32 Bits => Previous Entry, Right 32 Bits => Next Entry */ + protected long[] links; + /** The First Index in the Map */ + protected int firstIndex = -1; + /** The Last Index in the Map */ + protected int lastIndex = -1; + /** + * Default Constructor + * @param keyType the type of Enum that should be used + */ + public LINKED_ENUM_MAP(Class keyType) { + super(keyType); + links = new long[keys.length]; + } + +#if !VALUE_OBJECT + /** + * Helper constructor that allow to create a EnumMap from boxed values (it will unbox them) + * @param keys the keys that should be put into the EnumMap + * @param values the values that should be put into the EnumMap. + * @throws IllegalStateException if the keys and values do not match in lenght + */ + public LINKED_ENUM_MAP(T[] keys, CLASS_VALUE_TYPE[] values) { + if(keys.length <= 0) throw new IllegalArgumentException("Empty Array are not allowed"); + if(keys.length != values.length) throw new IllegalArgumentException("Keys and Values have to be the same size"); + keyType = keys[0].getDeclaringClass(); + this.keys = getKeyUniverse(keyType); + this.values = NEW_VALUE_ARRAY(this.keys.length); + present = new long[((this.keys.length - 1) >> 6) + 1]; + links = new long[this.keys.length]; + putAll(keys, values); + } + +#endif + /** + * Helper constructor that allow to create a EnumMap from unboxed values + * @param keys the keys that should be put into the map + * @param values the values that should be put into the map. + * @throws IllegalStateException if the keys and values do not match in lenght + */ + public LINKED_ENUM_MAP(T[] keys, VALUE_TYPE[] values) { + if(keys.length <= 0) throw new IllegalArgumentException("Empty Array are not allowed"); + if(keys.length != values.length) throw new IllegalArgumentException("Keys and Values have to be the same size"); + keyType = keys[0].getDeclaringClass(); + this.keys = getKeyUniverse(keyType); + this.values = NEW_VALUE_ARRAY(this.keys.length); + present = new long[((this.keys.length - 1) >> 6) + 1]; + links = new long[this.keys.length]; + putAll(keys, values); + } + + /** + * A Helper constructor that allows to create a EnumMap with exactly the same values as the provided map. + * @param map the values that should be present in the map + */ + public LINKED_ENUM_MAP(Map map) { + if(map instanceof LINKED_ENUM_MAP) { + LINKED_ENUM_MAP KEY_VALUE_GENERIC_TYPE enumMap = (LINKED_ENUM_MAP KEY_VALUE_GENERIC_TYPE)map; + keyType = enumMap.keyType; + keys = enumMap.keys; + values = enumMap.values.clone(); + present = enumMap.present.clone(); + links = enumMap.links.clone(); + size = enumMap.size; + } + else if(map instanceof ENUM_MAP) { + ENUM_MAP KEY_VALUE_GENERIC_TYPE enumMap = (ENUM_MAP KEY_VALUE_GENERIC_TYPE)map; + keyType = enumMap.keyType; + keys = enumMap.keys; + values = enumMap.values.clone(); + present = enumMap.present.clone(); + links = new long[keys.length]; + for(int i = 0,m=keys.length;i> 6) + 1]; + links = new long[keys.length]; + putAll(map); + } + } + + /** + * A Type Specific Helper function that allows to create a new EnumMap with exactly the same values as the provided map. + * @param map the values that should be present in the map + */ + public LINKED_ENUM_MAP(MAP KEY_VALUE_GENERIC_TYPE map) { + if(map instanceof LINKED_ENUM_MAP) { + LINKED_ENUM_MAP KEY_VALUE_GENERIC_TYPE enumMap = (LINKED_ENUM_MAP KEY_VALUE_GENERIC_TYPE)map; + keyType = enumMap.keyType; + keys = enumMap.keys; + values = enumMap.values.clone(); + present = enumMap.present.clone(); + links = enumMap.links.clone(); + size = enumMap.size; + } + else if(map instanceof ENUM_MAP) { + ENUM_MAP KEY_VALUE_GENERIC_TYPE enumMap = (ENUM_MAP KEY_VALUE_GENERIC_TYPE)map; + keyType = enumMap.keyType; + keys = enumMap.keys; + values = enumMap.values.clone(); + present = enumMap.present.clone(); + links = new long[keys.length]; + for(int i = 0,m=keys.length;i> 6) + 1]; + links = new long[keys.length]; + putAll(map); + } + } + + @Override + public VALUE_TYPE putAndMoveToFirst(T key, VALUE_TYPE value) { + int index = key.ordinal(); + if(isSet(index)) { + VALUE_TYPE result = values[index]; + values[index] = value; + moveToFirstIndex(index); + return result; + } + set(index); + values[index] = value; + onNodeAdded(index); + moveToFirstIndex(index); + return getDefaultReturnValue(); + } + + @Override + public VALUE_TYPE putAndMoveToLast(T key, VALUE_TYPE value) { + int index = key.ordinal(); + if(isSet(index)) { + VALUE_TYPE result = values[index]; + values[index] = value; + moveToLastIndex(index); + return result; + } + set(index); + values[index] = value; + onNodeAdded(index); + moveToLastIndex(index); + return getDefaultReturnValue(); + } + + @Override + public boolean moveToFirst(T key) { + int index = key.ordinal(); + if(isSet(index)) { + moveToFirstIndex(index); + return true; + } + return false; + } + + @Override + public boolean moveToLast(T key) { + int index = key.ordinal(); + if(isSet(index)) { + moveToLastIndex(index); + return true; + } + return false; + } + + @Override + public VALUE_TYPE getAndMoveToFirst(T key) { + int index = key.ordinal(); + if(!isSet(index)) return getDefaultReturnValue(); + moveToFirstIndex(index); + return values[index]; + } + + @Override + public VALUE_TYPE getAndMoveToLast(T key) { + int index = key.ordinal(); + if(!isSet(index)) return getDefaultReturnValue(); + moveToLastIndex(index); + return values[index]; + } + + @Override + public LINKED_ENUM_MAP KEY_VALUE_GENERIC_TYPE copy() { + LINKED_ENUM_MAP KEY_VALUE_GENERIC_TYPE map = new LINKED_ENUM_MAPKV_BRACES(keyType); + map.size = size; + System.arraycopy(present, 0, map.present, 0, Math.min(present.length, map.present.length)); + System.arraycopy(values, 0, map.values, 0, Math.min(values.length, map.values.length)); + System.arraycopy(links, 0, map.links, 0, Math.min(links.length, map.links.length)); + map.firstIndex = firstIndex; + map.lastIndex = lastIndex; + return map; + } + + @Override + public T FIRST_ENTRY_KEY() { + if(size == 0) throw new NoSuchElementException(); + return keys[firstIndex]; + } + + @Override + public T POLL_FIRST_ENTRY_KEY() { + if(size == 0) throw new NoSuchElementException(); + int pos = firstIndex; + firstIndex = (int)links[pos]; + if(0 <= firstIndex) links[firstIndex] |= 0xFFFFFFFF00000000L; + T result = keys[pos]; + size--; + values[result.ordinal()] = EMPTY_VALUE; + return result; + } + + @Override + public T LAST_ENTRY_KEY() { + if(size == 0) throw new NoSuchElementException(); + return keys[lastIndex]; + } + + @Override + public T POLL_LAST_ENTRY_KEY() { + if(size == 0) throw new NoSuchElementException(); + int pos = lastIndex; + lastIndex = (int)(links[pos] >>> 32); + if(0 <= lastIndex) links[lastIndex] |= 0xFFFFFFFFL; + T result = keys[pos]; + size--; + values[result.ordinal()] = EMPTY_VALUE; + return result; + } + + @Override + public VALUE_TYPE FIRST_ENTRY_VALUE() { + if(size == 0) throw new NoSuchElementException(); + return values[firstIndex]; + } + + @Override + public VALUE_TYPE LAST_ENTRY_VALUE() { + if(size == 0) throw new NoSuchElementException(); + return values[lastIndex]; + } + + @Override + public ObjectOrderedSet ENTRY_SET() { + if(entrySet == null) entrySet = new MapEntrySet(); + return (ObjectOrderedSet)entrySet; + } + + @Override + public ORDERED_SET KEY_GENERIC_TYPE keySet() { + if(keySet == null) keySet = new KeySet(); + return (ORDERED_SET KEY_GENERIC_TYPE)keySet; + } + + @Override + public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { + if(valuesC == null) valuesC = new Values(); + return valuesC; + } + + @Override + public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { + int index = firstIndex; + while(index != -1){ + action.accept(keys[index], values[index]); + index = (int)links[index]; + } + } + + @Override + public void clear() { + super.clear(); + firstIndex = lastIndex = -1; + } + + protected void moveToFirstIndex(int startPos) { + if(size == 1 || firstIndex == startPos) return; + if(lastIndex == startPos) { + lastIndex = (int)(links[startPos] >>> 32); + links[lastIndex] |= 0xFFFFFFFFL; + } + else { + long link = links[startPos]; + int prev = (int)(link >>> 32); + int next = (int)link; + links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L); + } + links[firstIndex] ^= ((links[firstIndex] ^ ((startPos & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); + links[startPos] = 0xFFFFFFFF00000000L | (firstIndex & 0xFFFFFFFFL); + firstIndex = startPos; + } + + protected void moveToLastIndex(int startPos) { + if(size == 1 || lastIndex == startPos) return; + if(firstIndex == startPos) { + firstIndex = (int)links[startPos]; + links[lastIndex] |= 0xFFFFFFFF00000000L; + } + else { + long link = links[startPos]; + int prev = (int)(link >>> 32); + int next = (int)link; + links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L); + } + links[lastIndex] ^= ((links[lastIndex] ^ (startPos & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + links[startPos] = ((lastIndex & 0xFFFFFFFFL) << 32) | 0xFFFFFFFFL; + lastIndex = startPos; + } + + @Override + protected void onNodeAdded(int pos) { + if(size == 0) { + firstIndex = lastIndex = pos; + links[pos] = -1L; + } + else { + links[lastIndex] ^= ((links[lastIndex] ^ (pos & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + links[pos] = ((lastIndex & 0xFFFFFFFFL) << 32) | 0xFFFFFFFFL; + lastIndex = pos; + } + } + + @Override + protected void onNodeRemoved(int pos) { + if(size == 0) firstIndex = lastIndex = -1; + else if(firstIndex == pos) { + firstIndex = (int)links[pos]; + if(0 <= firstIndex) links[firstIndex] |= 0xFFFFFFFF00000000L; + } + else if(lastIndex == pos) { + lastIndex = (int)(links[pos] >>> 32); + if(0 <= lastIndex) links[lastIndex] |= 0xFFFFFFFFL; + } + else { + long link = links[pos]; + int prev = (int)(link >>> 32); + int next = (int)link; + links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L); + } + } + + private class MapEntrySet extends AbstractObjectSet implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE { + @Override + public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } + @Override + public boolean addAndMoveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } + + @Override + public boolean moveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { + return LINKED_ENUM_MAP.this.moveToFirst(o.ENTRY_KEY()); + } + + @Override + public boolean moveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { + return LINKED_ENUM_MAP.this.moveToLast(o.ENTRY_KEY()); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE first() { + return new BasicEntryKV_BRACES(FIRST_ENTRY_KEY(), FIRST_ENTRY_VALUE()); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE last() { + return new BasicEntryKV_BRACES(LAST_ENTRY_KEY(), LAST_ENTRY_VALUE()); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirst() { + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(FIRST_ENTRY_KEY(), FIRST_ENTRY_VALUE()); + POLL_FIRST_ENTRY_KEY(); + return entry; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLast() { + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(LAST_ENTRY_KEY(), LAST_ENTRY_VALUE()); + POLL_LAST_ENTRY_KEY(); + return entry; + } + + @Override + public ObjectBidirectionalIterator iterator() { + return new EntryIterator(); + } + + @Override + public ObjectBidirectionalIterator iterator(MAP.Entry KEY_VALUE_GENERIC_TYPE fromElement) { + return new EntryIterator(fromElement.ENTRY_KEY()); + } + + @Override + public ObjectBidirectionalIterator fastIterator() { + return new FastEntryIterator(); + } + + @Override + public ObjectBidirectionalIterator fastIterator(T fromElement) { + return new FastEntryIterator(fromElement); + } + + public MapEntrySet copy() { throw new UnsupportedOperationException(); } + + @Override + public void forEach(Consumer action) { + int index = firstIndex; + while(index != -1){ + action.accept(new BasicEntryKV_BRACES(keys[index], values[index])); + index = (int)links[index]; + } + } + + @Override + public void fastForEach(Consumer action) { + BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); + int index = firstIndex; + while(index != -1){ + entry.set(keys[index], values[index]); + action.accept(entry); + index = (int)links[index]; + } + } + + @Override + @Deprecated + public boolean contains(Object o) { + if(o instanceof Map.Entry) { + if(o instanceof MAP.Entry) { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; + if(!keyType.isInstance(entry.ENTRY_KEY())) return false; + int index = ((T)entry.ENTRY_KEY()).ordinal(); + if(index >= 0 && LINKED_ENUM_MAP.this.isSet(index)) return VALUE_EQUALS(entry.ENTRY_VALUE(), LINKED_ENUM_MAP.this.values[index]); + } + else { + Map.Entry entry = (Map.Entry)o; + if(!keyType.isInstance(entry.getKey())) return false; + int index = ((T)entry.getKey()).ordinal(); + if(index >= 0 && LINKED_ENUM_MAP.this.isSet(index)) return Objects.equals(entry.getValue(), VALUE_TO_OBJ(LINKED_ENUM_MAP.this.values[index])); + } + } + return false; + } + + @Override + @Deprecated + public boolean remove(Object o) { + if(o instanceof Map.Entry) { + if(o instanceof MAP.Entry) { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; + return LINKED_ENUM_MAP.this.remove(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); + } + Map.Entry entry = (Map.Entry)o; + return LINKED_ENUM_MAP.this.remove(entry.getKey(), entry.getValue()); + } + return false; + } + + @Override + public int size() { + return LINKED_ENUM_MAP.this.size(); + } + + @Override + public void clear() { + LINKED_ENUM_MAP.this.clear(); + } + } + + private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE { +#if TYPE_OBJECT + @Override + @Deprecated + public boolean contains(Object e) { + return containsKey(e); + } + + @Override + public boolean remove(Object o) { + int oldSize = size; + LINKED_ENUM_MAP.this.remove(o); + return size != oldSize; + } + +#else + @Override + public boolean contains(T e) { + return containsKey(e); + } + + @Override + public boolean remove(T o) { + int oldSize = size; + LINKED_ENUM_MAP.this.remove(o); + return size != oldSize; + } + +#endif + @Override + public boolean add(T o) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean addAndMoveToFirst(T o) { throw new UnsupportedOperationException(); } + + @Override + public boolean addAndMoveToLast(T o) { throw new UnsupportedOperationException(); } + + @Override + public boolean moveToFirst(T o) { + return LINKED_ENUM_MAP.this.moveToFirst(o); + } + + @Override + public boolean moveToLast(T o) { + return LINKED_ENUM_MAP.this.moveToLast(o); + } + + @Override + public LIST_ITERATOR KEY_GENERIC_TYPE iterator() { + return new KeyIterator(); + } + + @Override + public BI_ITERATOR KEY_GENERIC_TYPE iterator(T fromElement) { + return new KeyIterator(fromElement); + } + + public KeySet copy() { throw new UnsupportedOperationException(); } + + @Override + public int size() { + return LINKED_ENUM_MAP.this.size(); + } + + @Override + public void clear() { + LINKED_ENUM_MAP.this.clear(); + } + + @Override + public T FIRST_KEY() { + return FIRST_ENTRY_KEY(); + } + + @Override + public T POLL_FIRST_KEY() { + return POLL_FIRST_ENTRY_KEY(); + } + + @Override + public T LAST_KEY() { + return LAST_ENTRY_KEY(); + } + + @Override + public T POLL_LAST_KEY() { + return POLL_LAST_ENTRY_KEY(); + } + +#if TYPE_OBJECT + @Override + public void forEach(Consumer KEY_SUPER_GENERIC_TYPE action) { + int index = firstIndex; + while(index != -1){ + action.accept(keys[index]); + index = (int)links[index]; + } + } + +#else + @Override + public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { + int index = firstIndex; + while(index != -1){ + action.accept(keys[index]); + index = (int)links[index]; + } + } + +#endif + } + + private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { +#if VALUE_OBJECT + @Override + @Deprecated + public boolean contains(Object e) { + return containsValue(e); + } + +#else + @Override + public boolean contains(VALUE_TYPE e) { + return containsValue(e); + } + +#endif + @Override + public boolean add(VALUE_TYPE o) { + throw new UnsupportedOperationException(); + } + + @Override + public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() { + return new ValueIterator(); + } + + @Override + public int size() { + return LINKED_ENUM_MAP.this.size(); + } + + @Override + public void clear() { + LINKED_ENUM_MAP.this.clear(); + } + +#if VALUE_OBJECT + @Override + public void forEach(Consumer VALUE_SUPER_GENERIC_TYPE action) { + int index = firstIndex; + while(index != -1){ + action.accept(values[index]); + index = (int)links[index]; + } + } +#else + @Override + public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) { + int index = firstIndex; + while(index != -1){ + action.accept(values[index]); + index = (int)links[index]; + } + } +#endif + } + + private class FastEntryIterator extends MapIterator implements ObjectListIterator { + MapEntry entry = new MapEntry(); + + public FastEntryIterator() {} + public FastEntryIterator(T from) { + super(from); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { + entry.index = nextEntry(); + return entry; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { + entry.index = previousEntry(); + return entry; + } + + @Override + public void set(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } + + @Override + public void add(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } + } + + private class EntryIterator extends MapIterator implements ObjectListIterator { + MapEntry entry; + + public EntryIterator() {} + public EntryIterator(T from) { + super(from); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { + return entry = new MapEntry(nextEntry()); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { + return entry = new MapEntry(previousEntry()); + } + + @Override + public void remove() { + super.remove(); + entry.index = -1; + } + + @Override + public void set(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } + + @Override + public void add(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); } + } + + private class KeyIterator extends MapIterator implements LIST_ITERATOR KEY_GENERIC_TYPE { + + public KeyIterator() {} + public KeyIterator(T from) { + super(from); + } + + @Override + public T PREVIOUS() { + return keys[previousEntry()]; + } + + @Override + public T NEXT() { + return keys[nextEntry()]; + } + + @Override + public void set(T e) { throw new UnsupportedOperationException(); } + @Override + public void add(T e) { throw new UnsupportedOperationException(); } + } + + private class ValueIterator extends MapIterator implements VALUE_LIST_ITERATOR VALUE_GENERIC_TYPE { + public ValueIterator() {} + + @Override + public VALUE_TYPE VALUE_PREVIOUS() { + return values[previousEntry()]; + } + + @Override + public VALUE_TYPE VALUE_NEXT() { + return values[nextEntry()]; + } + + @Override + public void set(VALUE_TYPE e) { throw new UnsupportedOperationException(); } + + @Override + public void add(VALUE_TYPE e) { throw new UnsupportedOperationException(); } + + } + + private class MapIterator { + int previous = -1; + int next = -1; + int current = -1; + int index = 0; + + MapIterator() { + next = firstIndex; + } + + MapIterator(T from) { + previous = from.ordinal() - 1; + index = from.ordinal(); + next = from.ordinal(); + if(!isSet(index)) throw new NoSuchElementException(); + } + + public boolean hasNext() { + return next != -1; + } + + public boolean hasPrevious() { + return previous != -1; + } + + public int nextIndex() { + ensureIndexKnown(); + return index; + } + + public int previousIndex() { + ensureIndexKnown(); + return index - 1; + } + + public void remove() { + if(current == -1) throw new IllegalStateException(); + ensureIndexKnown(); + if(current == previous) { + index--; + previous = (int)(links[current] >>> 32); + } + else next = (int)links[current]; + + size--; + if(previous == -1) firstIndex = next; + else links[previous] ^= ((links[previous] ^ (next & 0xFFFFFFFFL)) & 0xFFFFFFFFL); + + if (next == -1) lastIndex = previous; + else links[next] ^= ((links[next] ^ ((previous & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); + values[current] = EMPTY_VALUE; + present[current >> 6] &= ~(1L << current); + current = -1; + } + + public int previousEntry() { + if(!hasPrevious()) throw new NoSuchElementException(); + current = previous; + previous = (int)(links[current] >> 32); + next = current; + if(index >= 0) index--; + return current; + } + + public int nextEntry() { + if(!hasNext()) throw new NoSuchElementException(); + current = next; + next = (int)(links[current]); + previous = current; + if(index >= 0) index++; + return current; + } + + private void ensureIndexKnown() { + if(index == -1) { + if(previous == -1) { + index = 0; + } + else if(next == -1) { + index = size; + } + else { + index = 1; + for(int pos = firstIndex;pos != previous;pos = (int)links[pos], index++); + } + } + } + } + + protected class MapEntry implements MAP.Entry KEY_VALUE_GENERIC_TYPE, Map.Entry { + public int index = -1; + + public MapEntry() {} + public MapEntry(int index) { + this.index = index; + } + + @Override + public KEY_TYPE ENTRY_KEY() { + return keys[index]; + } + + @Override + public VALUE_TYPE ENTRY_VALUE() { + return values[index]; + } + + @Override + public VALUE_TYPE setValue(VALUE_TYPE value) { + VALUE_TYPE oldValue = values[index]; + values[index] = value; + return oldValue; + } + + @Override + public boolean equals(Object obj) { + if(obj instanceof Map.Entry) { + if(obj instanceof MAP.Entry) { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)obj; + return KEY_EQUALS(keys[index], entry.ENTRY_KEY()) && VALUE_EQUALS(values[index], entry.ENTRY_VALUE()); + } + Map.Entry entry = (Map.Entry)obj; + Object key = entry.getKey(); + Object value = entry.getValue(); +#if TYPE_OBJECT && VALUE_OBJECT + return KEY_EQUALS(keys[index], key) && VALUE_EQUALS(values[index], value); +#else if TYPE_OBJECT + return value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(keys[index], key) && VALUE_EQUALS(values[index], CLASS_TO_VALUE(value)); +#else if VALUE_OBJECT + return key instanceof CLASS_TYPE && KEY_EQUALS(keys[index], CLASS_TO_KEY(key)) && VALUE_EQUALS(values[index], value); +#else + return key instanceof CLASS_TYPE && value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(keys[index], CLASS_TO_KEY(key)) && VALUE_EQUALS(values[index], CLASS_TO_VALUE(value)); +#endif + } + return false; + } + + @Override + public int hashCode() { + return KEY_TO_HASH(keys[index]) ^ VALUE_TO_HASH(values[index]); + } + + @Override + public String toString() { + return KEY_TO_STRING(keys[index]) + "=" + VALUE_TO_STRING(values[index]); + } + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/collections/templates/maps/impl/tree/AVLTreeMap.template b/src/builder/resources/speiger/assets/collections/templates/maps/impl/tree/AVLTreeMap.template index 69bc214..03a1300 100644 --- a/src/builder/resources/speiger/assets/collections/templates/maps/impl/tree/AVLTreeMap.template +++ b/src/builder/resources/speiger/assets/collections/templates/maps/impl/tree/AVLTreeMap.template @@ -1,2917 +1,2919 @@ -package speiger.src.collections.PACKAGE.maps.impl.tree; - -import java.util.Collections; -import java.util.Map; -#if TYPE_OBJECT -import java.util.Comparator; -#endif -import java.util.Objects; -import java.util.NoSuchElementException; -import java.util.function.Consumer; -import java.util.function.BiFunction; -import java.util.function.Predicate; -#if !TYPE_OBJECT && JDK_TYPE -import java.util.function.PREDICATE; -#endif -#if !SAME_TYPE && JDK_VALUE && !VALUE_OBJECT -import java.util.function.VALUE_PREDICATE; -#endif - - -import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.functions.COMPARATOR; -import speiger.src.collections.PACKAGE.functions.CONSUMER; -import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; -#endif -import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER; -#if !TYPE_OBJECT && !VALUE_OBJECT -import speiger.src.collections.ints.functions.consumer.IntObjectConsumer; -#endif -#if !SAME_TYPE -import speiger.src.collections.ints.functions.consumer.VALUE_BI_FROM_INT_CONSUMER; -#endif -#if !VALUE_BOOLEAN || !JDK_TYPE -import speiger.src.collections.PACKAGE.functions.function.FUNCTION; -#endif -import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; -#if !TYPE_OBJECT && !VALUE_BOOLEAN && !JDK_TYPE -import speiger.src.collections.PACKAGE.functions.function.PREDICATE; -#endif -import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; -#if !SAME_TYPE -import speiger.src.collections.PACKAGE.functions.function.SINGLE_UNARY_OPERATOR; -#endif -import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.NAVIGABLE_MAP; -import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET; -import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET; -#if TYPE_OBJECT -import speiger.src.collections.PACKAGE.sets.SET; -#endif -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; -import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_SUPPLIER; -#if !SAME_TYPE -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_BI_ITERATOR; -import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR; -#endif -#if !VALUE_OBJECT && !SAME_TYPE -import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER; -#endif -#if !TYPE_OBJECT && !VALUE_OBJECT || !VALUE_OBJECT -import speiger.src.collections.objects.functions.consumer.ObjectObjectConsumer; -#endif -#if !SAME_TYPE -#if !TYPE_OBJECT -import speiger.src.collections.objects.functions.consumer.VALUE_BI_FROM_OBJECT_CONSUMER; - -#endif -#if !JDK_VALUE -import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE; -#endif -#endif -#if !TYPE_OBJECT && !VALUE_OBJECT -import speiger.src.collections.objects.collections.ObjectBidirectionalIterator; -#endif -#if !VALUE_OBJECT -import speiger.src.collections.objects.collections.ObjectIterator; -#endif -#if !TYPE_OBJECT -#if !VALUE_OBJECT -import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator; - -#endif -import speiger.src.collections.objects.sets.AbstractObjectSet; -import speiger.src.collections.objects.sets.ObjectSet; -#endif - -/** - * A Simple Type Specific AVL TreeMap implementation that reduces boxing/unboxing. - * It is using a bit more memory then FastUtil, - * but it saves a lot of Performance on the Optimized removal and iteration logic. - * Which makes the implementation actually useable and does not get outperformed by Javas default implementation. - * @Type(T) - * @ValueType(V) - */ -public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE -{ - /** The center of the Tree */ - protected transient Node KEY_VALUE_GENERIC_TYPE tree; - /** The Lowest possible Node */ - protected transient Node KEY_VALUE_GENERIC_TYPE first; - /** The Highest possible Node */ - protected transient Node KEY_VALUE_GENERIC_TYPE last; - /** The amount of elements stored in the Map */ - protected int size = 0; - /** The Sorter of the Tree */ - protected transient COMPARATOR KEY_GENERIC_TYPE comparator; - -#if !TYPE_OBJECT - /** the default return value for max searches */ - protected KEY_TYPE defaultMaxNotFound = CLASS_TYPE.MIN_VALUE; - /** the default return value for min searches */ - protected KEY_TYPE defaultMinNotFound = CLASS_TYPE.MAX_VALUE; -#endif - - /** KeySet Cache */ - protected NAVIGABLE_SET KEY_GENERIC_TYPE keySet; - /** Values Cache */ - protected VALUE_COLLECTION VALUE_GENERIC_TYPE values; - /** EntrySet Cache */ - protected ObjectSet entrySet; - - /** - * Default Constructor - */ - public AVL_TREE_MAP() { - } - - /** - * Constructor that allows to define the sorter - * @param comp the function that decides how the tree is sorted, can be null - */ - public AVL_TREE_MAP(COMPARATOR KEY_GENERIC_TYPE comp) { - comparator = comp; - } - -#if !TYPE_OBJECT || !VALUE_OBJECT - /** - * Helper constructor that allow to create a map from boxed values (it will unbox them) - * @param keys the keys that should be put into the map - * @param values the values that should be put into the map. - * @throws IllegalStateException if the keys and values do not match in lenght - */ - public AVL_TREE_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values) { - this(keys, values, null); - } - - /** - * Helper constructor that has a custom sorter and allow to create a map from boxed values (it will unbox them) - * @param keys the keys that should be put into the map - * @param values the values that should be put into the map. - * @param comp the function that decides how the tree is sorted, can be null - * @throws IllegalStateException if the keys and values do not match in lenght - */ - public AVL_TREE_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, COMPARATOR KEY_GENERIC_TYPE comp) { - comparator = comp; - if(keys.length != values.length) throw new IllegalStateException("Input Arrays are not equal size"); - for(int i = 0,m=keys.length;i map) { - this(map, null); - } - - /** - * A Helper constructor that has a custom sorter and allows to create a Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - * @param comp the function that decides how the tree is sorted, can be null - */ - public AVL_TREE_MAP(Map map, COMPARATOR KEY_GENERIC_TYPE comp) { - comparator = comp; - putAll(map); - } - - /** - * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - */ - public AVL_TREE_MAP(MAP KEY_VALUE_GENERIC_TYPE map) { - this(map, null); - } - - /** - * A Type Specific Helper function that has a custom sorter and allows to create a new Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - * @param comp the function that decides how the tree is sorted, can be null - */ - public AVL_TREE_MAP(MAP KEY_VALUE_GENERIC_TYPE map, COMPARATOR KEY_GENERIC_TYPE comp) { - comparator = comp; - putAll(map); - } - -#if TYPE_OBJECT - /** only used for primitives - * @return null - */ - public KEY_TYPE getDefaultMaxValue() { return null; } - /** only used for primitives - * @return null - */ - public KEY_TYPE getDefaultMinValue() { return null; } - -#else - @Override - public void setDefaultMaxValue(KEY_TYPE value) { defaultMaxNotFound = value; } - @Override - public KEY_TYPE getDefaultMaxValue() { return defaultMaxNotFound; } - @Override - public void setDefaultMinValue(KEY_TYPE value) { defaultMinNotFound = value; } - @Override - public KEY_TYPE getDefaultMinValue() { return defaultMinNotFound; } - -#endif - - @Override - public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { -#if TYPE_OBJECT - validate(key); -#endif - if(tree == null) { - tree = first = last = new NodeKV_BRACES(key, value, null); - size++; - return getDefaultReturnValue(); - } - int compare = 0; - Node KEY_VALUE_GENERIC_TYPE parent = tree; - while(true) { - if((compare = compare(key, parent.key)) == 0) return parent.setValue(value); - if(compare < 0) { - if(parent.left == null) break; - parent = parent.left; - } - else if(compare > 0) { - if(parent.right == null) break; - parent = parent.right; - } - } - Node KEY_VALUE_GENERIC_TYPE adding = new NodeKV_BRACES(key, value, parent); - if(compare < 0) { - parent.left = adding; - if(parent == first) first = adding; - } - else { - parent.right = adding; - if(parent == last) last = adding; - } - fixAfterInsertion(adding); - size++; - return getDefaultReturnValue(); - } - - @Override - public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { -#if TYPE_OBJECT - validate(key); -#endif - if(tree == null) { - tree = first = last = new NodeKV_BRACES(key, value, null); - size++; - return getDefaultReturnValue(); - } - int compare = 0; - Node KEY_VALUE_GENERIC_TYPE parent = tree; - while(true) { - if((compare = compare(key, parent.key)) == 0) { - if(VALUE_EQUALS(parent.value, getDefaultReturnValue())) return parent.setValue(value); - return parent.value; - } - if(compare < 0) { - if(parent.left == null) break; - parent = parent.left; - } - else if(compare > 0) { - if(parent.right == null) break; - parent = parent.right; - } - } - Node KEY_VALUE_GENERIC_TYPE adding = new NodeKV_BRACES(key, value, parent); - if(compare < 0) { - parent.left = adding; - if(parent == first) first = adding; - } - else { - parent.right = adding; - if(parent == last) last = adding; - } - fixAfterInsertion(adding); - size++; - return getDefaultReturnValue(); - } - -#if VALUE_PRIMITIVES - @Override - public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { - if(tree == null) { - tree = first = last = new NodeKV_BRACES(key, value, null); - size++; - return getDefaultReturnValue(); - } - int compare = 0; - Node KEY_VALUE_GENERIC_TYPE parent = tree; - while(true) { - if((compare = compare(key, parent.key)) == 0) return parent.addTo(value); - if(compare < 0) { - if(parent.left == null) break; - parent = parent.left; - } - else if(compare > 0) { - if(parent.right == null) break; - parent = parent.right; - } - } - Node KEY_VALUE_GENERIC_TYPE adding = new NodeKV_BRACES(key, value, parent); - if(compare < 0) { - parent.left = adding; - if(parent == first) first = adding; - } - else { - parent.right = adding; - if(parent == last) last = adding; - } - fixAfterInsertion(adding); - size++; - return getDefaultReturnValue(); - } - - @Override - public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { - if(tree == null) return getDefaultReturnValue(); - int compare = 0; - Node KEY_VALUE_GENERIC_TYPE parent = tree; - while(true) { - if((compare = compare(key, parent.key)) == 0) - { - VALUE_TYPE oldValue = parent.subFrom(value); - if(value < 0 ? (parent.value >= getDefaultReturnValue()) : (parent.value <= getDefaultReturnValue())) removeNode(parent); - return oldValue; - } - if(compare < 0) { - if(parent.left == null) break; - parent = parent.left; - } - else if(compare > 0) { - if(parent.right == null) break; - parent = parent.right; - } - } - return getDefaultReturnValue(); - } - -#endif - @Override - public COMPARATOR KEY_GENERIC_TYPE comparator() { return comparator; } - -#if TYPE_OBJECT - @Override - public boolean containsKey(Object key) { - return findNode((KEY_TYPE)key) != null; - } - -#else - @Override - public boolean containsKey(KEY_TYPE key) { - return findNode(key) != null; - } - -#endif - @Override - public VALUE_TYPE GET_VALUE(KEY_TYPE key) { - Node KEY_VALUE_GENERIC_TYPE node = findNode(key); - return node == null ? getDefaultReturnValue() : node.value; - } - -#if TYPE_OBJECT && VALUE_OBJECT - @Override - public VALUE_TYPE getOrDefault(Object key, VALUE_TYPE defaultValue) { - Node KEY_VALUE_GENERIC_TYPE node = findNode((CLASS_TYPE)key); - return node == null ? defaultValue : node.value; - } - -#else - @Override - public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { - Node KEY_VALUE_GENERIC_TYPE node = findNode(key); - return node == null ? defaultValue : node.value; - } - -#endif - @Override - public KEY_TYPE FIRST_ENTRY_KEY() { - if(tree == null) throw new NoSuchElementException(); - return first.key; - } - - @Override - public KEY_TYPE POLL_FIRST_ENTRY_KEY() { - if(tree == null) return getDefaultMinValue(); - KEY_TYPE result = first.key; - removeNode(first); - return result; - } - - @Override - public KEY_TYPE LAST_ENTRY_KEY() { - if(tree == null) throw new NoSuchElementException(); - return last.key; - } - - @Override - public KEY_TYPE POLL_LAST_ENTRY_KEY() { - if(tree == null) return getDefaultMaxValue(); - KEY_TYPE result = last.key; - removeNode(last); - return result; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE firstEntry() { - if(tree == null) return null; - return first.export(); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE lastEntry() { - if(tree == null) return null; - return last.export(); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirstEntry() { - if(tree == null) return null; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = first.export(); - removeNode(first); - return entry; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLastEntry() { - if(tree == null) return null; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = last.export(); - removeNode(last); - return entry; - } - - @Override - public VALUE_TYPE FIRST_ENTRY_VALUE() { - if(tree == null) throw new NoSuchElementException(); - return first.value; - } - - @Override - public VALUE_TYPE LAST_ENTRY_VALUE() { - if(tree == null) throw new NoSuchElementException(); - return last.value; - } - - @Override - public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { - Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); - if(entry == null) return getDefaultReturnValue(); - VALUE_TYPE value = entry.value; - removeNode(entry); - return value; - } - - @Override - public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { - Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); - if(entry == null) return defaultValue; - VALUE_TYPE value = entry.value; - removeNode(entry); - return value; - } - -#if TYPE_OBJECT && VALUE_OBJECT - @Override - public boolean remove(Object key, Object value) { - Node KEY_VALUE_GENERIC_TYPE entry = findNode((CLASS_TYPE)key); - if(entry == null || !Objects.equals(value, entry.value)) return false; - removeNode(entry); - return true; - } - -#else - @Override - public boolean remove(KEY_TYPE key, VALUE_TYPE value) { - Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); - if(entry == null || entry.value != value) return false; - removeNode(entry); - return true; - } - -#endif - @Override - public boolean replace(KEY_TYPE key, VALUE_TYPE oldValue, VALUE_TYPE newValue) { - Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); - if(entry == null || entry.value != oldValue) return false; - entry.value = newValue; - return true; - } - - @Override - public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value) { - Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); - if(entry == null) return getDefaultReturnValue(); - VALUE_TYPE oldValue = entry.value; - entry.value = value; - return oldValue; - } - - @Override - public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); -#if TYPE_OBJECT - validate(key); -#endif - Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); - if(entry == null) { - VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, getDefaultReturnValue()); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - put(key, newValue); - return newValue; - } - VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, entry.value); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - removeNode(entry); - return newValue; - } - entry.value = newValue; - return newValue; - } - - @Override - public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); -#if TYPE_OBJECT - validate(key); -#endif - Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); - if(entry == null) { - VALUE_TYPE newValue = mappingFunction.APPLY(key); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - put(key, newValue); - return newValue; - } - if(Objects.equals(entry.value, getDefaultReturnValue())) { - VALUE_TYPE newValue = mappingFunction.APPLY(key); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - entry.value = newValue; - } - return entry.value; - } - - @Override - public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) { - Objects.requireNonNull(valueProvider); -#if TYPE_OBJECT - validate(key); -#endif - Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); - if(entry == null) { - VALUE_TYPE newValue = valueProvider.VALUE_SUPPLY_GET(); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - put(key, newValue); - return newValue; - } - if(VALUE_EQUALS(entry.value, getDefaultReturnValue())) { - VALUE_TYPE newValue = valueProvider.VALUE_SUPPLY_GET(); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - entry.value = newValue; - } - return entry.value; - } - - @Override - public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); -#if TYPE_OBJECT - validate(key); -#endif - Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); - if(entry == null || VALUE_EQUALS(entry.value, getDefaultReturnValue())) return getDefaultReturnValue(); - VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, entry.value); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - removeNode(entry); - return newValue; - } - entry.value = newValue; - return newValue; - } - - @Override - public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); -#if TYPE_OBJECT - validate(key); -#endif - Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); - VALUE_TYPE newValue = entry == null || VALUE_EQUALS(entry.value, getDefaultReturnValue()) ? value : mappingFunction.APPLY_VALUE(entry.value, value); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - if(entry != null) - removeNode(entry); - } - else if(entry == null) put(key, newValue); - else entry.value = newValue; - return newValue; - } - - @Override - public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); - for(MAP.Entry KEY_VALUE_GENERIC_TYPE entry : getFastIterable(m)) { - KEY_TYPE key = entry.ENTRY_KEY(); - Node KEY_VALUE_GENERIC_TYPE subEntry = findNode(key); - VALUE_TYPE newValue = subEntry == null || VALUE_EQUALS(subEntry.value, getDefaultReturnValue()) ? entry.ENTRY_VALUE() : mappingFunction.APPLY_VALUE(subEntry.value, entry.ENTRY_VALUE()); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - if(subEntry != null) - removeNode(subEntry); - } - else if(subEntry == null) put(key, newValue); - else subEntry.value = newValue; - } - } - - @Override - public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - action.accept(entry.key, entry.value); - } - - @Override - public int size() { return size; } - - @Override - public void clear() { - size = 0; - first = null; - last = null; - tree = null; - } - - protected BI_ITERATOR KEY_GENERIC_TYPE keyIterator() { - return new AscendingKeyIterator(first); - } - - protected BI_ITERATOR KEY_GENERIC_TYPE keyIterator(KEY_TYPE element) { - return new AscendingKeyIterator(findNode(element)); - } - - protected BI_ITERATOR KEY_GENERIC_TYPE descendingKeyIterator() { - return new DescendingKeyIterator(last); - } - - @Override - public AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE copy() { - AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE set = new AVL_TREE_MAPKV_BRACES(); - set.size = size; - if(tree != null) { - set.tree = tree.copy(); - Node KEY_VALUE_GENERIC_TYPE lastFound = null; - for(Node KEY_VALUE_GENERIC_TYPE entry = tree;entry != null;entry = entry.left) lastFound = entry; - set.first = lastFound; - lastFound = null; - for(Node KEY_VALUE_GENERIC_TYPE entry = tree;entry != null;entry = entry.right) lastFound = entry; - set.last = lastFound; - } - return set; - } - - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE keySet() { - return navigableKeySet(); - } - - @Override - public ObjectSet ENTRY_SET() { - if(entrySet == null) entrySet = new EntrySet(); - return entrySet; - } - - @Override - public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { - if(values == null) values = new Values(); - return values; - } - - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE navigableKeySet() { - if(keySet == null) keySet = new KeySetKV_BRACES(this); - return keySet; - } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap() { - return new DescendingNaivgableSubMapKV_BRACES(this, true, EMPTY_KEY_VALUE, true, true, EMPTY_KEY_VALUE, true); - } - - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE descendingKeySet() { - return descendingMap().navigableKeySet(); - } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, boolean fromInclusive, KEY_TYPE toKey, boolean toInclusive) { - return new AscendingNaivgableSubMapKV_BRACES(this, false, fromKey, fromInclusive, false, toKey, toInclusive); - } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey, boolean inclusive) { - return new AscendingNaivgableSubMapKV_BRACES(this, true, EMPTY_KEY_VALUE, true, false, toKey, inclusive); - } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey, boolean inclusive) { - return new AscendingNaivgableSubMapKV_BRACES(this, false, fromKey, inclusive, true, EMPTY_KEY_VALUE, true); - } - - @Override - public KEY_TYPE lowerKey(KEY_TYPE e) { - Node KEY_VALUE_GENERIC_TYPE node = findLowerNode(e); - return node != null ? node.key : getDefaultMinValue(); - } - - @Override - public KEY_TYPE floorKey(KEY_TYPE e) { - Node KEY_VALUE_GENERIC_TYPE node = findFloorNode(e); - return node != null ? node.key : getDefaultMinValue(); - } - - @Override - public KEY_TYPE higherKey(KEY_TYPE e) { - Node KEY_VALUE_GENERIC_TYPE node = findHigherNode(e); - return node != null ? node.key : getDefaultMaxValue(); - } - - @Override - public KEY_TYPE ceilingKey(KEY_TYPE e) { - Node KEY_VALUE_GENERIC_TYPE node = findCeilingNode(e); - return node != null ? node.key : getDefaultMaxValue(); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE lowerEntry(KEY_TYPE key) { - Node KEY_VALUE_GENERIC_TYPE node = findLowerNode(key); - return node != null ? node.export() : null; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE higherEntry(KEY_TYPE key) { - Node KEY_VALUE_GENERIC_TYPE node = findHigherNode(key); - return node != null ? node.export() : null; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE floorEntry(KEY_TYPE key) { - Node KEY_VALUE_GENERIC_TYPE node = findFloorNode(key); - return node != null ? node.export() : null; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE ceilingEntry(KEY_TYPE key) { - Node KEY_VALUE_GENERIC_TYPE node = findCeilingNode(key); - return node != null ? node.export() : null; - } - - protected Node KEY_VALUE_GENERIC_TYPE findLowerNode(KEY_TYPE key) { - Node KEY_VALUE_GENERIC_TYPE entry = tree; - while(entry != null) { - if(compare(key, entry.key) > 0) { - if(entry.right != null) entry = entry.right; - else return entry; - } - else { - if(entry.left != null) entry = entry.left; - else { - Node KEY_VALUE_GENERIC_TYPE parent = entry.parent; - while(parent != null && parent.left == entry) { - entry = parent; - parent = parent.parent; - } - return parent; - } - } - } - return null; - } - - protected Node KEY_VALUE_GENERIC_TYPE findFloorNode(KEY_TYPE key) { - Node KEY_VALUE_GENERIC_TYPE entry = tree; - int compare; - while(entry != null) { - if((compare = compare(key, entry.key)) > 0) { - if(entry.right == null) break; - entry = entry.right; - continue; - } - else if(compare < 0) { - if(entry.left != null) entry = entry.left; - else { - Node KEY_VALUE_GENERIC_TYPE parent = entry.parent; - while(parent != null && parent.left == entry) { - entry = parent; - parent = parent.parent; - } - return parent; - } - continue; - } - break; - } - return entry; - } - - protected Node KEY_VALUE_GENERIC_TYPE findCeilingNode(KEY_TYPE key) { - Node KEY_VALUE_GENERIC_TYPE entry = tree; - int compare; - while(entry != null) { - if((compare = compare(key, entry.key)) < 0) { - if(entry.left == null) break; - entry = entry.left; - continue; - } - else if(compare > 0) { - if(entry.right != null) entry = entry.right; - else { - Node KEY_VALUE_GENERIC_TYPE parent = entry.parent; - while(parent != null && parent.right == entry) { - entry = parent; - parent = parent.parent; - } - return parent; - } - continue; - } - break; - } - return entry; - } - - protected Node KEY_VALUE_GENERIC_TYPE findHigherNode(KEY_TYPE key) { - Node KEY_VALUE_GENERIC_TYPE entry = tree; - while(entry != null) { - if(compare(key, entry.key) < 0) { - if(entry.left != null) entry = entry.left; - else return entry; - } - else { - if(entry.right != null) entry = entry.right; - else { - Node KEY_VALUE_GENERIC_TYPE parent = entry.parent; - while(parent != null && parent.right == entry) { - entry = parent; - parent = parent.parent; - } - return parent; - } - } - } - return null; - } - - protected Node KEY_VALUE_GENERIC_TYPE findNode(KEY_TYPE key) { - Node KEY_VALUE_GENERIC_TYPE node = tree; - int compare; - while(node != null) { - if((compare = compare(key, node.key)) == 0) return node; - if(compare < 0) node = node.left; - else node = node.right; - } - return null; - } - - protected void removeNode(Node KEY_VALUE_GENERIC_TYPE entry) { - size--; - if(entry.needsSuccessor()) { - Node KEY_VALUE_GENERIC_TYPE successor = entry.next(); - entry.key = successor.key; - entry.value = successor.value; - entry = successor; - } - if(entry.previous() == null) first = entry.next(); - if(entry.next() == null) last = entry.previous(); - Node KEY_VALUE_GENERIC_TYPE replacement = entry.left != null ? entry.left : entry.right; - if(replacement != null) { - if(entry.replace(replacement)) tree = replacement; - entry.left = entry.right = entry.parent = null; - fixAfterDeletion(replacement); - } - else if(entry.parent == null) tree = first = last = null; - else { - fixAfterDeletion(entry); - entry.replace(null); - entry.parent = null; - } - } - - protected void validate(KEY_TYPE k) { compare(k, k); } - protected int compare(KEY_TYPE k, KEY_TYPE v) { return comparator != null ? comparator.compare(k, v) : COMPAREABLE_TO_KEY(k, v);} - - /** From CLR */ - protected void rotateLeft(Node KEY_VALUE_GENERIC_TYPE entry) { - if(entry != null) { - Node KEY_VALUE_GENERIC_TYPE right = entry.right; - entry.right = right.left; - if(right.left != null) right.left.parent = entry; - right.parent = entry.parent; - if(entry.parent == null) tree = right; - else if(entry.parent.left == entry) entry.parent.left = right; - else entry.parent.right = right; - right.left = entry; - entry.parent = right; - entry.updateHeight(); - right.updateHeight(); - } - } - - /** From CLR */ - protected void rotateRight(Node KEY_VALUE_GENERIC_TYPE entry) { - if(entry != null) { - Node KEY_VALUE_GENERIC_TYPE left = entry.left; - entry.left = left.right; - if(left.right != null) left.right.parent = entry; - left.parent = entry.parent; - if(entry.parent == null) tree = left; - else if(entry.parent.right == entry) entry.parent.right = left; - else entry.parent.left = left; - left.right = entry; - entry.parent = left; - entry.updateHeight(); - left.updateHeight(); - } - } - - /** From CLR */ - protected void fixAfterInsertion(Node KEY_VALUE_GENERIC_TYPE entry) { - while(entry != null) { - entry.updateHeight(); - int balance = entry.getBalance(); - if(balance > 1) { - int compare = entry.left.getBalance(); - if(compare > 0) rotateRight(entry); - else if(compare < 0) { - rotateLeft(entry.left); - rotateRight(entry); - } - } - else if(balance < -1) { - int compare = entry.right.getBalance(); - if(compare < 0) rotateLeft(entry); - else if(compare > 0) { - rotateRight(entry.right); - rotateLeft(entry); - } - } - entry = entry.parent; - } - } - - /** From CLR */ - protected void fixAfterDeletion(Node KEY_VALUE_GENERIC_TYPE entry) { - if(entry != null) { - entry.updateHeight(); - int balance = entry.getBalance(); - if(balance > 1) { - int subBalance = entry.left.getBalance(); - if(subBalance >= 0) rotateRight(entry); - else { - rotateLeft(entry.left); - rotateRight(entry); - } - } - else if(balance < -1) - { - int subBalance = entry.right.getBalance(); - if(subBalance <= 0) rotateLeft(entry); - else { - rotateRight(entry.right); - rotateLeft(entry); - } - } - entry = entry.parent; - } - } - - static class KeySet KEY_VALUE_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE implements NAVIGABLE_SET KEY_GENERIC_TYPE - { - NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map; - - public KeySet(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map) { - this.map = map; - } - -#if !TYPE_OBJECT - @Override - public void setDefaultMaxValue(KEY_TYPE e) { map.setDefaultMaxValue(e); } - @Override - public KEY_TYPE getDefaultMaxValue() { return map.getDefaultMaxValue(); } - @Override - public void setDefaultMinValue(KEY_TYPE e) { map.setDefaultMinValue(e); } - @Override - public KEY_TYPE getDefaultMinValue() { return map.getDefaultMinValue(); } -#endif - @Override - public KEY_TYPE lower(KEY_TYPE e) { return map.lowerKey(e); } - @Override - public KEY_TYPE floor(KEY_TYPE e) { return map.floorKey(e); } - @Override - public KEY_TYPE ceiling(KEY_TYPE e) { return map.ceilingKey(e); } - @Override - public KEY_TYPE higher(KEY_TYPE e) { return map.higherKey(e); } - -#if !TYPE_OBJECT - @Override - public CLASS_TYPE lower(CLASS_TYPE e) { - MAP.Entry KEY_VALUE_GENERIC_TYPE node = map.lowerEntry(OBJ_TO_KEY(e)); - return node != null ? node.getKey() : null; - } - - @Override - public CLASS_TYPE floor(CLASS_TYPE e) { - MAP.Entry KEY_VALUE_GENERIC_TYPE node = map.floorEntry(OBJ_TO_KEY(e)); - return node != null ? node.getKey() : null; - } - - @Override - public CLASS_TYPE higher(CLASS_TYPE e) { - MAP.Entry KEY_VALUE_GENERIC_TYPE node = map.higherEntry(OBJ_TO_KEY(e)); - return node != null ? node.getKey() : null; - } - - @Override - public CLASS_TYPE ceiling(CLASS_TYPE e) { - MAP.Entry KEY_VALUE_GENERIC_TYPE node = map.ceilingEntry(OBJ_TO_KEY(e)); - return node != null ? node.getKey() : null; - } - -#endif - @Override - public KEY_TYPE POLL_FIRST_KEY() { return map.POLL_FIRST_ENTRY_KEY(); } - @Override - public KEY_TYPE POLL_LAST_KEY() { return map.POLL_LAST_ENTRY_KEY(); } - @Override - public COMPARATOR KEY_GENERIC_TYPE comparator() { return map.comparator(); } - @Override - public KEY_TYPE FIRST_KEY() { return map.FIRST_ENTRY_KEY(); } - @Override - public KEY_TYPE LAST_KEY() { return map.LAST_ENTRY_KEY(); } - @Override - public void clear() { map.clear(); } - -#if TYPE_OBJECT - @Override - public boolean remove(Object o) { - int oldSize = map.size(); - map.remove(o); - return oldSize != map.size(); - } - -#else - @Override - public boolean remove(KEY_TYPE o) { - int oldSize = map.size(); - map.remove(o); - return oldSize != map.size(); - } - -#endif - @Override - public boolean add(KEY_TYPE e) { throw new UnsupportedOperationException(); } - - @Override - public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { - if(map instanceof AVL_TREE_MAP) return ((AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE)map).keyIterator(fromElement); - return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).keyIterator(fromElement); - } - - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, boolean fromInclusive, KEY_TYPE toElement, boolean toInclusive) { return new KeySetKV_BRACES(map.subMap(fromElement, fromInclusive, toElement, toInclusive)); } - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement, boolean inclusive) { return new KeySetKV_BRACES(map.headMap(toElement, inclusive)); } - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement, boolean inclusive) { return new KeySetKV_BRACES(map.tailMap(fromElement, inclusive)); } - - @Override - public BI_ITERATOR KEY_GENERIC_TYPE iterator() { - if(map instanceof AVL_TREE_MAP) return ((AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE)map).keyIterator(); - return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).keyIterator(); - } - - @Override - public BI_ITERATOR KEY_GENERIC_TYPE descendingIterator() { - if(map instanceof AVL_TREE_MAP) return ((AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE)map).descendingKeyIterator(); - return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).descendingKeyIterator(); - } - - protected Node KEY_VALUE_GENERIC_TYPE start() { - if(map instanceof AVL_TREE_MAP) return ((AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE)map).first; - return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).subLowest(); - } - - protected Node KEY_VALUE_GENERIC_TYPE end() { - if(map instanceof AVL_TREE_MAP) return null; - return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).subHighest(); - } - - protected Node KEY_VALUE_GENERIC_TYPE next(Node KEY_VALUE_GENERIC_TYPE entry) { - if(map instanceof AVL_TREE_MAP) return entry.next(); - return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).next(entry); - } - - protected Node KEY_VALUE_GENERIC_TYPE previous(Node KEY_VALUE_GENERIC_TYPE entry) { - if(map instanceof AVL_TREE_MAP) return entry.previous(); - return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).previous(entry); - } - - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE descendingSet() { return new KeySetKV_BRACES(map.descendingMap()); } - @Override - public KeySet KEY_VALUE_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); } - @Override - public boolean isEmpty() { return map.isEmpty(); } - @Override - public int size() { return map.size(); } - - @Override - public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { - Objects.requireNonNull(action); - for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) - action.accept(entry.key); - } - - @Override - public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) { - Objects.requireNonNull(action); - int index = 0; - for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) - action.accept(index++, entry.key); - } - - @Override - public void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { - Objects.requireNonNull(action); - for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) - action.accept(input, entry.key); - } - - @Override - public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) - if(filter.test(entry.key)) return true; - return false; - } - - @Override - public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) - if(filter.test(entry.key)) return false; - return true; - } - - @Override - public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) - if(!filter.test(entry.key)) return false; - return true; - } - -#if !TYPE_OBJECT - @Override - public KEY_TYPE reduce(KEY_TYPE identity, SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - KEY_TYPE state = identity; - for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) - state = operator.APPLY_KEY_VALUE(state, entry.key); - return state; - } - -#else - @Override - public KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) { - Objects.requireNonNull(operator); - KEY_SPECIAL_TYPE state = identity; - for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) - state = operator.apply(state, entry.key); - return state; - } - -#endif - @Override - public KEY_TYPE reduce(SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - KEY_TYPE state = EMPTY_KEY_VALUE; - boolean empty = true; - for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) { - if(empty) { - empty = false; - state = entry.key; - continue; - } - state = operator.APPLY_KEY_VALUE(state, entry.key); - } - return state; - } - - @Override - public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) - if(filter.test(entry.key)) return entry.key; - return EMPTY_KEY_VALUE; - } - - @Override - public int count(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - int result = 0; - for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) - if(filter.test(entry.key)) result++; - return result; - } - } - - static class AscendingNaivgableSubMap KEY_VALUE_GENERIC_TYPE extends NavigableSubMap KEY_VALUE_GENERIC_TYPE - { - AscendingNaivgableSubMap(AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE map, boolean fromStart, KEY_TYPE lo, boolean loInclusive, boolean toEnd, KEY_TYPE hi, boolean hiInclusive) { - super(map, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); - } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap() { - if(inverse == null) inverse = new DescendingNaivgableSubMapKV_BRACES(map, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); - return inverse; - } - - @Override - public ObjectSet ENTRY_SET() { - if(entrySet == null) entrySet = new AscendingSubEntrySet(); - return entrySet; - } - - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE navigableKeySet() { - if(keySet == null) keySet = new KeySetKV_BRACES(this); - return keySet; - } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, boolean fromInclusive, KEY_TYPE toKey, boolean toInclusive) { - if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range"); - if (!inRange(toKey, toInclusive)) throw new IllegalArgumentException("toKey out of range"); - return new AscendingNaivgableSubMapKV_BRACES(map, false, fromKey, fromInclusive, false, toKey, toInclusive); - } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey, boolean inclusive) { - if (!inRange(toKey, inclusive)) throw new IllegalArgumentException("toKey out of range"); - return new AscendingNaivgableSubMapKV_BRACES(map, fromStart, lo, loInclusive, false, toKey, inclusive); - } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey, boolean inclusive) { - if (!inRange(fromKey, inclusive)) throw new IllegalArgumentException("fromKey out of range"); - return new AscendingNaivgableSubMapKV_BRACES(map, false, fromKey, inclusive, toEnd, hi, hiInclusive); - } - - @Override - protected Node KEY_VALUE_GENERIC_TYPE subLowest() { return absLowest(); } - @Override - protected Node KEY_VALUE_GENERIC_TYPE subHighest() { return absHighest(); } - @Override - protected Node KEY_VALUE_GENERIC_TYPE subCeiling(KEY_TYPE key) { return absCeiling(key); } - @Override - protected Node KEY_VALUE_GENERIC_TYPE subHigher(KEY_TYPE key) { return absHigher(key); } - @Override - protected Node KEY_VALUE_GENERIC_TYPE subFloor(KEY_TYPE key) { return absFloor(key); } - @Override - protected Node KEY_VALUE_GENERIC_TYPE subLower(KEY_TYPE key) { return absLower(key); } - - @Override - protected BI_ITERATOR KEY_GENERIC_TYPE keyIterator() { - return new AcsendingSubKeyIterator(absLowest(), absHighFence(), absLowFence()); - } - @Override - protected BI_ITERATOR KEY_GENERIC_TYPE keyIterator(KEY_TYPE element) { - return new AcsendingSubKeyIterator(absLower(element), absHighFence(), absLowFence()); - } - - @Override - protected VALUE_BI_ITERATOR VALUE_GENERIC_TYPE valueIterator() { - return new AcsendingSubValueIterator(absLowest(), absHighFence(), absLowFence()); - } - - @Override - protected BI_ITERATOR KEY_GENERIC_TYPE descendingKeyIterator() { - return new DecsendingSubKeyIterator(absHighest(), absLowFence(), absHighFence()); - } - - class AscendingSubEntrySet extends SubEntrySet { - @Override - public ObjectIterator iterator() { - return new AcsendingSubEntryIterator(absLowest(), absHighFence(), absLowFence()); - } - } - } - - static class DescendingNaivgableSubMap KEY_VALUE_GENERIC_TYPE extends NavigableSubMap KEY_VALUE_GENERIC_TYPE - { - COMPARATOR KEY_GENERIC_TYPE comparator; - DescendingNaivgableSubMap(AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE map, boolean fromStart, KEY_TYPE lo, boolean loInclusive, boolean toEnd, KEY_TYPE hi, boolean hiInclusive) { - super(map, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); -#if TYPE_OBJECT - comparator = Collections.reverseOrder(map.comparator()); -#else - comparator = map.comparator() == null ? COMPARATOR.of(Collections.reverseOrder()) : map.comparator().reversed(); -#endif - } - - @Override - public COMPARATOR KEY_GENERIC_TYPE comparator() { return comparator; } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap() { - if(inverse == null) inverse = new AscendingNaivgableSubMapKV_BRACES(map, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); - return inverse; - } - - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE navigableKeySet() { - if(keySet == null) keySet = new KeySetKV_BRACES(this); - return keySet; - } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, boolean fromInclusive, KEY_TYPE toKey, boolean toInclusive) { - if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range"); - if (!inRange(toKey, toInclusive)) throw new IllegalArgumentException("toKey out of range"); - return new DescendingNaivgableSubMapKV_BRACES(map, false, toKey, toInclusive, false, fromKey, fromInclusive); - } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey, boolean inclusive) { - if (!inRange(toKey, inclusive)) throw new IllegalArgumentException("toKey out of range"); - return new DescendingNaivgableSubMapKV_BRACES(map, false, toKey, inclusive, toEnd, hi, hiInclusive); - } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey, boolean inclusive) { - if (!inRange(fromKey, inclusive)) throw new IllegalArgumentException("fromKey out of range"); - return new DescendingNaivgableSubMapKV_BRACES(map, fromStart, lo, loInclusive, false, fromKey, inclusive); - } - - @Override - public ObjectSet ENTRY_SET() { - if(entrySet == null) entrySet = new DescendingSubEntrySet(); - return entrySet; - } - - @Override - protected Node KEY_VALUE_GENERIC_TYPE subLowest() { return absHighest(); } - @Override - protected Node KEY_VALUE_GENERIC_TYPE subHighest() { return absLowest(); } - @Override - protected Node KEY_VALUE_GENERIC_TYPE subCeiling(KEY_TYPE key) { return absFloor(key); } - @Override - protected Node KEY_VALUE_GENERIC_TYPE subHigher(KEY_TYPE key) { return absLower(key); } - @Override - protected Node KEY_VALUE_GENERIC_TYPE subFloor(KEY_TYPE key) { return absCeiling(key); } - @Override - protected Node KEY_VALUE_GENERIC_TYPE subLower(KEY_TYPE key) { return absHigher(key); } - @Override - protected Node KEY_VALUE_GENERIC_TYPE next(Node KEY_VALUE_GENERIC_TYPE entry) { return entry.previous(); } - @Override - protected Node KEY_VALUE_GENERIC_TYPE previous(Node KEY_VALUE_GENERIC_TYPE entry) { return entry.next(); } - - @Override - protected BI_ITERATOR KEY_GENERIC_TYPE keyIterator() { - return new DecsendingSubKeyIterator(absHighest(), absLowFence(), absHighFence()); - } - - @Override - protected BI_ITERATOR KEY_GENERIC_TYPE keyIterator(KEY_TYPE element) { - return new DecsendingSubKeyIterator(absHigher(element), absLowFence(), absHighFence()); - } - - @Override - protected VALUE_BI_ITERATOR VALUE_GENERIC_TYPE valueIterator() { - return new DecsendingSubValueIterator(absHighest(), absLowFence(), absHighFence()); - } - - @Override - protected BI_ITERATOR KEY_GENERIC_TYPE descendingKeyIterator() { - return new AcsendingSubKeyIterator(absLowest(), absHighFence(), absLowFence()); - } - - class DescendingSubEntrySet extends SubEntrySet { - @Override - public ObjectIterator iterator() { - return new DecsendingSubEntryIterator(absHighest(), absLowFence(), absHighFence()); - } - } - } - - static abstract class NavigableSubMap KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE - { - final AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE map; - final KEY_TYPE lo, hi; - final boolean fromStart, toEnd; - final boolean loInclusive, hiInclusive; - - NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE inverse; - NAVIGABLE_SET KEY_GENERIC_TYPE keySet; - ObjectSet entrySet; - VALUE_COLLECTION VALUE_GENERIC_TYPE values; - - NavigableSubMap(AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE map, boolean fromStart, KEY_TYPE lo, boolean loInclusive, boolean toEnd, KEY_TYPE hi, boolean hiInclusive) { - if (!fromStart && !toEnd) { - if (map.compare(lo, hi) > 0) throw new IllegalArgumentException("fromKey > toKey"); - } - else { - if (!fromStart) map.validate(lo); - if (!toEnd) map.validate(hi); - } - this.map = map; - this.fromStart = fromStart; - this.lo = lo; - this.loInclusive = loInclusive; - this.toEnd = toEnd; - this.hi = hi; - this.hiInclusive = hiInclusive; - } - -#if TYPE_OBJECT - public KEY_TYPE getDefaultMaxValue() { return map.getDefaultMaxValue(); } - public KEY_TYPE getDefaultMinValue() { return map.getDefaultMinValue(); } -#else - @Override - public void setDefaultMaxValue(KEY_TYPE e) { map.setDefaultMaxValue(e); } - @Override - public KEY_TYPE getDefaultMaxValue() { return map.getDefaultMaxValue(); } - @Override - public void setDefaultMinValue(KEY_TYPE e) { map.setDefaultMinValue(e); } - @Override - public KEY_TYPE getDefaultMinValue() { return map.getDefaultMinValue(); } -#endif - protected boolean isNullComparator() { return map.comparator() == null; } - - @Override - public ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE setDefaultReturnValue(VALUE_TYPE v) { - map.setDefaultReturnValue(v); - return this; - } - - @Override - public VALUE_TYPE getDefaultReturnValue() { return map.getDefaultReturnValue(); } - - @Override - public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { - if(values == null) values = new SubMapValues(); - return values; - } - - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE descendingKeySet() { - return descendingMap().navigableKeySet(); - } - - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE keySet() { - return navigableKeySet(); - } - - protected abstract Node KEY_VALUE_GENERIC_TYPE subLowest(); - protected abstract Node KEY_VALUE_GENERIC_TYPE subHighest(); - protected abstract Node KEY_VALUE_GENERIC_TYPE subCeiling(KEY_TYPE key); - protected abstract Node KEY_VALUE_GENERIC_TYPE subHigher(KEY_TYPE key); - protected abstract Node KEY_VALUE_GENERIC_TYPE subFloor(KEY_TYPE key); - protected abstract Node KEY_VALUE_GENERIC_TYPE subLower(KEY_TYPE key); - protected abstract BI_ITERATOR KEY_GENERIC_TYPE keyIterator(); - protected abstract BI_ITERATOR KEY_GENERIC_TYPE keyIterator(KEY_TYPE element); - protected abstract VALUE_BI_ITERATOR VALUE_GENERIC_TYPE valueIterator(); - protected abstract BI_ITERATOR KEY_GENERIC_TYPE descendingKeyIterator(); - protected KEY_TYPE lowKeyOrNull(Node KEY_VALUE_GENERIC_TYPE entry) { return entry == null ? getDefaultMinValue() : entry.key; } - protected KEY_TYPE highKeyOrNull(Node KEY_VALUE_GENERIC_TYPE entry) { return entry == null ? getDefaultMaxValue() : entry.key; } - protected Node KEY_VALUE_GENERIC_TYPE next(Node KEY_VALUE_GENERIC_TYPE entry) { return entry.next(); } - protected Node KEY_VALUE_GENERIC_TYPE previous(Node KEY_VALUE_GENERIC_TYPE entry) { return entry.previous(); } - - protected boolean tooLow(KEY_TYPE key) { - if (!fromStart) { - int c = map.compare(key, lo); - if (c < 0 || (c == 0 && !loInclusive)) return true; - } - return false; - } - - protected boolean tooHigh(KEY_TYPE key) { - if (!toEnd) { - int c = map.compare(key, hi); - if (c > 0 || (c == 0 && !hiInclusive)) return true; - } - return false; - } - protected boolean inRange(KEY_TYPE key) { return !tooLow(key) && !tooHigh(key); } - protected boolean inClosedRange(KEY_TYPE key) { return (fromStart || map.compare(key, lo) >= 0) && (toEnd || map.compare(hi, key) >= 0); } - protected boolean inRange(KEY_TYPE key, boolean inclusive) { return inclusive ? inRange(key) : inClosedRange(key); } - - protected Node KEY_VALUE_GENERIC_TYPE absLowest() { - Node KEY_VALUE_GENERIC_TYPE e = (fromStart ? map.first : (loInclusive ? map.findCeilingNode(lo) : map.findHigherNode(lo))); - return (e == null || tooHigh(e.key)) ? null : e; - } - - protected Node KEY_VALUE_GENERIC_TYPE absHighest() { - Node KEY_VALUE_GENERIC_TYPE e = (toEnd ? map.last : (hiInclusive ? map.findFloorNode(hi) : map.findLowerNode(hi))); - return (e == null || tooLow(e.key)) ? null : e; - } - - protected Node KEY_VALUE_GENERIC_TYPE absCeiling(KEY_TYPE key) { - if (tooLow(key)) return absLowest(); - Node KEY_VALUE_GENERIC_TYPE e = map.findCeilingNode(key); - return (e == null || tooHigh(e.key)) ? null : e; - } - - protected Node KEY_VALUE_GENERIC_TYPE absHigher(KEY_TYPE key) { - if (tooLow(key)) return absLowest(); - Node KEY_VALUE_GENERIC_TYPE e = map.findHigherNode(key); - return (e == null || tooHigh(e.key)) ? null : e; - } - - protected Node KEY_VALUE_GENERIC_TYPE absFloor(KEY_TYPE key) { - if (tooHigh(key)) return absHighest(); - Node KEY_VALUE_GENERIC_TYPE e = map.findFloorNode(key); - return (e == null || tooLow(e.key)) ? null : e; - } - - protected Node KEY_VALUE_GENERIC_TYPE absLower(KEY_TYPE key) { - if (tooHigh(key)) return absHighest(); - Node KEY_VALUE_GENERIC_TYPE e = map.findLowerNode(key); - return (e == null || tooLow(e.key)) ? null : e; - } - - protected Node KEY_VALUE_GENERIC_TYPE absHighFence() { return (toEnd ? null : (hiInclusive ? map.findHigherNode(hi) : map.findCeilingNode(hi))); } - protected Node KEY_VALUE_GENERIC_TYPE absLowFence() { return (fromStart ? null : (loInclusive ? map.findLowerNode(lo) : map.findFloorNode(lo))); } - - @Override - public COMPARATOR KEY_GENERIC_TYPE comparator() { return map.comparator(); } - - @Override - public KEY_TYPE POLL_FIRST_ENTRY_KEY() { - Node KEY_VALUE_GENERIC_TYPE entry = subLowest(); - if(entry != null) { - KEY_TYPE result = entry.key; - map.removeNode(entry); - return result; - } - return getDefaultMinValue(); - } - - @Override - public KEY_TYPE POLL_LAST_ENTRY_KEY() { - Node KEY_VALUE_GENERIC_TYPE entry = subHighest(); - if(entry != null) { - KEY_TYPE result = entry.key; - map.removeNode(entry); - return result; - } - return getDefaultMaxValue(); - } - - @Override - public VALUE_TYPE FIRST_ENTRY_VALUE() { - Node KEY_VALUE_GENERIC_TYPE entry = subLowest(); - if(entry == null) throw new NoSuchElementException(); - return entry.value; - } - - @Override - public VALUE_TYPE LAST_ENTRY_VALUE() { - Node KEY_VALUE_GENERIC_TYPE entry = subHighest(); - if(entry == null) throw new NoSuchElementException(); - return entry.value; - } - - @Override - public KEY_TYPE FIRST_ENTRY_KEY() { - Node KEY_VALUE_GENERIC_TYPE entry = subLowest(); - if(entry == null) throw new NoSuchElementException(); - return entry.key; - } - - @Override - public KEY_TYPE LAST_ENTRY_KEY() { - Node KEY_VALUE_GENERIC_TYPE entry = subHighest(); - if(entry == null) throw new NoSuchElementException(); - return entry.key; - } - - @Override - public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { - if (!inRange(key)) throw new IllegalArgumentException("key out of range"); - return map.put(key, value); - } - - @Override - public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { - if (!inRange(key)) throw new IllegalArgumentException("key out of range"); - return map.putIfAbsent(key, value); - } - -#if VALUE_PRIMITIVES - @Override - public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { - if(!inRange(key)) throw new IllegalArgumentException("key out of range"); - return map.addTo(key, value); - } - - @Override - public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { - if(!inRange(key)) throw new IllegalArgumentException("key out of range"); - return map.subFrom(key, value); - } - -#endif -#if TYPE_OBJECT - @Override - public boolean containsKey(Object key) { return inRange((CLASS_TYPE)key) && map.containsKey(key); } -#else - @Override - public boolean containsKey(KEY_TYPE key) { return inRange(key) && map.containsKey(key); } - -#endif - @Override - public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); -#if TYPE_OBJECT - map.validate(key); -#endif - if(!inRange(key)) return getDefaultReturnValue(); - Node KEY_VALUE_GENERIC_TYPE entry = map.findNode(key); - if(entry == null || VALUE_EQUALS(entry.value, getDefaultReturnValue())) return getDefaultReturnValue(); - VALUE_TYPE newValue = mappingFunction.apply(key, entry.value); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - map.removeNode(entry); - return newValue; - } - entry.value = newValue; - return newValue; - } - - @Override - public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { - return inRange(key) ? map.REMOVE_VALUE(key) : getDefaultReturnValue(); - } - - @Override - public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { - return inRange(key) ? map.REMOVE_VALUEOrDefault(key, defaultValue) : defaultValue; - } - -#if TYPE_OBJECT && VALUE_OBJECT - @Override - public boolean remove(Object key, Object value) { - return inRange((CLASS_TYPE)key) && map.remove(key, value); - } - -#else - @Override - public boolean remove(KEY_TYPE key, VALUE_TYPE value) { - return inRange(key) && map.remove(key, value); - } - -#endif - - @Override - public VALUE_TYPE GET_VALUE(KEY_TYPE key) { - return inRange(key) ? map.GET_VALUE(key) : getDefaultReturnValue(); - } - -#if TYPE_OBJECT && VALUE_OBJECT - @Override - public VALUE_TYPE getOrDefault(Object key, VALUE_TYPE defaultValue) { - return inRange((CLASS_TYPE)key) ? map.getOrDefault(key, defaultValue) : getDefaultReturnValue(); - } - -#else - @Override - public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { - return inRange(key) ? map.getOrDefault(key, defaultValue) : getDefaultReturnValue(); - } - -#endif - - @Override - public KEY_TYPE lowerKey(KEY_TYPE key) { return lowKeyOrNull(subLower(key)); } - @Override - public KEY_TYPE floorKey(KEY_TYPE key) { return lowKeyOrNull(subFloor(key)); } - @Override - public KEY_TYPE ceilingKey(KEY_TYPE key) { return highKeyOrNull(subCeiling(key)); } - @Override - public KEY_TYPE higherKey(KEY_TYPE key) { return highKeyOrNull(subHigher(key)); } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE lowerEntry(KEY_TYPE key) { return subLower(key); } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE floorEntry(KEY_TYPE key) { return subFloor(key); } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE ceilingEntry(KEY_TYPE key) { return subCeiling(key); } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE higherEntry(KEY_TYPE key) { return subHigher(key); } - - @Override - public boolean isEmpty() { - if(fromStart && toEnd) return map.isEmpty(); - Node KEY_VALUE_GENERIC_TYPE n = absLowest(); - return n == null || tooHigh(n.key); - } - - @Override - public int size() { return fromStart && toEnd ? map.size() : entrySet().size(); } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE firstEntry() { - Node KEY_VALUE_GENERIC_TYPE entry = subLowest(); - return entry == null ? null : entry.export(); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE lastEntry() { - Node KEY_VALUE_GENERIC_TYPE entry = subHighest(); - return entry == null ? null : entry.export(); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirstEntry() { - Node KEY_VALUE_GENERIC_TYPE entry = subLowest(); - if(entry != null) { - MAP.Entry KEY_VALUE_GENERIC_TYPE result = entry.export(); - map.removeNode(entry); - return result; - } - return null; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLastEntry() { - Node KEY_VALUE_GENERIC_TYPE entry = subHighest(); - if(entry != null) { - MAP.Entry KEY_VALUE_GENERIC_TYPE result = entry.export(); - map.removeNode(entry); - return result; - } - return null; - } - - abstract class SubEntrySet extends AbstractObjectSet { - @Override - public int size() { - if (fromStart && toEnd) return map.size(); - int size = 0; - for(ObjectIterator iter = iterator();iter.hasNext();iter.next(),size++); - return size; - } - - @Override - public boolean isEmpty() { - Node KEY_VALUE_GENERIC_TYPE n = absLowest(); - return n == null || tooHigh(n.key); - } - - @Override - public boolean contains(Object o) { - if (!(o instanceof Map.Entry)) return false; - if(o instanceof MAP.Entry) - { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE) o; -#if TYPE_OBJECT - if(entry.ENTRY_KEY() == null && isNullComparator()) return false; -#endif - KEY_TYPE key = entry.ENTRY_KEY(); - if (!inRange(key)) return false; - Node KEY_VALUE_GENERIC_TYPE node = map.findNode(key); - return node != null && VALUE_EQUALS(entry.ENTRY_VALUE(), node.ENTRY_VALUE()); - } - Map.Entry entry = (Map.Entry) o; - if(entry.getKey() == null && isNullComparator()) return false; - CLASS_TYPE key = (CLASS_TYPE)entry.getKey(); - if (!inRange(key)) return false; - Node KEY_VALUE_GENERIC_TYPE node = map.findNode(key); - return node != null && Objects.equals(entry.getValue(), VALUE_TO_OBJ(node.ENTRY_VALUE())); - } - - @Override - public boolean remove(Object o) { - if (!(o instanceof Map.Entry)) return false; - if(o instanceof MAP.Entry) - { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE) o; - KEY_TYPE key = entry.ENTRY_KEY(); - if (!inRange(key)) return false; - Node KEY_VALUE_GENERIC_TYPE node = map.findNode(key); - if (node != null && VALUE_EQUALS(node.ENTRY_VALUE(), entry.ENTRY_VALUE())) { - map.removeNode(node); - return true; - } - return false; - } - Map.Entry entry = (Map.Entry) o; - CLASS_TYPE key = (CLASS_TYPE)entry.getKey(); - if (!inRange(key)) return false; - Node KEY_VALUE_GENERIC_TYPE node = map.findNode(key); - if (node != null && Objects.equals(node.getValue(), entry.getValue())) { - map.removeNode(node); - return true; - } - return false; - } - - @Override - public void forEach(Consumer action) { - Objects.requireNonNull(action); - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) - action.accept(new BasicEntryKV_BRACES(entry.key, entry.value)); - } - - @Override - public void forEachIndexed(IntObjectConsumer action) { - Objects.requireNonNull(action); - int index = 0; - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) - action.accept(index++, new BasicEntryKV_BRACES(entry.key, entry.value)); - } - - @Override - public void forEach(E input, ObjectObjectConsumer action) { - Objects.requireNonNull(action); - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) - action.accept(input, new BasicEntryKV_BRACES(entry.key, entry.value)); - } - - @Override - public boolean matchesAny(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return false; - BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { - subEntry.set(entry.key, entry.value); - if(filter.test(subEntry)) return true; - } - return false; - } - - @Override - public boolean matchesNone(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { - subEntry.set(entry.key, entry.value); - if(filter.test(subEntry)) return false; - } - return true; - } - - @Override - public boolean matchesAll(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { - subEntry.set(entry.key, entry.value); - if(!filter.test(subEntry)) return false; - } - return true; - } - - @Override - public E reduce(E identity, BiFunction operator) { - Objects.requireNonNull(operator); - E state = identity; - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { - state = operator.apply(state, new BasicEntryKV_BRACES(entry.key, entry.value)); - } - return state; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE reduce(ObjectObjectUnaryOperator operator) { - Objects.requireNonNull(operator); - MAP.Entry KEY_VALUE_GENERIC_TYPE state = null; - boolean empty = true; - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { - if(empty) { - empty = false; - state = new BasicEntryKV_BRACES(entry.key, entry.value); - continue; - } - state = operator.apply(state, new BasicEntryKV_BRACES(entry.key, entry.value)); - } - return state; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE findFirst(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return null; - BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { - subEntry.set(entry.key, entry.value); - if(filter.test(subEntry)) return subEntry; - } - return null; - } - - @Override - public int count(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return 0; - int result = 0; - BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { - subEntry.set(entry.key, entry.value); - if(filter.test(subEntry)) result++; - } - return result; - } - } - - final class SubMapValues extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { - @Override - public boolean add(VALUE_TYPE o) { throw new UnsupportedOperationException(); } - -#if VALUE_OBJECT - @Override - public boolean contains(Object e) { - return containsValue(e); - } - -#else - @Override - public boolean contains(VALUE_TYPE e) { - return containsValue(e); - } - -#endif - @Override - public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() { return valueIterator(); } - - @Override - public int size() { - return NavigableSubMap.this.size(); - } - - @Override - public void clear() { - NavigableSubMap.this.clear(); - } - - @Override - public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) { - Objects.requireNonNull(action); - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) - action.accept(entry.value); - } - - @Override - public void forEachIndexed(VALUE_BI_FROM_INT_CONSUMER VALUE_GENERIC_TYPE action) { - Objects.requireNonNull(action); - int index = 0; - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) - action.accept(index++, entry.value); - } - - @Override - public void forEach(E input, VALUE_BI_FROM_OBJECT_CONSUMER VSV_GENERIC_TYPE action) { - Objects.requireNonNull(action); - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) - action.accept(input, entry.value); - } - - @Override - public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) - if(filter.test(entry.value)) return true; - return false; - } - - @Override - public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) - if(filter.test(entry.value)) return false; - return true; - } - - @Override - public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) - if(!filter.test(entry.value)) return false; - return true; - } - -#if !VALUE_OBJECT - @Override - public VALUE_TYPE reduce(VALUE_TYPE identity, VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - VALUE_TYPE state = identity; - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) - state = operator.APPLY_VALUE(state, entry.value); - return state; - } - -#else - @Override - public VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction operator) { - Objects.requireNonNull(operator); - VALUE_SPECIAL_TYPE state = identity; - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) - state = operator.apply(state, entry.value); - return state; - } - -#endif - @Override - public VALUE_TYPE reduce(VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - VALUE_TYPE state = EMPTY_VALUE; - boolean empty = true; - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { - if(empty) { - empty = false; - state = entry.value; - continue; - } - state = operator.APPLY_VALUE(state, entry.value); - } - return state; - } - - @Override - public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) - if(filter.test(entry.value)) return entry.value; - return EMPTY_VALUE; - } - - @Override - public int count(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - int result = 0; - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) - if(filter.test(entry.value)) result++; - return result; - } - } - - class DecsendingSubEntryIterator extends SubMapEntryIterator implements ObjectBidirectionalIterator - { - public DecsendingSubEntryIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence) { - super(first, forwardFence, backwardFence, false); - } - - @Override - protected Node KEY_VALUE_GENERIC_TYPE moveNext(Node KEY_VALUE_GENERIC_TYPE node) { - return node.previous(); - } - - @Override - protected Node KEY_VALUE_GENERIC_TYPE movePrevious(Node KEY_VALUE_GENERIC_TYPE node) { - return node.next(); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { - if(!hasPrevious()) throw new NoSuchElementException(); - return previousEntry(); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { - if(!hasNext()) throw new NoSuchElementException(); - return nextEntry(); - } - } - - class AcsendingSubEntryIterator extends SubMapEntryIterator implements ObjectBidirectionalIterator - { - public AcsendingSubEntryIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence) { - super(first, forwardFence, backwardFence, true); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { - if(!hasPrevious()) throw new NoSuchElementException(); - return previousEntry(); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { - if(!hasNext()) throw new NoSuchElementException(); - return nextEntry(); - } - } - - class DecsendingSubKeyIterator extends SubMapEntryIterator implements BI_ITERATOR KEY_GENERIC_TYPE - { - public DecsendingSubKeyIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence) { - super(first, forwardFence, backwardFence, false); - } - - @Override - protected Node KEY_VALUE_GENERIC_TYPE moveNext(Node KEY_VALUE_GENERIC_TYPE node) { - return node.previous(); - } - - @Override - protected Node KEY_VALUE_GENERIC_TYPE movePrevious(Node KEY_VALUE_GENERIC_TYPE node) { - return node.next(); - } - - @Override - public KEY_TYPE PREVIOUS() { - if(!hasPrevious()) throw new NoSuchElementException(); - return previousEntry().key; - } - - @Override - public KEY_TYPE NEXT() { - if(!hasNext()) throw new NoSuchElementException(); - return nextEntry().key; - } - } - - class AcsendingSubKeyIterator extends SubMapEntryIterator implements BI_ITERATOR KEY_GENERIC_TYPE - { - public AcsendingSubKeyIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence) { - super(first, forwardFence, backwardFence, true); - } - - @Override - public KEY_TYPE PREVIOUS() { - if(!hasPrevious()) throw new NoSuchElementException(); - return previousEntry().key; - } - - @Override - public KEY_TYPE NEXT() { - if(!hasNext()) throw new NoSuchElementException(); - return nextEntry().key; - } - } - - class AcsendingSubValueIterator extends SubMapEntryIterator implements VALUE_BI_ITERATOR VALUE_GENERIC_TYPE - { - public AcsendingSubValueIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence) { - super(first, forwardFence, backwardFence, true); - } - - @Override - public VALUE_TYPE VALUE_PREVIOUS() { - if(!hasPrevious()) throw new NoSuchElementException(); - return previousEntry().value; - } - - @Override - public VALUE_TYPE VALUE_NEXT() { - if(!hasNext()) throw new NoSuchElementException(); - return nextEntry().value; - } - } - - class DecsendingSubValueIterator extends SubMapEntryIterator implements VALUE_BI_ITERATOR VALUE_GENERIC_TYPE - { - public DecsendingSubValueIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence) { - super(first, forwardFence, backwardFence, false); - } - - @Override - protected Node KEY_VALUE_GENERIC_TYPE moveNext(Node KEY_VALUE_GENERIC_TYPE node) { - return node.previous(); - } - - @Override - protected Node KEY_VALUE_GENERIC_TYPE movePrevious(Node KEY_VALUE_GENERIC_TYPE node) { - return node.next(); - } - - @Override - public VALUE_TYPE VALUE_PREVIOUS() { - if(!hasPrevious()) throw new NoSuchElementException(); - return previousEntry().value; - } - - @Override - public VALUE_TYPE VALUE_NEXT() { - if(!hasNext()) throw new NoSuchElementException(); - return nextEntry().value; - } - } - - abstract class SubMapEntryIterator - { - final boolean isForward; - boolean wasForward; - Node KEY_VALUE_GENERIC_TYPE lastReturned; - Node KEY_VALUE_GENERIC_TYPE next; - Node KEY_VALUE_GENERIC_TYPE previous; - boolean unboundForwardFence; - boolean unboundBackwardFence; - KEY_TYPE forwardFence; - KEY_TYPE backwardFence; - - public SubMapEntryIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence, boolean isForward) { - next = first; - previous = first == null ? null : movePrevious(first); - this.forwardFence = forwardFence == null ? EMPTY_KEY_VALUE : forwardFence.key; - this.backwardFence = backwardFence == null ? EMPTY_KEY_VALUE : backwardFence.key; - unboundForwardFence = forwardFence == null; - unboundBackwardFence = backwardFence == null; - this.isForward = isForward; - } - - protected Node KEY_VALUE_GENERIC_TYPE moveNext(Node KEY_VALUE_GENERIC_TYPE node) { - return node.next(); - } - - protected Node KEY_VALUE_GENERIC_TYPE movePrevious(Node KEY_VALUE_GENERIC_TYPE node) { - return node.previous(); - } - - public boolean hasNext() { - return next != null && (unboundForwardFence || next.key != forwardFence); - } - - protected Node KEY_VALUE_GENERIC_TYPE nextEntry() { - lastReturned = next; - previous = next; - Node KEY_VALUE_GENERIC_TYPE result = next; - next = moveNext(next); - wasForward = isForward; - return result; - } - - public boolean hasPrevious() { - return previous != null && (unboundBackwardFence || previous.key != backwardFence); - } - - protected Node KEY_VALUE_GENERIC_TYPE previousEntry() { - lastReturned = previous; - next = previous; - Node KEY_VALUE_GENERIC_TYPE result = previous; - previous = movePrevious(previous); - wasForward = !isForward; - return result; - } - - public void remove() { - if(lastReturned == null) throw new IllegalStateException(); - if(next == lastReturned) next = moveNext(next); - if(previous == lastReturned) previous = movePrevious(previous); - if(wasForward && lastReturned.needsSuccessor()) next = lastReturned; - map.removeNode(lastReturned); - lastReturned = null; - } - } - } - - class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE - { - @Override - public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() { - return new AscendingValueIterator(first); - } - - @Override - public boolean add(VALUE_TYPE e) { throw new UnsupportedOperationException(); } - - @Override - public void clear() { - AVL_TREE_MAP.this.clear(); - } - - @Override - public int size() { - return AVL_TREE_MAP.this.size; - } - -#if VALUE_OBJECT - @Override - public boolean contains(Object e) { - return containsValue(e); - } - -#else - @Override - public boolean contains(VALUE_TYPE e) { - return containsValue(e); - } - -#endif - @Override - public boolean remove(Object o) { - for(Node KEY_VALUE_GENERIC_TYPE entry = first; entry != null; entry = entry.next()) { - if(Objects.equals(entry.getValue(), o)) { - removeNode(entry); - return true; - } - } - return false; - } - - @Override - public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) { - Objects.requireNonNull(action); - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - action.accept(entry.value); - } - - @Override - public void forEachIndexed(VALUE_BI_FROM_INT_CONSUMER VALUE_GENERIC_TYPE action) { - Objects.requireNonNull(action); - int index = 0; - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - action.accept(index++, entry.value); - } - - @Override - public void forEach(E input, VALUE_BI_FROM_OBJECT_CONSUMER VSV_GENERIC_TYPE action) { - Objects.requireNonNull(action); - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - action.accept(input, entry.value); - } - - @Override - public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - if(filter.test(entry.value)) return true; - return false; - } - - @Override - public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - if(filter.test(entry.value)) return false; - return true; - } - - @Override - public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - if(!filter.test(entry.value)) return false; - return true; - } - - #if !VALUE_OBJECT - @Override - public VALUE_TYPE reduce(VALUE_TYPE identity, VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - VALUE_TYPE state = identity; - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - state = operator.APPLY_VALUE(state, entry.value); - return state; - } - - #else - @Override - public VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction operator) { - Objects.requireNonNull(operator); - VALUE_SPECIAL_TYPE state = identity; - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - state = operator.apply(state, entry.value); - return state; - } - - #endif - @Override - public VALUE_TYPE reduce(VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - VALUE_TYPE state = EMPTY_VALUE; - boolean empty = true; - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { - if(empty) { - empty = false; - state = entry.value; - continue; - } - state = operator.APPLY_VALUE(state, entry.value); - } - return state; - } - - @Override - public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - if(filter.test(entry.value)) return entry.value; - return EMPTY_VALUE; - } - - @Override - public int count(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - int result = 0; - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - if(filter.test(entry.value)) result++; - return result; - } - } - - class EntrySet extends AbstractObjectSet { - - @Override - public ObjectIterator iterator() { - return new AscendingMapEntryIterator(first); - } - - @Override - public void clear() { - AVL_TREE_MAP.this.clear(); - } - - @Override - public int size() { - return AVL_TREE_MAP.this.size; - } - - @Override - public boolean contains(Object o) { - if (!(o instanceof Map.Entry)) return false; - if(o instanceof MAP.Entry) - { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE) o; -#if TYPE_OBJECT - if(entry.getKey() == null && comparator() == null) return false; -#endif - KEY_TYPE key = entry.ENTRY_KEY(); - Node KEY_VALUE_GENERIC_TYPE node = findNode(key); - return node != null && VALUE_EQUALS(entry.ENTRY_VALUE(), node.ENTRY_VALUE()); - } - Map.Entry entry = (Map.Entry) o; - if(entry.getKey() == null && comparator() == null) return false; -#if !TYPE_OBJECT - if(!(entry.getKey() instanceof CLASS_TYPE)) return false; -#endif - CLASS_TYPE key = (CLASS_TYPE)entry.getKey(); - Node KEY_VALUE_GENERIC_TYPE node = findNode(key); - return node != null && Objects.equals(entry.getValue(), VALUE_TO_OBJ(node.ENTRY_VALUE())); - } - - @Override - public boolean remove(Object o) { - if (!(o instanceof Map.Entry)) return false; - if(o instanceof MAP.Entry) - { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE) o; - KEY_TYPE key = entry.ENTRY_KEY(); - Node KEY_VALUE_GENERIC_TYPE node = findNode(key); - if (node != null && VALUE_EQUALS(entry.ENTRY_VALUE(), node.ENTRY_VALUE())) { - removeNode(node); - return true; - } - return false; - } - Map.Entry entry = (Map.Entry) o; - CLASS_TYPE key = (CLASS_TYPE)entry.getKey(); - Node KEY_VALUE_GENERIC_TYPE node = findNode(key); - if (node != null && Objects.equals(entry.getValue(), VALUE_TO_OBJ(node.ENTRY_VALUE()))) { - removeNode(node); - return true; - } - return false; - } - - @Override - public void forEach(Consumer action) { - Objects.requireNonNull(action); - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - action.accept(new BasicEntryKV_BRACES(entry.key, entry.value)); - } - - @Override - public void forEachIndexed(IntObjectConsumer action) { - Objects.requireNonNull(action); - int index = 0; - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - action.accept(index++, new BasicEntryKV_BRACES(entry.key, entry.value)); - } - - @Override - public void forEach(E input, ObjectObjectConsumer action) { - Objects.requireNonNull(action); - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - action.accept(input, new BasicEntryKV_BRACES(entry.key, entry.value)); - } - - @Override - public boolean matchesAny(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return false; - BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { - subEntry.set(entry.key, entry.value); - if(filter.test(subEntry)) return true; - } - return false; - } - - @Override - public boolean matchesNone(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { - subEntry.set(entry.key, entry.value); - if(filter.test(subEntry)) return false; - } - return true; - } - - @Override - public boolean matchesAll(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { - subEntry.set(entry.key, entry.value); - if(!filter.test(subEntry)) return false; - } - return true; - } - - @Override - public E reduce(E identity, BiFunction operator) { - Objects.requireNonNull(operator); - E state = identity; - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { - state = operator.apply(state, new BasicEntryKV_BRACES(entry.key, entry.value)); - } - return state; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE reduce(ObjectObjectUnaryOperator operator) { - Objects.requireNonNull(operator); - MAP.Entry KEY_VALUE_GENERIC_TYPE state = null; - boolean empty = true; - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { - if(empty) { - empty = false; - state = new BasicEntryKV_BRACES(entry.key, entry.value); - continue; - } - state = operator.apply(state, new BasicEntryKV_BRACES(entry.key, entry.value)); - } - return state; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE findFirst(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return null; - BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { - subEntry.set(entry.key, entry.value); - if(filter.test(subEntry)) return subEntry; - } - return null; - } - - @Override - public int count(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return 0; - int result = 0; - BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { - subEntry.set(entry.key, entry.value); - if(filter.test(subEntry)) result++; - } - return result; - } - } - - class DescendingKeyIterator extends MapEntryIterator implements BI_ITERATOR KEY_GENERIC_TYPE - { - public DescendingKeyIterator(Node KEY_VALUE_GENERIC_TYPE first) { - super(first, false); - } - - @Override - protected Node KEY_VALUE_GENERIC_TYPE moveNext(Node KEY_VALUE_GENERIC_TYPE node) { - return node.previous(); - } - - @Override - protected Node KEY_VALUE_GENERIC_TYPE movePrevious(Node KEY_VALUE_GENERIC_TYPE node) { - return node.next(); - } - - @Override - public KEY_TYPE PREVIOUS() { - if(!hasPrevious()) throw new NoSuchElementException(); - return previousEntry().key; - } - - @Override - public KEY_TYPE NEXT() { - if(!hasNext()) throw new NoSuchElementException(); - return nextEntry().key; - } - } - - class AscendingMapEntryIterator extends MapEntryIterator implements ObjectBidirectionalIterator - { - public AscendingMapEntryIterator(Node KEY_VALUE_GENERIC_TYPE first) - { - super(first, true); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { - if(!hasPrevious()) throw new NoSuchElementException(); - return previousEntry(); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { - if(!hasNext()) throw new NoSuchElementException(); - return nextEntry(); - } - } - - class AscendingValueIterator extends MapEntryIterator implements VALUE_BI_ITERATOR VALUE_GENERIC_TYPE - { - public AscendingValueIterator(Node KEY_VALUE_GENERIC_TYPE first) { - super(first, true); - } - - @Override - public VALUE_TYPE VALUE_PREVIOUS() { - if(!hasPrevious()) throw new NoSuchElementException(); - return previousEntry().value; - } - - @Override - public VALUE_TYPE VALUE_NEXT() { - if(!hasNext()) throw new NoSuchElementException(); - return nextEntry().value; - } - } - - class AscendingKeyIterator extends MapEntryIterator implements BI_ITERATOR KEY_GENERIC_TYPE - { - public AscendingKeyIterator(Node KEY_VALUE_GENERIC_TYPE first) { - super(first, true); - } - - @Override - public KEY_TYPE PREVIOUS() { - if(!hasPrevious()) throw new NoSuchElementException(); - return previousEntry().key; - } - - @Override - public KEY_TYPE NEXT() { - if(!hasNext()) throw new NoSuchElementException(); - return nextEntry().key; - } - } - - abstract class MapEntryIterator - { - final boolean isForward; - boolean wasMoved = false; - Node KEY_VALUE_GENERIC_TYPE lastReturned; - Node KEY_VALUE_GENERIC_TYPE next; - Node KEY_VALUE_GENERIC_TYPE previous; - - public MapEntryIterator(Node KEY_VALUE_GENERIC_TYPE first, boolean isForward) { - next = first; - previous = first == null ? null : movePrevious(first); - this.isForward = isForward; - } - - protected Node KEY_VALUE_GENERIC_TYPE moveNext(Node KEY_VALUE_GENERIC_TYPE node) { - return node.next(); - } - - protected Node KEY_VALUE_GENERIC_TYPE movePrevious(Node KEY_VALUE_GENERIC_TYPE node) { - return node.previous(); - } - - public boolean hasNext() { - return next != null; - } - - protected Node KEY_VALUE_GENERIC_TYPE nextEntry() { - lastReturned = next; - previous = next; - Node KEY_VALUE_GENERIC_TYPE result = next; - next = moveNext(next); - wasMoved = isForward; - return result; - } - - public boolean hasPrevious() { - return previous != null; - } - - protected Node KEY_VALUE_GENERIC_TYPE previousEntry() { - lastReturned = previous; - next = previous; - Node KEY_VALUE_GENERIC_TYPE result = previous; - previous = movePrevious(previous); - wasMoved = !isForward; - return result; - } - - public void remove() { - if(lastReturned == null) throw new IllegalStateException(); - if(next == lastReturned) next = moveNext(next); - if(previous == lastReturned) previous = movePrevious(previous); - if(wasMoved && lastReturned.needsSuccessor()) next = lastReturned; - removeNode(lastReturned); - lastReturned = null; - } - } - - private static final class Node KEY_VALUE_GENERIC_TYPE implements MAP.Entry KEY_VALUE_GENERIC_TYPE - { - KEY_TYPE key; - VALUE_TYPE value; - int state; - Node KEY_VALUE_GENERIC_TYPE parent; - Node KEY_VALUE_GENERIC_TYPE left; - Node KEY_VALUE_GENERIC_TYPE right; - - Node(KEY_TYPE key, VALUE_TYPE value, Node KEY_VALUE_GENERIC_TYPE parent) { - this.key = key; - this.value = value; - this.parent = parent; - } - - Node KEY_VALUE_GENERIC_TYPE copy() { - Node KEY_VALUE_GENERIC_TYPE entry = new NodeKV_BRACES(key, value, null); - entry.state = state; - if(left != null) { - Node KEY_VALUE_GENERIC_TYPE newLeft = left.copy(); - entry.left = newLeft; - newLeft.parent = entry; - } - if(right != null) { - Node KEY_VALUE_GENERIC_TYPE newRight = right.copy(); - entry.right = newRight; - newRight.parent = entry; - } - return entry; - } - - public BasicEntry KEY_VALUE_GENERIC_TYPE export() { - return new BasicEntryKV_BRACES(key, value); - } - - @Override - public KEY_TYPE ENTRY_KEY() { - return key; - } - - @Override - public VALUE_TYPE ENTRY_VALUE() { - return value; - } - - @Override - public VALUE_TYPE setValue(VALUE_TYPE value) { - VALUE_TYPE oldValue = this.value; - this.value = value; - return oldValue; - } - -#if VALUE_PRIMITIVES - VALUE_TYPE addTo(VALUE_TYPE value) { - VALUE_TYPE oldValue = this.value; - this.value += value; - return oldValue; - } - - VALUE_TYPE subFrom(VALUE_TYPE value) { - VALUE_TYPE oldValue = this.value; - this.value -= value; - return oldValue; - } -#endif - @Override - public boolean equals(Object obj) { - if(obj instanceof Map.Entry) { - if(obj instanceof MAP.Entry) { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)obj; -#if TYPE_OBJECT - if(entry.ENTRY_KEY() == null) return false; -#endif - return KEY_EQUALS(key, entry.ENTRY_KEY()) && VALUE_EQUALS(value, entry.ENTRY_VALUE()); - } - Map.Entry entry = (Map.Entry)obj; - Object otherKey = entry.getKey(); - if(otherKey == null) return false; - Object otherValue = entry.getValue(); -#if TYPE_OBJECT && VALUE_OBJECT - return KEY_EQUALS(key, otherKey) && VALUE_EQUALS(value, otherValue); -#else if TYPE_OBJECT - return otherValue instanceof CLASS_VALUE_TYPE && KEY_EQUALS(key, otherKey) && VALUE_EQUALS(value, CLASS_TO_VALUE(otherValue)); -#else if VALUE_OBJECT - return otherKey instanceof CLASS_TYPE && KEY_EQUALS(key, CLASS_TO_KEY(otherKey)) && VALUE_EQUALS(value, otherValue); -#else - return otherKey instanceof CLASS_TYPE && otherValue instanceof CLASS_VALUE_TYPE && KEY_EQUALS(key, CLASS_TO_KEY(otherKey)) && VALUE_EQUALS(value, CLASS_TO_VALUE(otherValue)); -#endif - } - return false; - } - - @Override - public int hashCode() { - return KEY_TO_HASH(key) ^ VALUE_TO_HASH(value); - } - - @Override - public String toString() { - return KEY_TO_STRING(key) + "=" + VALUE_TO_STRING(value); - } - - int getHeight() { return state; } - - void updateHeight() { state = (1 + Math.max(left == null ? -1 : left.getHeight(), right == null ? -1 : right.getHeight())); } - - int getBalance() { return (left == null ? -1 : left.getHeight()) - (right == null ? -1 : right.getHeight()); } - - boolean needsSuccessor() { return left != null && right != null; } - - boolean replace(Node KEY_VALUE_GENERIC_TYPE entry) { - if(entry != null) entry.parent = parent; - if(parent != null) { - if(parent.left == this) parent.left = entry; - else parent.right = entry; - } - return parent == null; - } - - Node KEY_VALUE_GENERIC_TYPE next() { - if(right != null) { - Node KEY_VALUE_GENERIC_TYPE parent = right; - while(parent.left != null) parent = parent.left; - return parent; - } - Node KEY_VALUE_GENERIC_TYPE parent = this.parent; - Node KEY_VALUE_GENERIC_TYPE control = this; - while(parent != null && control == parent.right) { - control = parent; - parent = parent.parent; - } - return parent; - } - - Node KEY_VALUE_GENERIC_TYPE previous() { - if(left != null) { - Node KEY_VALUE_GENERIC_TYPE parent = left; - while(parent.right != null) parent = parent.right; - return parent; - } - Node KEY_VALUE_GENERIC_TYPE parent = this.parent; - Node KEY_VALUE_GENERIC_TYPE control = this; - while(parent != null && control == parent.left) { - control = parent; - parent = parent.parent; - } - return parent; - } - } +package speiger.src.collections.PACKAGE.maps.impl.tree; + +import java.util.Collections; +import java.util.Map; +#if TYPE_OBJECT +import java.util.Comparator; +#endif +import java.util.Objects; +import java.util.NoSuchElementException; +import java.util.function.Consumer; +import java.util.function.BiFunction; +import java.util.function.Predicate; +#if !TYPE_OBJECT && JDK_TYPE +import java.util.function.PREDICATE; +#endif +#if !SAME_TYPE && JDK_VALUE && !VALUE_OBJECT +import java.util.function.VALUE_PREDICATE; +#endif + + +import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.functions.COMPARATOR; +import speiger.src.collections.PACKAGE.functions.CONSUMER; +import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; +#endif +import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER; +#if !TYPE_OBJECT && !VALUE_OBJECT +import speiger.src.collections.ints.functions.consumer.IntObjectConsumer; +#endif +#if !SAME_TYPE && !TYPE_INT +import speiger.src.collections.ints.functions.consumer.VALUE_BI_FROM_INT_CONSUMER; +#endif +#if !VALUE_BOOLEAN || !JDK_TYPE +import speiger.src.collections.PACKAGE.functions.function.FUNCTION; +#endif +#if !TYPE_INT || !SAME_TYPE +import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; +#endif +#if !TYPE_OBJECT && !VALUE_BOOLEAN && !JDK_TYPE +import speiger.src.collections.PACKAGE.functions.function.PREDICATE; +#endif +import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; +#if !SAME_TYPE +import speiger.src.collections.PACKAGE.functions.function.SINGLE_UNARY_OPERATOR; +#endif +import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.NAVIGABLE_MAP; +import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET; +import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET; +#if TYPE_OBJECT +import speiger.src.collections.PACKAGE.sets.SET; +#endif +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; +import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_SUPPLIER; +#if !SAME_TYPE +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_BI_ITERATOR; +import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR; +#endif +#if !VALUE_OBJECT && !SAME_TYPE +import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER; +#endif +#if !TYPE_OBJECT && !VALUE_OBJECT || !VALUE_OBJECT +import speiger.src.collections.objects.functions.consumer.ObjectObjectConsumer; +#endif +#if !SAME_TYPE +#if !TYPE_OBJECT +import speiger.src.collections.objects.functions.consumer.VALUE_BI_FROM_OBJECT_CONSUMER; + +#endif +#if !JDK_VALUE +import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE; +#endif +#endif +#if !TYPE_OBJECT && !VALUE_OBJECT +import speiger.src.collections.objects.collections.ObjectBidirectionalIterator; +#endif +#if !VALUE_OBJECT +import speiger.src.collections.objects.collections.ObjectIterator; +#endif +#if !TYPE_OBJECT +#if !VALUE_OBJECT +import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator; + +#endif +import speiger.src.collections.objects.sets.AbstractObjectSet; +import speiger.src.collections.objects.sets.ObjectSet; +#endif + +/** + * A Simple Type Specific AVL TreeMap implementation that reduces boxing/unboxing. + * It is using a bit more memory then FastUtil, + * but it saves a lot of Performance on the Optimized removal and iteration logic. + * Which makes the implementation actually useable and does not get outperformed by Javas default implementation. + * @Type(T) + * @ValueType(V) + */ +public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE +{ + /** The center of the Tree */ + protected transient Node KEY_VALUE_GENERIC_TYPE tree; + /** The Lowest possible Node */ + protected transient Node KEY_VALUE_GENERIC_TYPE first; + /** The Highest possible Node */ + protected transient Node KEY_VALUE_GENERIC_TYPE last; + /** The amount of elements stored in the Map */ + protected int size = 0; + /** The Sorter of the Tree */ + protected transient COMPARATOR KEY_GENERIC_TYPE comparator; + +#if !TYPE_OBJECT + /** the default return value for max searches */ + protected KEY_TYPE defaultMaxNotFound = CLASS_TYPE.MIN_VALUE; + /** the default return value for min searches */ + protected KEY_TYPE defaultMinNotFound = CLASS_TYPE.MAX_VALUE; +#endif + + /** KeySet Cache */ + protected NAVIGABLE_SET KEY_GENERIC_TYPE keySet; + /** Values Cache */ + protected VALUE_COLLECTION VALUE_GENERIC_TYPE values; + /** EntrySet Cache */ + protected ObjectSet entrySet; + + /** + * Default Constructor + */ + public AVL_TREE_MAP() { + } + + /** + * Constructor that allows to define the sorter + * @param comp the function that decides how the tree is sorted, can be null + */ + public AVL_TREE_MAP(COMPARATOR KEY_GENERIC_TYPE comp) { + comparator = comp; + } + +#if !TYPE_OBJECT || !VALUE_OBJECT + /** + * Helper constructor that allow to create a map from boxed values (it will unbox them) + * @param keys the keys that should be put into the map + * @param values the values that should be put into the map. + * @throws IllegalStateException if the keys and values do not match in lenght + */ + public AVL_TREE_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values) { + this(keys, values, null); + } + + /** + * Helper constructor that has a custom sorter and allow to create a map from boxed values (it will unbox them) + * @param keys the keys that should be put into the map + * @param values the values that should be put into the map. + * @param comp the function that decides how the tree is sorted, can be null + * @throws IllegalStateException if the keys and values do not match in lenght + */ + public AVL_TREE_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, COMPARATOR KEY_GENERIC_TYPE comp) { + comparator = comp; + if(keys.length != values.length) throw new IllegalStateException("Input Arrays are not equal size"); + for(int i = 0,m=keys.length;i map) { + this(map, null); + } + + /** + * A Helper constructor that has a custom sorter and allows to create a Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + * @param comp the function that decides how the tree is sorted, can be null + */ + public AVL_TREE_MAP(Map map, COMPARATOR KEY_GENERIC_TYPE comp) { + comparator = comp; + putAll(map); + } + + /** + * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + */ + public AVL_TREE_MAP(MAP KEY_VALUE_GENERIC_TYPE map) { + this(map, null); + } + + /** + * A Type Specific Helper function that has a custom sorter and allows to create a new Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + * @param comp the function that decides how the tree is sorted, can be null + */ + public AVL_TREE_MAP(MAP KEY_VALUE_GENERIC_TYPE map, COMPARATOR KEY_GENERIC_TYPE comp) { + comparator = comp; + putAll(map); + } + +#if TYPE_OBJECT + /** only used for primitives + * @return null + */ + public KEY_TYPE getDefaultMaxValue() { return null; } + /** only used for primitives + * @return null + */ + public KEY_TYPE getDefaultMinValue() { return null; } + +#else + @Override + public void setDefaultMaxValue(KEY_TYPE value) { defaultMaxNotFound = value; } + @Override + public KEY_TYPE getDefaultMaxValue() { return defaultMaxNotFound; } + @Override + public void setDefaultMinValue(KEY_TYPE value) { defaultMinNotFound = value; } + @Override + public KEY_TYPE getDefaultMinValue() { return defaultMinNotFound; } + +#endif + + @Override + public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { +#if TYPE_OBJECT + validate(key); +#endif + if(tree == null) { + tree = first = last = new NodeKV_BRACES(key, value, null); + size++; + return getDefaultReturnValue(); + } + int compare = 0; + Node KEY_VALUE_GENERIC_TYPE parent = tree; + while(true) { + if((compare = compare(key, parent.key)) == 0) return parent.setValue(value); + if(compare < 0) { + if(parent.left == null) break; + parent = parent.left; + } + else if(compare > 0) { + if(parent.right == null) break; + parent = parent.right; + } + } + Node KEY_VALUE_GENERIC_TYPE adding = new NodeKV_BRACES(key, value, parent); + if(compare < 0) { + parent.left = adding; + if(parent == first) first = adding; + } + else { + parent.right = adding; + if(parent == last) last = adding; + } + fixAfterInsertion(adding); + size++; + return getDefaultReturnValue(); + } + + @Override + public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { +#if TYPE_OBJECT + validate(key); +#endif + if(tree == null) { + tree = first = last = new NodeKV_BRACES(key, value, null); + size++; + return getDefaultReturnValue(); + } + int compare = 0; + Node KEY_VALUE_GENERIC_TYPE parent = tree; + while(true) { + if((compare = compare(key, parent.key)) == 0) { + if(VALUE_EQUALS(parent.value, getDefaultReturnValue())) return parent.setValue(value); + return parent.value; + } + if(compare < 0) { + if(parent.left == null) break; + parent = parent.left; + } + else if(compare > 0) { + if(parent.right == null) break; + parent = parent.right; + } + } + Node KEY_VALUE_GENERIC_TYPE adding = new NodeKV_BRACES(key, value, parent); + if(compare < 0) { + parent.left = adding; + if(parent == first) first = adding; + } + else { + parent.right = adding; + if(parent == last) last = adding; + } + fixAfterInsertion(adding); + size++; + return getDefaultReturnValue(); + } + +#if VALUE_PRIMITIVES + @Override + public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { + if(tree == null) { + tree = first = last = new NodeKV_BRACES(key, value, null); + size++; + return getDefaultReturnValue(); + } + int compare = 0; + Node KEY_VALUE_GENERIC_TYPE parent = tree; + while(true) { + if((compare = compare(key, parent.key)) == 0) return parent.addTo(value); + if(compare < 0) { + if(parent.left == null) break; + parent = parent.left; + } + else if(compare > 0) { + if(parent.right == null) break; + parent = parent.right; + } + } + Node KEY_VALUE_GENERIC_TYPE adding = new NodeKV_BRACES(key, value, parent); + if(compare < 0) { + parent.left = adding; + if(parent == first) first = adding; + } + else { + parent.right = adding; + if(parent == last) last = adding; + } + fixAfterInsertion(adding); + size++; + return getDefaultReturnValue(); + } + + @Override + public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { + if(tree == null) return getDefaultReturnValue(); + int compare = 0; + Node KEY_VALUE_GENERIC_TYPE parent = tree; + while(true) { + if((compare = compare(key, parent.key)) == 0) + { + VALUE_TYPE oldValue = parent.subFrom(value); + if(value < 0 ? (parent.value >= getDefaultReturnValue()) : (parent.value <= getDefaultReturnValue())) removeNode(parent); + return oldValue; + } + if(compare < 0) { + if(parent.left == null) break; + parent = parent.left; + } + else if(compare > 0) { + if(parent.right == null) break; + parent = parent.right; + } + } + return getDefaultReturnValue(); + } + +#endif + @Override + public COMPARATOR KEY_GENERIC_TYPE comparator() { return comparator; } + +#if TYPE_OBJECT + @Override + public boolean containsKey(Object key) { + return findNode((KEY_TYPE)key) != null; + } + +#else + @Override + public boolean containsKey(KEY_TYPE key) { + return findNode(key) != null; + } + +#endif + @Override + public VALUE_TYPE GET_VALUE(KEY_TYPE key) { + Node KEY_VALUE_GENERIC_TYPE node = findNode(key); + return node == null ? getDefaultReturnValue() : node.value; + } + +#if TYPE_OBJECT && VALUE_OBJECT + @Override + public VALUE_TYPE getOrDefault(Object key, VALUE_TYPE defaultValue) { + Node KEY_VALUE_GENERIC_TYPE node = findNode((CLASS_TYPE)key); + return node == null ? defaultValue : node.value; + } + +#else + @Override + public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { + Node KEY_VALUE_GENERIC_TYPE node = findNode(key); + return node == null ? defaultValue : node.value; + } + +#endif + @Override + public KEY_TYPE FIRST_ENTRY_KEY() { + if(tree == null) throw new NoSuchElementException(); + return first.key; + } + + @Override + public KEY_TYPE POLL_FIRST_ENTRY_KEY() { + if(tree == null) return getDefaultMinValue(); + KEY_TYPE result = first.key; + removeNode(first); + return result; + } + + @Override + public KEY_TYPE LAST_ENTRY_KEY() { + if(tree == null) throw new NoSuchElementException(); + return last.key; + } + + @Override + public KEY_TYPE POLL_LAST_ENTRY_KEY() { + if(tree == null) return getDefaultMaxValue(); + KEY_TYPE result = last.key; + removeNode(last); + return result; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE firstEntry() { + if(tree == null) return null; + return first.export(); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE lastEntry() { + if(tree == null) return null; + return last.export(); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirstEntry() { + if(tree == null) return null; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = first.export(); + removeNode(first); + return entry; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLastEntry() { + if(tree == null) return null; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = last.export(); + removeNode(last); + return entry; + } + + @Override + public VALUE_TYPE FIRST_ENTRY_VALUE() { + if(tree == null) throw new NoSuchElementException(); + return first.value; + } + + @Override + public VALUE_TYPE LAST_ENTRY_VALUE() { + if(tree == null) throw new NoSuchElementException(); + return last.value; + } + + @Override + public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { + Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); + if(entry == null) return getDefaultReturnValue(); + VALUE_TYPE value = entry.value; + removeNode(entry); + return value; + } + + @Override + public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { + Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); + if(entry == null) return defaultValue; + VALUE_TYPE value = entry.value; + removeNode(entry); + return value; + } + +#if TYPE_OBJECT && VALUE_OBJECT + @Override + public boolean remove(Object key, Object value) { + Node KEY_VALUE_GENERIC_TYPE entry = findNode((CLASS_TYPE)key); + if(entry == null || !Objects.equals(value, entry.value)) return false; + removeNode(entry); + return true; + } + +#else + @Override + public boolean remove(KEY_TYPE key, VALUE_TYPE value) { + Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); + if(entry == null || entry.value != value) return false; + removeNode(entry); + return true; + } + +#endif + @Override + public boolean replace(KEY_TYPE key, VALUE_TYPE oldValue, VALUE_TYPE newValue) { + Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); + if(entry == null || entry.value != oldValue) return false; + entry.value = newValue; + return true; + } + + @Override + public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value) { + Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); + if(entry == null) return getDefaultReturnValue(); + VALUE_TYPE oldValue = entry.value; + entry.value = value; + return oldValue; + } + + @Override + public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); +#if TYPE_OBJECT + validate(key); +#endif + Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); + if(entry == null) { + VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, getDefaultReturnValue()); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + put(key, newValue); + return newValue; + } + VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, entry.value); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + removeNode(entry); + return newValue; + } + entry.value = newValue; + return newValue; + } + + @Override + public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); +#if TYPE_OBJECT + validate(key); +#endif + Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); + if(entry == null) { + VALUE_TYPE newValue = mappingFunction.APPLY(key); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + put(key, newValue); + return newValue; + } + if(Objects.equals(entry.value, getDefaultReturnValue())) { + VALUE_TYPE newValue = mappingFunction.APPLY(key); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + entry.value = newValue; + } + return entry.value; + } + + @Override + public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) { + Objects.requireNonNull(valueProvider); +#if TYPE_OBJECT + validate(key); +#endif + Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); + if(entry == null) { + VALUE_TYPE newValue = valueProvider.VALUE_SUPPLY_GET(); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + put(key, newValue); + return newValue; + } + if(VALUE_EQUALS(entry.value, getDefaultReturnValue())) { + VALUE_TYPE newValue = valueProvider.VALUE_SUPPLY_GET(); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + entry.value = newValue; + } + return entry.value; + } + + @Override + public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); +#if TYPE_OBJECT + validate(key); +#endif + Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); + if(entry == null || VALUE_EQUALS(entry.value, getDefaultReturnValue())) return getDefaultReturnValue(); + VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, entry.value); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + removeNode(entry); + return newValue; + } + entry.value = newValue; + return newValue; + } + + @Override + public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); +#if TYPE_OBJECT + validate(key); +#endif + Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); + VALUE_TYPE newValue = entry == null || VALUE_EQUALS(entry.value, getDefaultReturnValue()) ? value : mappingFunction.APPLY_VALUE(entry.value, value); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + if(entry != null) + removeNode(entry); + } + else if(entry == null) put(key, newValue); + else entry.value = newValue; + return newValue; + } + + @Override + public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); + for(MAP.Entry KEY_VALUE_GENERIC_TYPE entry : getFastIterable(m)) { + KEY_TYPE key = entry.ENTRY_KEY(); + Node KEY_VALUE_GENERIC_TYPE subEntry = findNode(key); + VALUE_TYPE newValue = subEntry == null || VALUE_EQUALS(subEntry.value, getDefaultReturnValue()) ? entry.ENTRY_VALUE() : mappingFunction.APPLY_VALUE(subEntry.value, entry.ENTRY_VALUE()); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + if(subEntry != null) + removeNode(subEntry); + } + else if(subEntry == null) put(key, newValue); + else subEntry.value = newValue; + } + } + + @Override + public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + action.accept(entry.key, entry.value); + } + + @Override + public int size() { return size; } + + @Override + public void clear() { + size = 0; + first = null; + last = null; + tree = null; + } + + protected BI_ITERATOR KEY_GENERIC_TYPE keyIterator() { + return new AscendingKeyIterator(first); + } + + protected BI_ITERATOR KEY_GENERIC_TYPE keyIterator(KEY_TYPE element) { + return new AscendingKeyIterator(findNode(element)); + } + + protected BI_ITERATOR KEY_GENERIC_TYPE descendingKeyIterator() { + return new DescendingKeyIterator(last); + } + + @Override + public AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE copy() { + AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE set = new AVL_TREE_MAPKV_BRACES(); + set.size = size; + if(tree != null) { + set.tree = tree.copy(); + Node KEY_VALUE_GENERIC_TYPE lastFound = null; + for(Node KEY_VALUE_GENERIC_TYPE entry = tree;entry != null;entry = entry.left) lastFound = entry; + set.first = lastFound; + lastFound = null; + for(Node KEY_VALUE_GENERIC_TYPE entry = tree;entry != null;entry = entry.right) lastFound = entry; + set.last = lastFound; + } + return set; + } + + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE keySet() { + return navigableKeySet(); + } + + @Override + public ObjectSet ENTRY_SET() { + if(entrySet == null) entrySet = new EntrySet(); + return entrySet; + } + + @Override + public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { + if(values == null) values = new Values(); + return values; + } + + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE navigableKeySet() { + if(keySet == null) keySet = new KeySetKV_BRACES(this); + return keySet; + } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap() { + return new DescendingNaivgableSubMapKV_BRACES(this, true, EMPTY_KEY_VALUE, true, true, EMPTY_KEY_VALUE, true); + } + + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE descendingKeySet() { + return descendingMap().navigableKeySet(); + } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, boolean fromInclusive, KEY_TYPE toKey, boolean toInclusive) { + return new AscendingNaivgableSubMapKV_BRACES(this, false, fromKey, fromInclusive, false, toKey, toInclusive); + } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey, boolean inclusive) { + return new AscendingNaivgableSubMapKV_BRACES(this, true, EMPTY_KEY_VALUE, true, false, toKey, inclusive); + } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey, boolean inclusive) { + return new AscendingNaivgableSubMapKV_BRACES(this, false, fromKey, inclusive, true, EMPTY_KEY_VALUE, true); + } + + @Override + public KEY_TYPE lowerKey(KEY_TYPE e) { + Node KEY_VALUE_GENERIC_TYPE node = findLowerNode(e); + return node != null ? node.key : getDefaultMinValue(); + } + + @Override + public KEY_TYPE floorKey(KEY_TYPE e) { + Node KEY_VALUE_GENERIC_TYPE node = findFloorNode(e); + return node != null ? node.key : getDefaultMinValue(); + } + + @Override + public KEY_TYPE higherKey(KEY_TYPE e) { + Node KEY_VALUE_GENERIC_TYPE node = findHigherNode(e); + return node != null ? node.key : getDefaultMaxValue(); + } + + @Override + public KEY_TYPE ceilingKey(KEY_TYPE e) { + Node KEY_VALUE_GENERIC_TYPE node = findCeilingNode(e); + return node != null ? node.key : getDefaultMaxValue(); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE lowerEntry(KEY_TYPE key) { + Node KEY_VALUE_GENERIC_TYPE node = findLowerNode(key); + return node != null ? node.export() : null; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE higherEntry(KEY_TYPE key) { + Node KEY_VALUE_GENERIC_TYPE node = findHigherNode(key); + return node != null ? node.export() : null; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE floorEntry(KEY_TYPE key) { + Node KEY_VALUE_GENERIC_TYPE node = findFloorNode(key); + return node != null ? node.export() : null; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE ceilingEntry(KEY_TYPE key) { + Node KEY_VALUE_GENERIC_TYPE node = findCeilingNode(key); + return node != null ? node.export() : null; + } + + protected Node KEY_VALUE_GENERIC_TYPE findLowerNode(KEY_TYPE key) { + Node KEY_VALUE_GENERIC_TYPE entry = tree; + while(entry != null) { + if(compare(key, entry.key) > 0) { + if(entry.right != null) entry = entry.right; + else return entry; + } + else { + if(entry.left != null) entry = entry.left; + else { + Node KEY_VALUE_GENERIC_TYPE parent = entry.parent; + while(parent != null && parent.left == entry) { + entry = parent; + parent = parent.parent; + } + return parent; + } + } + } + return null; + } + + protected Node KEY_VALUE_GENERIC_TYPE findFloorNode(KEY_TYPE key) { + Node KEY_VALUE_GENERIC_TYPE entry = tree; + int compare; + while(entry != null) { + if((compare = compare(key, entry.key)) > 0) { + if(entry.right == null) break; + entry = entry.right; + continue; + } + else if(compare < 0) { + if(entry.left != null) entry = entry.left; + else { + Node KEY_VALUE_GENERIC_TYPE parent = entry.parent; + while(parent != null && parent.left == entry) { + entry = parent; + parent = parent.parent; + } + return parent; + } + continue; + } + break; + } + return entry; + } + + protected Node KEY_VALUE_GENERIC_TYPE findCeilingNode(KEY_TYPE key) { + Node KEY_VALUE_GENERIC_TYPE entry = tree; + int compare; + while(entry != null) { + if((compare = compare(key, entry.key)) < 0) { + if(entry.left == null) break; + entry = entry.left; + continue; + } + else if(compare > 0) { + if(entry.right != null) entry = entry.right; + else { + Node KEY_VALUE_GENERIC_TYPE parent = entry.parent; + while(parent != null && parent.right == entry) { + entry = parent; + parent = parent.parent; + } + return parent; + } + continue; + } + break; + } + return entry; + } + + protected Node KEY_VALUE_GENERIC_TYPE findHigherNode(KEY_TYPE key) { + Node KEY_VALUE_GENERIC_TYPE entry = tree; + while(entry != null) { + if(compare(key, entry.key) < 0) { + if(entry.left != null) entry = entry.left; + else return entry; + } + else { + if(entry.right != null) entry = entry.right; + else { + Node KEY_VALUE_GENERIC_TYPE parent = entry.parent; + while(parent != null && parent.right == entry) { + entry = parent; + parent = parent.parent; + } + return parent; + } + } + } + return null; + } + + protected Node KEY_VALUE_GENERIC_TYPE findNode(KEY_TYPE key) { + Node KEY_VALUE_GENERIC_TYPE node = tree; + int compare; + while(node != null) { + if((compare = compare(key, node.key)) == 0) return node; + if(compare < 0) node = node.left; + else node = node.right; + } + return null; + } + + protected void removeNode(Node KEY_VALUE_GENERIC_TYPE entry) { + size--; + if(entry.needsSuccessor()) { + Node KEY_VALUE_GENERIC_TYPE successor = entry.next(); + entry.key = successor.key; + entry.value = successor.value; + entry = successor; + } + if(entry.previous() == null) first = entry.next(); + if(entry.next() == null) last = entry.previous(); + Node KEY_VALUE_GENERIC_TYPE replacement = entry.left != null ? entry.left : entry.right; + if(replacement != null) { + if(entry.replace(replacement)) tree = replacement; + entry.left = entry.right = entry.parent = null; + fixAfterDeletion(replacement); + } + else if(entry.parent == null) tree = first = last = null; + else { + fixAfterDeletion(entry); + entry.replace(null); + entry.parent = null; + } + } + + protected void validate(KEY_TYPE k) { compare(k, k); } + protected int compare(KEY_TYPE k, KEY_TYPE v) { return comparator != null ? comparator.compare(k, v) : COMPAREABLE_TO_KEY(k, v);} + + /** From CLR */ + protected void rotateLeft(Node KEY_VALUE_GENERIC_TYPE entry) { + if(entry != null) { + Node KEY_VALUE_GENERIC_TYPE right = entry.right; + entry.right = right.left; + if(right.left != null) right.left.parent = entry; + right.parent = entry.parent; + if(entry.parent == null) tree = right; + else if(entry.parent.left == entry) entry.parent.left = right; + else entry.parent.right = right; + right.left = entry; + entry.parent = right; + entry.updateHeight(); + right.updateHeight(); + } + } + + /** From CLR */ + protected void rotateRight(Node KEY_VALUE_GENERIC_TYPE entry) { + if(entry != null) { + Node KEY_VALUE_GENERIC_TYPE left = entry.left; + entry.left = left.right; + if(left.right != null) left.right.parent = entry; + left.parent = entry.parent; + if(entry.parent == null) tree = left; + else if(entry.parent.right == entry) entry.parent.right = left; + else entry.parent.left = left; + left.right = entry; + entry.parent = left; + entry.updateHeight(); + left.updateHeight(); + } + } + + /** From CLR */ + protected void fixAfterInsertion(Node KEY_VALUE_GENERIC_TYPE entry) { + while(entry != null) { + entry.updateHeight(); + int balance = entry.getBalance(); + if(balance > 1) { + int compare = entry.left.getBalance(); + if(compare > 0) rotateRight(entry); + else if(compare < 0) { + rotateLeft(entry.left); + rotateRight(entry); + } + } + else if(balance < -1) { + int compare = entry.right.getBalance(); + if(compare < 0) rotateLeft(entry); + else if(compare > 0) { + rotateRight(entry.right); + rotateLeft(entry); + } + } + entry = entry.parent; + } + } + + /** From CLR */ + protected void fixAfterDeletion(Node KEY_VALUE_GENERIC_TYPE entry) { + if(entry != null) { + entry.updateHeight(); + int balance = entry.getBalance(); + if(balance > 1) { + int subBalance = entry.left.getBalance(); + if(subBalance >= 0) rotateRight(entry); + else { + rotateLeft(entry.left); + rotateRight(entry); + } + } + else if(balance < -1) + { + int subBalance = entry.right.getBalance(); + if(subBalance <= 0) rotateLeft(entry); + else { + rotateRight(entry.right); + rotateLeft(entry); + } + } + entry = entry.parent; + } + } + + static class KeySet KEY_VALUE_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE implements NAVIGABLE_SET KEY_GENERIC_TYPE + { + NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map; + + public KeySet(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map) { + this.map = map; + } + +#if !TYPE_OBJECT + @Override + public void setDefaultMaxValue(KEY_TYPE e) { map.setDefaultMaxValue(e); } + @Override + public KEY_TYPE getDefaultMaxValue() { return map.getDefaultMaxValue(); } + @Override + public void setDefaultMinValue(KEY_TYPE e) { map.setDefaultMinValue(e); } + @Override + public KEY_TYPE getDefaultMinValue() { return map.getDefaultMinValue(); } +#endif + @Override + public KEY_TYPE lower(KEY_TYPE e) { return map.lowerKey(e); } + @Override + public KEY_TYPE floor(KEY_TYPE e) { return map.floorKey(e); } + @Override + public KEY_TYPE ceiling(KEY_TYPE e) { return map.ceilingKey(e); } + @Override + public KEY_TYPE higher(KEY_TYPE e) { return map.higherKey(e); } + +#if !TYPE_OBJECT + @Override + public CLASS_TYPE lower(CLASS_TYPE e) { + MAP.Entry KEY_VALUE_GENERIC_TYPE node = map.lowerEntry(OBJ_TO_KEY(e)); + return node != null ? node.getKey() : null; + } + + @Override + public CLASS_TYPE floor(CLASS_TYPE e) { + MAP.Entry KEY_VALUE_GENERIC_TYPE node = map.floorEntry(OBJ_TO_KEY(e)); + return node != null ? node.getKey() : null; + } + + @Override + public CLASS_TYPE higher(CLASS_TYPE e) { + MAP.Entry KEY_VALUE_GENERIC_TYPE node = map.higherEntry(OBJ_TO_KEY(e)); + return node != null ? node.getKey() : null; + } + + @Override + public CLASS_TYPE ceiling(CLASS_TYPE e) { + MAP.Entry KEY_VALUE_GENERIC_TYPE node = map.ceilingEntry(OBJ_TO_KEY(e)); + return node != null ? node.getKey() : null; + } + +#endif + @Override + public KEY_TYPE POLL_FIRST_KEY() { return map.POLL_FIRST_ENTRY_KEY(); } + @Override + public KEY_TYPE POLL_LAST_KEY() { return map.POLL_LAST_ENTRY_KEY(); } + @Override + public COMPARATOR KEY_GENERIC_TYPE comparator() { return map.comparator(); } + @Override + public KEY_TYPE FIRST_KEY() { return map.FIRST_ENTRY_KEY(); } + @Override + public KEY_TYPE LAST_KEY() { return map.LAST_ENTRY_KEY(); } + @Override + public void clear() { map.clear(); } + +#if TYPE_OBJECT + @Override + public boolean remove(Object o) { + int oldSize = map.size(); + map.remove(o); + return oldSize != map.size(); + } + +#else + @Override + public boolean remove(KEY_TYPE o) { + int oldSize = map.size(); + map.remove(o); + return oldSize != map.size(); + } + +#endif + @Override + public boolean add(KEY_TYPE e) { throw new UnsupportedOperationException(); } + + @Override + public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { + if(map instanceof AVL_TREE_MAP) return ((AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE)map).keyIterator(fromElement); + return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).keyIterator(fromElement); + } + + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, boolean fromInclusive, KEY_TYPE toElement, boolean toInclusive) { return new KeySetKV_BRACES(map.subMap(fromElement, fromInclusive, toElement, toInclusive)); } + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement, boolean inclusive) { return new KeySetKV_BRACES(map.headMap(toElement, inclusive)); } + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement, boolean inclusive) { return new KeySetKV_BRACES(map.tailMap(fromElement, inclusive)); } + + @Override + public BI_ITERATOR KEY_GENERIC_TYPE iterator() { + if(map instanceof AVL_TREE_MAP) return ((AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE)map).keyIterator(); + return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).keyIterator(); + } + + @Override + public BI_ITERATOR KEY_GENERIC_TYPE descendingIterator() { + if(map instanceof AVL_TREE_MAP) return ((AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE)map).descendingKeyIterator(); + return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).descendingKeyIterator(); + } + + protected Node KEY_VALUE_GENERIC_TYPE start() { + if(map instanceof AVL_TREE_MAP) return ((AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE)map).first; + return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).subLowest(); + } + + protected Node KEY_VALUE_GENERIC_TYPE end() { + if(map instanceof AVL_TREE_MAP) return null; + return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).subHighest(); + } + + protected Node KEY_VALUE_GENERIC_TYPE next(Node KEY_VALUE_GENERIC_TYPE entry) { + if(map instanceof AVL_TREE_MAP) return entry.next(); + return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).next(entry); + } + + protected Node KEY_VALUE_GENERIC_TYPE previous(Node KEY_VALUE_GENERIC_TYPE entry) { + if(map instanceof AVL_TREE_MAP) return entry.previous(); + return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).previous(entry); + } + + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE descendingSet() { return new KeySetKV_BRACES(map.descendingMap()); } + @Override + public KeySet KEY_VALUE_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); } + @Override + public boolean isEmpty() { return map.isEmpty(); } + @Override + public int size() { return map.size(); } + + @Override + public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { + Objects.requireNonNull(action); + for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) + action.accept(entry.key); + } + + @Override + public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) { + Objects.requireNonNull(action); + int index = 0; + for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) + action.accept(index++, entry.key); + } + + @Override + public void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { + Objects.requireNonNull(action); + for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) + action.accept(input, entry.key); + } + + @Override + public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) + if(filter.test(entry.key)) return true; + return false; + } + + @Override + public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) + if(filter.test(entry.key)) return false; + return true; + } + + @Override + public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) + if(!filter.test(entry.key)) return false; + return true; + } + +#if !TYPE_OBJECT + @Override + public KEY_TYPE reduce(KEY_TYPE identity, SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + KEY_TYPE state = identity; + for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) + state = operator.APPLY_KEY_VALUE(state, entry.key); + return state; + } + +#else + @Override + public KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) { + Objects.requireNonNull(operator); + KEY_SPECIAL_TYPE state = identity; + for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) + state = operator.apply(state, entry.key); + return state; + } + +#endif + @Override + public KEY_TYPE reduce(SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + KEY_TYPE state = EMPTY_KEY_VALUE; + boolean empty = true; + for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) { + if(empty) { + empty = false; + state = entry.key; + continue; + } + state = operator.APPLY_KEY_VALUE(state, entry.key); + } + return state; + } + + @Override + public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) + if(filter.test(entry.key)) return entry.key; + return EMPTY_KEY_VALUE; + } + + @Override + public int count(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + int result = 0; + for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) + if(filter.test(entry.key)) result++; + return result; + } + } + + static class AscendingNaivgableSubMap KEY_VALUE_GENERIC_TYPE extends NavigableSubMap KEY_VALUE_GENERIC_TYPE + { + AscendingNaivgableSubMap(AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE map, boolean fromStart, KEY_TYPE lo, boolean loInclusive, boolean toEnd, KEY_TYPE hi, boolean hiInclusive) { + super(map, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); + } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap() { + if(inverse == null) inverse = new DescendingNaivgableSubMapKV_BRACES(map, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); + return inverse; + } + + @Override + public ObjectSet ENTRY_SET() { + if(entrySet == null) entrySet = new AscendingSubEntrySet(); + return entrySet; + } + + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE navigableKeySet() { + if(keySet == null) keySet = new KeySetKV_BRACES(this); + return keySet; + } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, boolean fromInclusive, KEY_TYPE toKey, boolean toInclusive) { + if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range"); + if (!inRange(toKey, toInclusive)) throw new IllegalArgumentException("toKey out of range"); + return new AscendingNaivgableSubMapKV_BRACES(map, false, fromKey, fromInclusive, false, toKey, toInclusive); + } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey, boolean inclusive) { + if (!inRange(toKey, inclusive)) throw new IllegalArgumentException("toKey out of range"); + return new AscendingNaivgableSubMapKV_BRACES(map, fromStart, lo, loInclusive, false, toKey, inclusive); + } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey, boolean inclusive) { + if (!inRange(fromKey, inclusive)) throw new IllegalArgumentException("fromKey out of range"); + return new AscendingNaivgableSubMapKV_BRACES(map, false, fromKey, inclusive, toEnd, hi, hiInclusive); + } + + @Override + protected Node KEY_VALUE_GENERIC_TYPE subLowest() { return absLowest(); } + @Override + protected Node KEY_VALUE_GENERIC_TYPE subHighest() { return absHighest(); } + @Override + protected Node KEY_VALUE_GENERIC_TYPE subCeiling(KEY_TYPE key) { return absCeiling(key); } + @Override + protected Node KEY_VALUE_GENERIC_TYPE subHigher(KEY_TYPE key) { return absHigher(key); } + @Override + protected Node KEY_VALUE_GENERIC_TYPE subFloor(KEY_TYPE key) { return absFloor(key); } + @Override + protected Node KEY_VALUE_GENERIC_TYPE subLower(KEY_TYPE key) { return absLower(key); } + + @Override + protected BI_ITERATOR KEY_GENERIC_TYPE keyIterator() { + return new AcsendingSubKeyIterator(absLowest(), absHighFence(), absLowFence()); + } + @Override + protected BI_ITERATOR KEY_GENERIC_TYPE keyIterator(KEY_TYPE element) { + return new AcsendingSubKeyIterator(absLower(element), absHighFence(), absLowFence()); + } + + @Override + protected VALUE_BI_ITERATOR VALUE_GENERIC_TYPE valueIterator() { + return new AcsendingSubValueIterator(absLowest(), absHighFence(), absLowFence()); + } + + @Override + protected BI_ITERATOR KEY_GENERIC_TYPE descendingKeyIterator() { + return new DecsendingSubKeyIterator(absHighest(), absLowFence(), absHighFence()); + } + + class AscendingSubEntrySet extends SubEntrySet { + @Override + public ObjectIterator iterator() { + return new AcsendingSubEntryIterator(absLowest(), absHighFence(), absLowFence()); + } + } + } + + static class DescendingNaivgableSubMap KEY_VALUE_GENERIC_TYPE extends NavigableSubMap KEY_VALUE_GENERIC_TYPE + { + COMPARATOR KEY_GENERIC_TYPE comparator; + DescendingNaivgableSubMap(AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE map, boolean fromStart, KEY_TYPE lo, boolean loInclusive, boolean toEnd, KEY_TYPE hi, boolean hiInclusive) { + super(map, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); +#if TYPE_OBJECT + comparator = Collections.reverseOrder(map.comparator()); +#else + comparator = map.comparator() == null ? COMPARATOR.of(Collections.reverseOrder()) : map.comparator().reversed(); +#endif + } + + @Override + public COMPARATOR KEY_GENERIC_TYPE comparator() { return comparator; } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap() { + if(inverse == null) inverse = new AscendingNaivgableSubMapKV_BRACES(map, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); + return inverse; + } + + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE navigableKeySet() { + if(keySet == null) keySet = new KeySetKV_BRACES(this); + return keySet; + } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, boolean fromInclusive, KEY_TYPE toKey, boolean toInclusive) { + if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range"); + if (!inRange(toKey, toInclusive)) throw new IllegalArgumentException("toKey out of range"); + return new DescendingNaivgableSubMapKV_BRACES(map, false, toKey, toInclusive, false, fromKey, fromInclusive); + } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey, boolean inclusive) { + if (!inRange(toKey, inclusive)) throw new IllegalArgumentException("toKey out of range"); + return new DescendingNaivgableSubMapKV_BRACES(map, false, toKey, inclusive, toEnd, hi, hiInclusive); + } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey, boolean inclusive) { + if (!inRange(fromKey, inclusive)) throw new IllegalArgumentException("fromKey out of range"); + return new DescendingNaivgableSubMapKV_BRACES(map, fromStart, lo, loInclusive, false, fromKey, inclusive); + } + + @Override + public ObjectSet ENTRY_SET() { + if(entrySet == null) entrySet = new DescendingSubEntrySet(); + return entrySet; + } + + @Override + protected Node KEY_VALUE_GENERIC_TYPE subLowest() { return absHighest(); } + @Override + protected Node KEY_VALUE_GENERIC_TYPE subHighest() { return absLowest(); } + @Override + protected Node KEY_VALUE_GENERIC_TYPE subCeiling(KEY_TYPE key) { return absFloor(key); } + @Override + protected Node KEY_VALUE_GENERIC_TYPE subHigher(KEY_TYPE key) { return absLower(key); } + @Override + protected Node KEY_VALUE_GENERIC_TYPE subFloor(KEY_TYPE key) { return absCeiling(key); } + @Override + protected Node KEY_VALUE_GENERIC_TYPE subLower(KEY_TYPE key) { return absHigher(key); } + @Override + protected Node KEY_VALUE_GENERIC_TYPE next(Node KEY_VALUE_GENERIC_TYPE entry) { return entry.previous(); } + @Override + protected Node KEY_VALUE_GENERIC_TYPE previous(Node KEY_VALUE_GENERIC_TYPE entry) { return entry.next(); } + + @Override + protected BI_ITERATOR KEY_GENERIC_TYPE keyIterator() { + return new DecsendingSubKeyIterator(absHighest(), absLowFence(), absHighFence()); + } + + @Override + protected BI_ITERATOR KEY_GENERIC_TYPE keyIterator(KEY_TYPE element) { + return new DecsendingSubKeyIterator(absHigher(element), absLowFence(), absHighFence()); + } + + @Override + protected VALUE_BI_ITERATOR VALUE_GENERIC_TYPE valueIterator() { + return new DecsendingSubValueIterator(absHighest(), absLowFence(), absHighFence()); + } + + @Override + protected BI_ITERATOR KEY_GENERIC_TYPE descendingKeyIterator() { + return new AcsendingSubKeyIterator(absLowest(), absHighFence(), absLowFence()); + } + + class DescendingSubEntrySet extends SubEntrySet { + @Override + public ObjectIterator iterator() { + return new DecsendingSubEntryIterator(absHighest(), absLowFence(), absHighFence()); + } + } + } + + static abstract class NavigableSubMap KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE + { + final AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE map; + final KEY_TYPE lo, hi; + final boolean fromStart, toEnd; + final boolean loInclusive, hiInclusive; + + NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE inverse; + NAVIGABLE_SET KEY_GENERIC_TYPE keySet; + ObjectSet entrySet; + VALUE_COLLECTION VALUE_GENERIC_TYPE values; + + NavigableSubMap(AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE map, boolean fromStart, KEY_TYPE lo, boolean loInclusive, boolean toEnd, KEY_TYPE hi, boolean hiInclusive) { + if (!fromStart && !toEnd) { + if (map.compare(lo, hi) > 0) throw new IllegalArgumentException("fromKey > toKey"); + } + else { + if (!fromStart) map.validate(lo); + if (!toEnd) map.validate(hi); + } + this.map = map; + this.fromStart = fromStart; + this.lo = lo; + this.loInclusive = loInclusive; + this.toEnd = toEnd; + this.hi = hi; + this.hiInclusive = hiInclusive; + } + +#if TYPE_OBJECT + public KEY_TYPE getDefaultMaxValue() { return map.getDefaultMaxValue(); } + public KEY_TYPE getDefaultMinValue() { return map.getDefaultMinValue(); } +#else + @Override + public void setDefaultMaxValue(KEY_TYPE e) { map.setDefaultMaxValue(e); } + @Override + public KEY_TYPE getDefaultMaxValue() { return map.getDefaultMaxValue(); } + @Override + public void setDefaultMinValue(KEY_TYPE e) { map.setDefaultMinValue(e); } + @Override + public KEY_TYPE getDefaultMinValue() { return map.getDefaultMinValue(); } +#endif + protected boolean isNullComparator() { return map.comparator() == null; } + + @Override + public ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE setDefaultReturnValue(VALUE_TYPE v) { + map.setDefaultReturnValue(v); + return this; + } + + @Override + public VALUE_TYPE getDefaultReturnValue() { return map.getDefaultReturnValue(); } + + @Override + public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { + if(values == null) values = new SubMapValues(); + return values; + } + + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE descendingKeySet() { + return descendingMap().navigableKeySet(); + } + + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE keySet() { + return navigableKeySet(); + } + + protected abstract Node KEY_VALUE_GENERIC_TYPE subLowest(); + protected abstract Node KEY_VALUE_GENERIC_TYPE subHighest(); + protected abstract Node KEY_VALUE_GENERIC_TYPE subCeiling(KEY_TYPE key); + protected abstract Node KEY_VALUE_GENERIC_TYPE subHigher(KEY_TYPE key); + protected abstract Node KEY_VALUE_GENERIC_TYPE subFloor(KEY_TYPE key); + protected abstract Node KEY_VALUE_GENERIC_TYPE subLower(KEY_TYPE key); + protected abstract BI_ITERATOR KEY_GENERIC_TYPE keyIterator(); + protected abstract BI_ITERATOR KEY_GENERIC_TYPE keyIterator(KEY_TYPE element); + protected abstract VALUE_BI_ITERATOR VALUE_GENERIC_TYPE valueIterator(); + protected abstract BI_ITERATOR KEY_GENERIC_TYPE descendingKeyIterator(); + protected KEY_TYPE lowKeyOrNull(Node KEY_VALUE_GENERIC_TYPE entry) { return entry == null ? getDefaultMinValue() : entry.key; } + protected KEY_TYPE highKeyOrNull(Node KEY_VALUE_GENERIC_TYPE entry) { return entry == null ? getDefaultMaxValue() : entry.key; } + protected Node KEY_VALUE_GENERIC_TYPE next(Node KEY_VALUE_GENERIC_TYPE entry) { return entry.next(); } + protected Node KEY_VALUE_GENERIC_TYPE previous(Node KEY_VALUE_GENERIC_TYPE entry) { return entry.previous(); } + + protected boolean tooLow(KEY_TYPE key) { + if (!fromStart) { + int c = map.compare(key, lo); + if (c < 0 || (c == 0 && !loInclusive)) return true; + } + return false; + } + + protected boolean tooHigh(KEY_TYPE key) { + if (!toEnd) { + int c = map.compare(key, hi); + if (c > 0 || (c == 0 && !hiInclusive)) return true; + } + return false; + } + protected boolean inRange(KEY_TYPE key) { return !tooLow(key) && !tooHigh(key); } + protected boolean inClosedRange(KEY_TYPE key) { return (fromStart || map.compare(key, lo) >= 0) && (toEnd || map.compare(hi, key) >= 0); } + protected boolean inRange(KEY_TYPE key, boolean inclusive) { return inclusive ? inRange(key) : inClosedRange(key); } + + protected Node KEY_VALUE_GENERIC_TYPE absLowest() { + Node KEY_VALUE_GENERIC_TYPE e = (fromStart ? map.first : (loInclusive ? map.findCeilingNode(lo) : map.findHigherNode(lo))); + return (e == null || tooHigh(e.key)) ? null : e; + } + + protected Node KEY_VALUE_GENERIC_TYPE absHighest() { + Node KEY_VALUE_GENERIC_TYPE e = (toEnd ? map.last : (hiInclusive ? map.findFloorNode(hi) : map.findLowerNode(hi))); + return (e == null || tooLow(e.key)) ? null : e; + } + + protected Node KEY_VALUE_GENERIC_TYPE absCeiling(KEY_TYPE key) { + if (tooLow(key)) return absLowest(); + Node KEY_VALUE_GENERIC_TYPE e = map.findCeilingNode(key); + return (e == null || tooHigh(e.key)) ? null : e; + } + + protected Node KEY_VALUE_GENERIC_TYPE absHigher(KEY_TYPE key) { + if (tooLow(key)) return absLowest(); + Node KEY_VALUE_GENERIC_TYPE e = map.findHigherNode(key); + return (e == null || tooHigh(e.key)) ? null : e; + } + + protected Node KEY_VALUE_GENERIC_TYPE absFloor(KEY_TYPE key) { + if (tooHigh(key)) return absHighest(); + Node KEY_VALUE_GENERIC_TYPE e = map.findFloorNode(key); + return (e == null || tooLow(e.key)) ? null : e; + } + + protected Node KEY_VALUE_GENERIC_TYPE absLower(KEY_TYPE key) { + if (tooHigh(key)) return absHighest(); + Node KEY_VALUE_GENERIC_TYPE e = map.findLowerNode(key); + return (e == null || tooLow(e.key)) ? null : e; + } + + protected Node KEY_VALUE_GENERIC_TYPE absHighFence() { return (toEnd ? null : (hiInclusive ? map.findHigherNode(hi) : map.findCeilingNode(hi))); } + protected Node KEY_VALUE_GENERIC_TYPE absLowFence() { return (fromStart ? null : (loInclusive ? map.findLowerNode(lo) : map.findFloorNode(lo))); } + + @Override + public COMPARATOR KEY_GENERIC_TYPE comparator() { return map.comparator(); } + + @Override + public KEY_TYPE POLL_FIRST_ENTRY_KEY() { + Node KEY_VALUE_GENERIC_TYPE entry = subLowest(); + if(entry != null) { + KEY_TYPE result = entry.key; + map.removeNode(entry); + return result; + } + return getDefaultMinValue(); + } + + @Override + public KEY_TYPE POLL_LAST_ENTRY_KEY() { + Node KEY_VALUE_GENERIC_TYPE entry = subHighest(); + if(entry != null) { + KEY_TYPE result = entry.key; + map.removeNode(entry); + return result; + } + return getDefaultMaxValue(); + } + + @Override + public VALUE_TYPE FIRST_ENTRY_VALUE() { + Node KEY_VALUE_GENERIC_TYPE entry = subLowest(); + if(entry == null) throw new NoSuchElementException(); + return entry.value; + } + + @Override + public VALUE_TYPE LAST_ENTRY_VALUE() { + Node KEY_VALUE_GENERIC_TYPE entry = subHighest(); + if(entry == null) throw new NoSuchElementException(); + return entry.value; + } + + @Override + public KEY_TYPE FIRST_ENTRY_KEY() { + Node KEY_VALUE_GENERIC_TYPE entry = subLowest(); + if(entry == null) throw new NoSuchElementException(); + return entry.key; + } + + @Override + public KEY_TYPE LAST_ENTRY_KEY() { + Node KEY_VALUE_GENERIC_TYPE entry = subHighest(); + if(entry == null) throw new NoSuchElementException(); + return entry.key; + } + + @Override + public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { + if (!inRange(key)) throw new IllegalArgumentException("key out of range"); + return map.put(key, value); + } + + @Override + public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { + if (!inRange(key)) throw new IllegalArgumentException("key out of range"); + return map.putIfAbsent(key, value); + } + +#if VALUE_PRIMITIVES + @Override + public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { + if(!inRange(key)) throw new IllegalArgumentException("key out of range"); + return map.addTo(key, value); + } + + @Override + public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { + if(!inRange(key)) throw new IllegalArgumentException("key out of range"); + return map.subFrom(key, value); + } + +#endif +#if TYPE_OBJECT + @Override + public boolean containsKey(Object key) { return inRange((CLASS_TYPE)key) && map.containsKey(key); } +#else + @Override + public boolean containsKey(KEY_TYPE key) { return inRange(key) && map.containsKey(key); } + +#endif + @Override + public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); +#if TYPE_OBJECT + map.validate(key); +#endif + if(!inRange(key)) return getDefaultReturnValue(); + Node KEY_VALUE_GENERIC_TYPE entry = map.findNode(key); + if(entry == null || VALUE_EQUALS(entry.value, getDefaultReturnValue())) return getDefaultReturnValue(); + VALUE_TYPE newValue = mappingFunction.apply(key, entry.value); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + map.removeNode(entry); + return newValue; + } + entry.value = newValue; + return newValue; + } + + @Override + public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { + return inRange(key) ? map.REMOVE_VALUE(key) : getDefaultReturnValue(); + } + + @Override + public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { + return inRange(key) ? map.REMOVE_VALUEOrDefault(key, defaultValue) : defaultValue; + } + +#if TYPE_OBJECT && VALUE_OBJECT + @Override + public boolean remove(Object key, Object value) { + return inRange((CLASS_TYPE)key) && map.remove(key, value); + } + +#else + @Override + public boolean remove(KEY_TYPE key, VALUE_TYPE value) { + return inRange(key) && map.remove(key, value); + } + +#endif + + @Override + public VALUE_TYPE GET_VALUE(KEY_TYPE key) { + return inRange(key) ? map.GET_VALUE(key) : getDefaultReturnValue(); + } + +#if TYPE_OBJECT && VALUE_OBJECT + @Override + public VALUE_TYPE getOrDefault(Object key, VALUE_TYPE defaultValue) { + return inRange((CLASS_TYPE)key) ? map.getOrDefault(key, defaultValue) : getDefaultReturnValue(); + } + +#else + @Override + public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { + return inRange(key) ? map.getOrDefault(key, defaultValue) : getDefaultReturnValue(); + } + +#endif + + @Override + public KEY_TYPE lowerKey(KEY_TYPE key) { return lowKeyOrNull(subLower(key)); } + @Override + public KEY_TYPE floorKey(KEY_TYPE key) { return lowKeyOrNull(subFloor(key)); } + @Override + public KEY_TYPE ceilingKey(KEY_TYPE key) { return highKeyOrNull(subCeiling(key)); } + @Override + public KEY_TYPE higherKey(KEY_TYPE key) { return highKeyOrNull(subHigher(key)); } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE lowerEntry(KEY_TYPE key) { return subLower(key); } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE floorEntry(KEY_TYPE key) { return subFloor(key); } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE ceilingEntry(KEY_TYPE key) { return subCeiling(key); } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE higherEntry(KEY_TYPE key) { return subHigher(key); } + + @Override + public boolean isEmpty() { + if(fromStart && toEnd) return map.isEmpty(); + Node KEY_VALUE_GENERIC_TYPE n = absLowest(); + return n == null || tooHigh(n.key); + } + + @Override + public int size() { return fromStart && toEnd ? map.size() : entrySet().size(); } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE firstEntry() { + Node KEY_VALUE_GENERIC_TYPE entry = subLowest(); + return entry == null ? null : entry.export(); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE lastEntry() { + Node KEY_VALUE_GENERIC_TYPE entry = subHighest(); + return entry == null ? null : entry.export(); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirstEntry() { + Node KEY_VALUE_GENERIC_TYPE entry = subLowest(); + if(entry != null) { + MAP.Entry KEY_VALUE_GENERIC_TYPE result = entry.export(); + map.removeNode(entry); + return result; + } + return null; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLastEntry() { + Node KEY_VALUE_GENERIC_TYPE entry = subHighest(); + if(entry != null) { + MAP.Entry KEY_VALUE_GENERIC_TYPE result = entry.export(); + map.removeNode(entry); + return result; + } + return null; + } + + abstract class SubEntrySet extends AbstractObjectSet { + @Override + public int size() { + if (fromStart && toEnd) return map.size(); + int size = 0; + for(ObjectIterator iter = iterator();iter.hasNext();iter.next(),size++); + return size; + } + + @Override + public boolean isEmpty() { + Node KEY_VALUE_GENERIC_TYPE n = absLowest(); + return n == null || tooHigh(n.key); + } + + @Override + public boolean contains(Object o) { + if (!(o instanceof Map.Entry)) return false; + if(o instanceof MAP.Entry) + { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE) o; +#if TYPE_OBJECT + if(entry.ENTRY_KEY() == null && isNullComparator()) return false; +#endif + KEY_TYPE key = entry.ENTRY_KEY(); + if (!inRange(key)) return false; + Node KEY_VALUE_GENERIC_TYPE node = map.findNode(key); + return node != null && VALUE_EQUALS(entry.ENTRY_VALUE(), node.ENTRY_VALUE()); + } + Map.Entry entry = (Map.Entry) o; + if(entry.getKey() == null && isNullComparator()) return false; + CLASS_TYPE key = (CLASS_TYPE)entry.getKey(); + if (!inRange(key)) return false; + Node KEY_VALUE_GENERIC_TYPE node = map.findNode(key); + return node != null && Objects.equals(entry.getValue(), VALUE_TO_OBJ(node.ENTRY_VALUE())); + } + + @Override + public boolean remove(Object o) { + if (!(o instanceof Map.Entry)) return false; + if(o instanceof MAP.Entry) + { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE) o; + KEY_TYPE key = entry.ENTRY_KEY(); + if (!inRange(key)) return false; + Node KEY_VALUE_GENERIC_TYPE node = map.findNode(key); + if (node != null && VALUE_EQUALS(node.ENTRY_VALUE(), entry.ENTRY_VALUE())) { + map.removeNode(node); + return true; + } + return false; + } + Map.Entry entry = (Map.Entry) o; + CLASS_TYPE key = (CLASS_TYPE)entry.getKey(); + if (!inRange(key)) return false; + Node KEY_VALUE_GENERIC_TYPE node = map.findNode(key); + if (node != null && Objects.equals(node.getValue(), entry.getValue())) { + map.removeNode(node); + return true; + } + return false; + } + + @Override + public void forEach(Consumer action) { + Objects.requireNonNull(action); + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) + action.accept(new BasicEntryKV_BRACES(entry.key, entry.value)); + } + + @Override + public void forEachIndexed(IntObjectConsumer action) { + Objects.requireNonNull(action); + int index = 0; + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) + action.accept(index++, new BasicEntryKV_BRACES(entry.key, entry.value)); + } + + @Override + public void forEach(E input, ObjectObjectConsumer action) { + Objects.requireNonNull(action); + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) + action.accept(input, new BasicEntryKV_BRACES(entry.key, entry.value)); + } + + @Override + public boolean matchesAny(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return false; + BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { + subEntry.set(entry.key, entry.value); + if(filter.test(subEntry)) return true; + } + return false; + } + + @Override + public boolean matchesNone(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { + subEntry.set(entry.key, entry.value); + if(filter.test(subEntry)) return false; + } + return true; + } + + @Override + public boolean matchesAll(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { + subEntry.set(entry.key, entry.value); + if(!filter.test(subEntry)) return false; + } + return true; + } + + @Override + public E reduce(E identity, BiFunction operator) { + Objects.requireNonNull(operator); + E state = identity; + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { + state = operator.apply(state, new BasicEntryKV_BRACES(entry.key, entry.value)); + } + return state; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE reduce(ObjectObjectUnaryOperator operator) { + Objects.requireNonNull(operator); + MAP.Entry KEY_VALUE_GENERIC_TYPE state = null; + boolean empty = true; + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { + if(empty) { + empty = false; + state = new BasicEntryKV_BRACES(entry.key, entry.value); + continue; + } + state = operator.apply(state, new BasicEntryKV_BRACES(entry.key, entry.value)); + } + return state; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE findFirst(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return null; + BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { + subEntry.set(entry.key, entry.value); + if(filter.test(subEntry)) return subEntry; + } + return null; + } + + @Override + public int count(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return 0; + int result = 0; + BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { + subEntry.set(entry.key, entry.value); + if(filter.test(subEntry)) result++; + } + return result; + } + } + + final class SubMapValues extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { + @Override + public boolean add(VALUE_TYPE o) { throw new UnsupportedOperationException(); } + +#if VALUE_OBJECT + @Override + public boolean contains(Object e) { + return containsValue(e); + } + +#else + @Override + public boolean contains(VALUE_TYPE e) { + return containsValue(e); + } + +#endif + @Override + public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() { return valueIterator(); } + + @Override + public int size() { + return NavigableSubMap.this.size(); + } + + @Override + public void clear() { + NavigableSubMap.this.clear(); + } + + @Override + public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) { + Objects.requireNonNull(action); + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) + action.accept(entry.value); + } + + @Override + public void forEachIndexed(VALUE_BI_FROM_INT_CONSUMER VALUE_GENERIC_TYPE action) { + Objects.requireNonNull(action); + int index = 0; + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) + action.accept(index++, entry.value); + } + + @Override + public void forEach(E input, VALUE_BI_FROM_OBJECT_CONSUMER VSV_GENERIC_TYPE action) { + Objects.requireNonNull(action); + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) + action.accept(input, entry.value); + } + + @Override + public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) + if(filter.test(entry.value)) return true; + return false; + } + + @Override + public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) + if(filter.test(entry.value)) return false; + return true; + } + + @Override + public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) + if(!filter.test(entry.value)) return false; + return true; + } + +#if !VALUE_OBJECT + @Override + public VALUE_TYPE reduce(VALUE_TYPE identity, VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + VALUE_TYPE state = identity; + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) + state = operator.APPLY_VALUE(state, entry.value); + return state; + } + +#else + @Override + public VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction operator) { + Objects.requireNonNull(operator); + VALUE_SPECIAL_TYPE state = identity; + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) + state = operator.apply(state, entry.value); + return state; + } + +#endif + @Override + public VALUE_TYPE reduce(VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + VALUE_TYPE state = EMPTY_VALUE; + boolean empty = true; + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { + if(empty) { + empty = false; + state = entry.value; + continue; + } + state = operator.APPLY_VALUE(state, entry.value); + } + return state; + } + + @Override + public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) + if(filter.test(entry.value)) return entry.value; + return EMPTY_VALUE; + } + + @Override + public int count(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + int result = 0; + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) + if(filter.test(entry.value)) result++; + return result; + } + } + + class DecsendingSubEntryIterator extends SubMapEntryIterator implements ObjectBidirectionalIterator + { + public DecsendingSubEntryIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence) { + super(first, forwardFence, backwardFence, false); + } + + @Override + protected Node KEY_VALUE_GENERIC_TYPE moveNext(Node KEY_VALUE_GENERIC_TYPE node) { + return node.previous(); + } + + @Override + protected Node KEY_VALUE_GENERIC_TYPE movePrevious(Node KEY_VALUE_GENERIC_TYPE node) { + return node.next(); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { + if(!hasPrevious()) throw new NoSuchElementException(); + return previousEntry(); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { + if(!hasNext()) throw new NoSuchElementException(); + return nextEntry(); + } + } + + class AcsendingSubEntryIterator extends SubMapEntryIterator implements ObjectBidirectionalIterator + { + public AcsendingSubEntryIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence) { + super(first, forwardFence, backwardFence, true); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { + if(!hasPrevious()) throw new NoSuchElementException(); + return previousEntry(); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { + if(!hasNext()) throw new NoSuchElementException(); + return nextEntry(); + } + } + + class DecsendingSubKeyIterator extends SubMapEntryIterator implements BI_ITERATOR KEY_GENERIC_TYPE + { + public DecsendingSubKeyIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence) { + super(first, forwardFence, backwardFence, false); + } + + @Override + protected Node KEY_VALUE_GENERIC_TYPE moveNext(Node KEY_VALUE_GENERIC_TYPE node) { + return node.previous(); + } + + @Override + protected Node KEY_VALUE_GENERIC_TYPE movePrevious(Node KEY_VALUE_GENERIC_TYPE node) { + return node.next(); + } + + @Override + public KEY_TYPE PREVIOUS() { + if(!hasPrevious()) throw new NoSuchElementException(); + return previousEntry().key; + } + + @Override + public KEY_TYPE NEXT() { + if(!hasNext()) throw new NoSuchElementException(); + return nextEntry().key; + } + } + + class AcsendingSubKeyIterator extends SubMapEntryIterator implements BI_ITERATOR KEY_GENERIC_TYPE + { + public AcsendingSubKeyIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence) { + super(first, forwardFence, backwardFence, true); + } + + @Override + public KEY_TYPE PREVIOUS() { + if(!hasPrevious()) throw new NoSuchElementException(); + return previousEntry().key; + } + + @Override + public KEY_TYPE NEXT() { + if(!hasNext()) throw new NoSuchElementException(); + return nextEntry().key; + } + } + + class AcsendingSubValueIterator extends SubMapEntryIterator implements VALUE_BI_ITERATOR VALUE_GENERIC_TYPE + { + public AcsendingSubValueIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence) { + super(first, forwardFence, backwardFence, true); + } + + @Override + public VALUE_TYPE VALUE_PREVIOUS() { + if(!hasPrevious()) throw new NoSuchElementException(); + return previousEntry().value; + } + + @Override + public VALUE_TYPE VALUE_NEXT() { + if(!hasNext()) throw new NoSuchElementException(); + return nextEntry().value; + } + } + + class DecsendingSubValueIterator extends SubMapEntryIterator implements VALUE_BI_ITERATOR VALUE_GENERIC_TYPE + { + public DecsendingSubValueIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence) { + super(first, forwardFence, backwardFence, false); + } + + @Override + protected Node KEY_VALUE_GENERIC_TYPE moveNext(Node KEY_VALUE_GENERIC_TYPE node) { + return node.previous(); + } + + @Override + protected Node KEY_VALUE_GENERIC_TYPE movePrevious(Node KEY_VALUE_GENERIC_TYPE node) { + return node.next(); + } + + @Override + public VALUE_TYPE VALUE_PREVIOUS() { + if(!hasPrevious()) throw new NoSuchElementException(); + return previousEntry().value; + } + + @Override + public VALUE_TYPE VALUE_NEXT() { + if(!hasNext()) throw new NoSuchElementException(); + return nextEntry().value; + } + } + + abstract class SubMapEntryIterator + { + final boolean isForward; + boolean wasForward; + Node KEY_VALUE_GENERIC_TYPE lastReturned; + Node KEY_VALUE_GENERIC_TYPE next; + Node KEY_VALUE_GENERIC_TYPE previous; + boolean unboundForwardFence; + boolean unboundBackwardFence; + KEY_TYPE forwardFence; + KEY_TYPE backwardFence; + + public SubMapEntryIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence, boolean isForward) { + next = first; + previous = first == null ? null : movePrevious(first); + this.forwardFence = forwardFence == null ? EMPTY_KEY_VALUE : forwardFence.key; + this.backwardFence = backwardFence == null ? EMPTY_KEY_VALUE : backwardFence.key; + unboundForwardFence = forwardFence == null; + unboundBackwardFence = backwardFence == null; + this.isForward = isForward; + } + + protected Node KEY_VALUE_GENERIC_TYPE moveNext(Node KEY_VALUE_GENERIC_TYPE node) { + return node.next(); + } + + protected Node KEY_VALUE_GENERIC_TYPE movePrevious(Node KEY_VALUE_GENERIC_TYPE node) { + return node.previous(); + } + + public boolean hasNext() { + return next != null && (unboundForwardFence || next.key != forwardFence); + } + + protected Node KEY_VALUE_GENERIC_TYPE nextEntry() { + lastReturned = next; + previous = next; + Node KEY_VALUE_GENERIC_TYPE result = next; + next = moveNext(next); + wasForward = isForward; + return result; + } + + public boolean hasPrevious() { + return previous != null && (unboundBackwardFence || previous.key != backwardFence); + } + + protected Node KEY_VALUE_GENERIC_TYPE previousEntry() { + lastReturned = previous; + next = previous; + Node KEY_VALUE_GENERIC_TYPE result = previous; + previous = movePrevious(previous); + wasForward = !isForward; + return result; + } + + public void remove() { + if(lastReturned == null) throw new IllegalStateException(); + if(next == lastReturned) next = moveNext(next); + if(previous == lastReturned) previous = movePrevious(previous); + if(wasForward && lastReturned.needsSuccessor()) next = lastReturned; + map.removeNode(lastReturned); + lastReturned = null; + } + } + } + + class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE + { + @Override + public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() { + return new AscendingValueIterator(first); + } + + @Override + public boolean add(VALUE_TYPE e) { throw new UnsupportedOperationException(); } + + @Override + public void clear() { + AVL_TREE_MAP.this.clear(); + } + + @Override + public int size() { + return AVL_TREE_MAP.this.size; + } + +#if VALUE_OBJECT + @Override + public boolean contains(Object e) { + return containsValue(e); + } + +#else + @Override + public boolean contains(VALUE_TYPE e) { + return containsValue(e); + } + +#endif + @Override + public boolean remove(Object o) { + for(Node KEY_VALUE_GENERIC_TYPE entry = first; entry != null; entry = entry.next()) { + if(Objects.equals(entry.getValue(), o)) { + removeNode(entry); + return true; + } + } + return false; + } + + @Override + public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) { + Objects.requireNonNull(action); + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + action.accept(entry.value); + } + + @Override + public void forEachIndexed(VALUE_BI_FROM_INT_CONSUMER VALUE_GENERIC_TYPE action) { + Objects.requireNonNull(action); + int index = 0; + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + action.accept(index++, entry.value); + } + + @Override + public void forEach(E input, VALUE_BI_FROM_OBJECT_CONSUMER VSV_GENERIC_TYPE action) { + Objects.requireNonNull(action); + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + action.accept(input, entry.value); + } + + @Override + public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + if(filter.test(entry.value)) return true; + return false; + } + + @Override + public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + if(filter.test(entry.value)) return false; + return true; + } + + @Override + public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + if(!filter.test(entry.value)) return false; + return true; + } + + #if !VALUE_OBJECT + @Override + public VALUE_TYPE reduce(VALUE_TYPE identity, VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + VALUE_TYPE state = identity; + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + state = operator.APPLY_VALUE(state, entry.value); + return state; + } + + #else + @Override + public VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction operator) { + Objects.requireNonNull(operator); + VALUE_SPECIAL_TYPE state = identity; + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + state = operator.apply(state, entry.value); + return state; + } + + #endif + @Override + public VALUE_TYPE reduce(VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + VALUE_TYPE state = EMPTY_VALUE; + boolean empty = true; + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { + if(empty) { + empty = false; + state = entry.value; + continue; + } + state = operator.APPLY_VALUE(state, entry.value); + } + return state; + } + + @Override + public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + if(filter.test(entry.value)) return entry.value; + return EMPTY_VALUE; + } + + @Override + public int count(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + int result = 0; + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + if(filter.test(entry.value)) result++; + return result; + } + } + + class EntrySet extends AbstractObjectSet { + + @Override + public ObjectIterator iterator() { + return new AscendingMapEntryIterator(first); + } + + @Override + public void clear() { + AVL_TREE_MAP.this.clear(); + } + + @Override + public int size() { + return AVL_TREE_MAP.this.size; + } + + @Override + public boolean contains(Object o) { + if (!(o instanceof Map.Entry)) return false; + if(o instanceof MAP.Entry) + { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE) o; +#if TYPE_OBJECT + if(entry.getKey() == null && comparator() == null) return false; +#endif + KEY_TYPE key = entry.ENTRY_KEY(); + Node KEY_VALUE_GENERIC_TYPE node = findNode(key); + return node != null && VALUE_EQUALS(entry.ENTRY_VALUE(), node.ENTRY_VALUE()); + } + Map.Entry entry = (Map.Entry) o; + if(entry.getKey() == null && comparator() == null) return false; +#if !TYPE_OBJECT + if(!(entry.getKey() instanceof CLASS_TYPE)) return false; +#endif + CLASS_TYPE key = (CLASS_TYPE)entry.getKey(); + Node KEY_VALUE_GENERIC_TYPE node = findNode(key); + return node != null && Objects.equals(entry.getValue(), VALUE_TO_OBJ(node.ENTRY_VALUE())); + } + + @Override + public boolean remove(Object o) { + if (!(o instanceof Map.Entry)) return false; + if(o instanceof MAP.Entry) + { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE) o; + KEY_TYPE key = entry.ENTRY_KEY(); + Node KEY_VALUE_GENERIC_TYPE node = findNode(key); + if (node != null && VALUE_EQUALS(entry.ENTRY_VALUE(), node.ENTRY_VALUE())) { + removeNode(node); + return true; + } + return false; + } + Map.Entry entry = (Map.Entry) o; + CLASS_TYPE key = (CLASS_TYPE)entry.getKey(); + Node KEY_VALUE_GENERIC_TYPE node = findNode(key); + if (node != null && Objects.equals(entry.getValue(), VALUE_TO_OBJ(node.ENTRY_VALUE()))) { + removeNode(node); + return true; + } + return false; + } + + @Override + public void forEach(Consumer action) { + Objects.requireNonNull(action); + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + action.accept(new BasicEntryKV_BRACES(entry.key, entry.value)); + } + + @Override + public void forEachIndexed(IntObjectConsumer action) { + Objects.requireNonNull(action); + int index = 0; + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + action.accept(index++, new BasicEntryKV_BRACES(entry.key, entry.value)); + } + + @Override + public void forEach(E input, ObjectObjectConsumer action) { + Objects.requireNonNull(action); + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + action.accept(input, new BasicEntryKV_BRACES(entry.key, entry.value)); + } + + @Override + public boolean matchesAny(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return false; + BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { + subEntry.set(entry.key, entry.value); + if(filter.test(subEntry)) return true; + } + return false; + } + + @Override + public boolean matchesNone(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { + subEntry.set(entry.key, entry.value); + if(filter.test(subEntry)) return false; + } + return true; + } + + @Override + public boolean matchesAll(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { + subEntry.set(entry.key, entry.value); + if(!filter.test(subEntry)) return false; + } + return true; + } + + @Override + public E reduce(E identity, BiFunction operator) { + Objects.requireNonNull(operator); + E state = identity; + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { + state = operator.apply(state, new BasicEntryKV_BRACES(entry.key, entry.value)); + } + return state; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE reduce(ObjectObjectUnaryOperator operator) { + Objects.requireNonNull(operator); + MAP.Entry KEY_VALUE_GENERIC_TYPE state = null; + boolean empty = true; + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { + if(empty) { + empty = false; + state = new BasicEntryKV_BRACES(entry.key, entry.value); + continue; + } + state = operator.apply(state, new BasicEntryKV_BRACES(entry.key, entry.value)); + } + return state; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE findFirst(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return null; + BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { + subEntry.set(entry.key, entry.value); + if(filter.test(subEntry)) return subEntry; + } + return null; + } + + @Override + public int count(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return 0; + int result = 0; + BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { + subEntry.set(entry.key, entry.value); + if(filter.test(subEntry)) result++; + } + return result; + } + } + + class DescendingKeyIterator extends MapEntryIterator implements BI_ITERATOR KEY_GENERIC_TYPE + { + public DescendingKeyIterator(Node KEY_VALUE_GENERIC_TYPE first) { + super(first, false); + } + + @Override + protected Node KEY_VALUE_GENERIC_TYPE moveNext(Node KEY_VALUE_GENERIC_TYPE node) { + return node.previous(); + } + + @Override + protected Node KEY_VALUE_GENERIC_TYPE movePrevious(Node KEY_VALUE_GENERIC_TYPE node) { + return node.next(); + } + + @Override + public KEY_TYPE PREVIOUS() { + if(!hasPrevious()) throw new NoSuchElementException(); + return previousEntry().key; + } + + @Override + public KEY_TYPE NEXT() { + if(!hasNext()) throw new NoSuchElementException(); + return nextEntry().key; + } + } + + class AscendingMapEntryIterator extends MapEntryIterator implements ObjectBidirectionalIterator + { + public AscendingMapEntryIterator(Node KEY_VALUE_GENERIC_TYPE first) + { + super(first, true); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { + if(!hasPrevious()) throw new NoSuchElementException(); + return previousEntry(); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { + if(!hasNext()) throw new NoSuchElementException(); + return nextEntry(); + } + } + + class AscendingValueIterator extends MapEntryIterator implements VALUE_BI_ITERATOR VALUE_GENERIC_TYPE + { + public AscendingValueIterator(Node KEY_VALUE_GENERIC_TYPE first) { + super(first, true); + } + + @Override + public VALUE_TYPE VALUE_PREVIOUS() { + if(!hasPrevious()) throw new NoSuchElementException(); + return previousEntry().value; + } + + @Override + public VALUE_TYPE VALUE_NEXT() { + if(!hasNext()) throw new NoSuchElementException(); + return nextEntry().value; + } + } + + class AscendingKeyIterator extends MapEntryIterator implements BI_ITERATOR KEY_GENERIC_TYPE + { + public AscendingKeyIterator(Node KEY_VALUE_GENERIC_TYPE first) { + super(first, true); + } + + @Override + public KEY_TYPE PREVIOUS() { + if(!hasPrevious()) throw new NoSuchElementException(); + return previousEntry().key; + } + + @Override + public KEY_TYPE NEXT() { + if(!hasNext()) throw new NoSuchElementException(); + return nextEntry().key; + } + } + + abstract class MapEntryIterator + { + final boolean isForward; + boolean wasMoved = false; + Node KEY_VALUE_GENERIC_TYPE lastReturned; + Node KEY_VALUE_GENERIC_TYPE next; + Node KEY_VALUE_GENERIC_TYPE previous; + + public MapEntryIterator(Node KEY_VALUE_GENERIC_TYPE first, boolean isForward) { + next = first; + previous = first == null ? null : movePrevious(first); + this.isForward = isForward; + } + + protected Node KEY_VALUE_GENERIC_TYPE moveNext(Node KEY_VALUE_GENERIC_TYPE node) { + return node.next(); + } + + protected Node KEY_VALUE_GENERIC_TYPE movePrevious(Node KEY_VALUE_GENERIC_TYPE node) { + return node.previous(); + } + + public boolean hasNext() { + return next != null; + } + + protected Node KEY_VALUE_GENERIC_TYPE nextEntry() { + lastReturned = next; + previous = next; + Node KEY_VALUE_GENERIC_TYPE result = next; + next = moveNext(next); + wasMoved = isForward; + return result; + } + + public boolean hasPrevious() { + return previous != null; + } + + protected Node KEY_VALUE_GENERIC_TYPE previousEntry() { + lastReturned = previous; + next = previous; + Node KEY_VALUE_GENERIC_TYPE result = previous; + previous = movePrevious(previous); + wasMoved = !isForward; + return result; + } + + public void remove() { + if(lastReturned == null) throw new IllegalStateException(); + if(next == lastReturned) next = moveNext(next); + if(previous == lastReturned) previous = movePrevious(previous); + if(wasMoved && lastReturned.needsSuccessor()) next = lastReturned; + removeNode(lastReturned); + lastReturned = null; + } + } + + private static final class Node KEY_VALUE_GENERIC_TYPE implements MAP.Entry KEY_VALUE_GENERIC_TYPE + { + KEY_TYPE key; + VALUE_TYPE value; + int state; + Node KEY_VALUE_GENERIC_TYPE parent; + Node KEY_VALUE_GENERIC_TYPE left; + Node KEY_VALUE_GENERIC_TYPE right; + + Node(KEY_TYPE key, VALUE_TYPE value, Node KEY_VALUE_GENERIC_TYPE parent) { + this.key = key; + this.value = value; + this.parent = parent; + } + + Node KEY_VALUE_GENERIC_TYPE copy() { + Node KEY_VALUE_GENERIC_TYPE entry = new NodeKV_BRACES(key, value, null); + entry.state = state; + if(left != null) { + Node KEY_VALUE_GENERIC_TYPE newLeft = left.copy(); + entry.left = newLeft; + newLeft.parent = entry; + } + if(right != null) { + Node KEY_VALUE_GENERIC_TYPE newRight = right.copy(); + entry.right = newRight; + newRight.parent = entry; + } + return entry; + } + + public BasicEntry KEY_VALUE_GENERIC_TYPE export() { + return new BasicEntryKV_BRACES(key, value); + } + + @Override + public KEY_TYPE ENTRY_KEY() { + return key; + } + + @Override + public VALUE_TYPE ENTRY_VALUE() { + return value; + } + + @Override + public VALUE_TYPE setValue(VALUE_TYPE value) { + VALUE_TYPE oldValue = this.value; + this.value = value; + return oldValue; + } + +#if VALUE_PRIMITIVES + VALUE_TYPE addTo(VALUE_TYPE value) { + VALUE_TYPE oldValue = this.value; + this.value += value; + return oldValue; + } + + VALUE_TYPE subFrom(VALUE_TYPE value) { + VALUE_TYPE oldValue = this.value; + this.value -= value; + return oldValue; + } +#endif + @Override + public boolean equals(Object obj) { + if(obj instanceof Map.Entry) { + if(obj instanceof MAP.Entry) { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)obj; +#if TYPE_OBJECT + if(entry.ENTRY_KEY() == null) return false; +#endif + return KEY_EQUALS(key, entry.ENTRY_KEY()) && VALUE_EQUALS(value, entry.ENTRY_VALUE()); + } + Map.Entry entry = (Map.Entry)obj; + Object otherKey = entry.getKey(); + if(otherKey == null) return false; + Object otherValue = entry.getValue(); +#if TYPE_OBJECT && VALUE_OBJECT + return KEY_EQUALS(key, otherKey) && VALUE_EQUALS(value, otherValue); +#else if TYPE_OBJECT + return otherValue instanceof CLASS_VALUE_TYPE && KEY_EQUALS(key, otherKey) && VALUE_EQUALS(value, CLASS_TO_VALUE(otherValue)); +#else if VALUE_OBJECT + return otherKey instanceof CLASS_TYPE && KEY_EQUALS(key, CLASS_TO_KEY(otherKey)) && VALUE_EQUALS(value, otherValue); +#else + return otherKey instanceof CLASS_TYPE && otherValue instanceof CLASS_VALUE_TYPE && KEY_EQUALS(key, CLASS_TO_KEY(otherKey)) && VALUE_EQUALS(value, CLASS_TO_VALUE(otherValue)); +#endif + } + return false; + } + + @Override + public int hashCode() { + return KEY_TO_HASH(key) ^ VALUE_TO_HASH(value); + } + + @Override + public String toString() { + return KEY_TO_STRING(key) + "=" + VALUE_TO_STRING(value); + } + + int getHeight() { return state; } + + void updateHeight() { state = (1 + Math.max(left == null ? -1 : left.getHeight(), right == null ? -1 : right.getHeight())); } + + int getBalance() { return (left == null ? -1 : left.getHeight()) - (right == null ? -1 : right.getHeight()); } + + boolean needsSuccessor() { return left != null && right != null; } + + boolean replace(Node KEY_VALUE_GENERIC_TYPE entry) { + if(entry != null) entry.parent = parent; + if(parent != null) { + if(parent.left == this) parent.left = entry; + else parent.right = entry; + } + return parent == null; + } + + Node KEY_VALUE_GENERIC_TYPE next() { + if(right != null) { + Node KEY_VALUE_GENERIC_TYPE parent = right; + while(parent.left != null) parent = parent.left; + return parent; + } + Node KEY_VALUE_GENERIC_TYPE parent = this.parent; + Node KEY_VALUE_GENERIC_TYPE control = this; + while(parent != null && control == parent.right) { + control = parent; + parent = parent.parent; + } + return parent; + } + + Node KEY_VALUE_GENERIC_TYPE previous() { + if(left != null) { + Node KEY_VALUE_GENERIC_TYPE parent = left; + while(parent.right != null) parent = parent.right; + return parent; + } + Node KEY_VALUE_GENERIC_TYPE parent = this.parent; + Node KEY_VALUE_GENERIC_TYPE control = this; + while(parent != null && control == parent.left) { + control = parent; + parent = parent.parent; + } + return parent; + } + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/collections/templates/maps/impl/tree/RBTreeMap.template b/src/builder/resources/speiger/assets/collections/templates/maps/impl/tree/RBTreeMap.template index 14b7e59..6ef4347 100644 --- a/src/builder/resources/speiger/assets/collections/templates/maps/impl/tree/RBTreeMap.template +++ b/src/builder/resources/speiger/assets/collections/templates/maps/impl/tree/RBTreeMap.template @@ -1,2989 +1,2991 @@ -package speiger.src.collections.PACKAGE.maps.impl.tree; - -import java.util.Collections; -import java.util.Map; -#if TYPE_OBJECT -import java.util.Comparator; -#endif -import java.util.Objects; -import java.util.NoSuchElementException; -import java.util.function.Consumer; -import java.util.function.BiFunction; -import java.util.function.Predicate; -#if !TYPE_OBJECT && JDK_TYPE -import java.util.function.PREDICATE; -#endif -#if !SAME_TYPE && JDK_VALUE && !VALUE_OBJECT -import java.util.function.VALUE_PREDICATE; -#endif - -import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.functions.COMPARATOR; -import speiger.src.collections.PACKAGE.functions.CONSUMER; -import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; -#endif -import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER; -#if !TYPE_OBJECT && !VALUE_OBJECT -import speiger.src.collections.ints.functions.consumer.IntObjectConsumer; -#endif -#if !SAME_TYPE -import speiger.src.collections.ints.functions.consumer.VALUE_BI_FROM_INT_CONSUMER; -#endif -#if !VALUE_BOOLEAN || !JDK_TYPE -import speiger.src.collections.PACKAGE.functions.function.FUNCTION; -#endif -import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; -#if !TYPE_OBJECT && !VALUE_BOOLEAN && !JDK_TYPE -import speiger.src.collections.PACKAGE.functions.function.PREDICATE; -#endif -import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; -#if !SAME_TYPE -import speiger.src.collections.PACKAGE.functions.function.SINGLE_UNARY_OPERATOR; -#endif -import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.NAVIGABLE_MAP; -import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET; -import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET; -#if TYPE_OBJECT -import speiger.src.collections.PACKAGE.sets.SET; -#endif -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; -import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_SUPPLIER; -#if !SAME_TYPE -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_BI_ITERATOR; -import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR; -#endif -#if !VALUE_OBJECT && !SAME_TYPE -import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER; -#endif -#if !TYPE_OBJECT && !VALUE_OBJECT || !VALUE_OBJECT -import speiger.src.collections.objects.functions.consumer.ObjectObjectConsumer; -#endif -#if !SAME_TYPE -#if !TYPE_OBJECT -import speiger.src.collections.objects.functions.consumer.VALUE_BI_FROM_OBJECT_CONSUMER; - -#endif -#if !JDK_VALUE -import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE; -#endif -#endif -#if !TYPE_OBJECT && !VALUE_OBJECT -import speiger.src.collections.objects.collections.ObjectBidirectionalIterator; -#endif -#if !VALUE_OBJECT -import speiger.src.collections.objects.collections.ObjectIterator; -#endif -#if !TYPE_OBJECT -#if !VALUE_OBJECT -import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator; - -#endif -import speiger.src.collections.objects.sets.AbstractObjectSet; -import speiger.src.collections.objects.sets.ObjectSet; -#endif - -/** - * A Simple Type Specific RB TreeMap implementation that reduces boxing/unboxing. - * It is using a bit more memory then FastUtil, - * but it saves a lot of Performance on the Optimized removal and iteration logic. - * Which makes the implementation actually useable and does not get outperformed by Javas default implementation. - * @Type(T) - * @ValueType(V) - */ -public class RB_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE -{ - /** The center of the Tree */ - protected transient Node KEY_VALUE_GENERIC_TYPE tree; - /** The Lowest possible Node */ - protected transient Node KEY_VALUE_GENERIC_TYPE first; - /** The Highest possible Node */ - protected transient Node KEY_VALUE_GENERIC_TYPE last; - /** The amount of elements stored in the Map */ - protected int size = 0; - /** The Sorter of the Tree */ - protected transient COMPARATOR KEY_GENERIC_TYPE comparator; - -#if !TYPE_OBJECT - /** the default return value for max searches */ - protected KEY_TYPE defaultMaxNotFound = CLASS_TYPE.MIN_VALUE; - /** the default return value for min searches */ - protected KEY_TYPE defaultMinNotFound = CLASS_TYPE.MAX_VALUE; -#endif - - /** KeySet Cache */ - protected NAVIGABLE_SET KEY_GENERIC_TYPE keySet; - /** Values Cache */ - protected VALUE_COLLECTION VALUE_GENERIC_TYPE values; - /** EntrySet Cache */ - protected ObjectSet entrySet; - - /** - * Default Constructor - */ - public RB_TREE_MAP() { - } - - /** - * Constructor that allows to define the sorter - * @param comp the function that decides how the tree is sorted, can be null - */ - public RB_TREE_MAP(COMPARATOR KEY_GENERIC_TYPE comp) { - comparator = comp; - } - -#if !TYPE_OBJECT || !VALUE_OBJECT - /** - * Helper constructor that allow to create a map from boxed values (it will unbox them) - * @param keys the keys that should be put into the map - * @param values the values that should be put into the map. - * @throws IllegalStateException if the keys and values do not match in lenght - */ - public RB_TREE_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values) { - this(keys, values, null); - } - - /** - * Helper constructor that has a custom sorter and allow to create a map from boxed values (it will unbox them) - * @param keys the keys that should be put into the map - * @param values the values that should be put into the map. - * @param comp the function that decides how the tree is sorted, can be null - * @throws IllegalStateException if the keys and values do not match in lenght - */ - public RB_TREE_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, COMPARATOR KEY_GENERIC_TYPE comp) { - comparator = comp; - if(keys.length != values.length) throw new IllegalStateException("Input Arrays are not equal size"); - for(int i = 0,m=keys.length;i map) { - this(map, null); - } - - /** - * A Helper constructor that has a custom sorter and allows to create a Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - * @param comp the function that decides how the tree is sorted, can be null - */ - public RB_TREE_MAP(Map map, COMPARATOR KEY_GENERIC_TYPE comp) { - comparator = comp; - putAll(map); - } - - /** - * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - */ - public RB_TREE_MAP(MAP KEY_VALUE_GENERIC_TYPE map) { - this(map, null); - } - - /** - * A Type Specific Helper function that has a custom sorter and allows to create a new Map with exactly the same values as the provided map. - * @param map the values that should be present in the map - * @param comp the function that decides how the tree is sorted, can be null - */ - public RB_TREE_MAP(MAP KEY_VALUE_GENERIC_TYPE map, COMPARATOR KEY_GENERIC_TYPE comp) { - comparator = comp; - putAll(map); - } - -#if TYPE_OBJECT - /** only used for primitives - * @return null - */ - public KEY_TYPE getDefaultMaxValue() { return null; } - /** only used for primitives - * @return null - */ - public KEY_TYPE getDefaultMinValue() { return null; } - -#else - @Override - public void setDefaultMaxValue(KEY_TYPE value) { defaultMaxNotFound = value; } - @Override - public KEY_TYPE getDefaultMaxValue() { return defaultMaxNotFound; } - @Override - public void setDefaultMinValue(KEY_TYPE value) { defaultMinNotFound = value; } - @Override - public KEY_TYPE getDefaultMinValue() { return defaultMinNotFound; } - -#endif - - @Override - public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { -#if TYPE_OBJECT - validate(key); -#endif - if(tree == null) { - tree = first = last = new NodeKV_BRACES(key, value, null); - size++; - return getDefaultReturnValue(); - } - int compare = 0; - Node KEY_VALUE_GENERIC_TYPE parent = tree; - while(true) { - if((compare = compare(key, parent.key)) == 0) return parent.setValue(value); - if(compare < 0) { - if(parent.left == null) break; - parent = parent.left; - } - else if(compare > 0) { - if(parent.right == null) break; - parent = parent.right; - } - } - Node KEY_VALUE_GENERIC_TYPE adding = new NodeKV_BRACES(key, value, parent); - if(compare < 0) { - parent.left = adding; - if(parent == first) first = adding; - } - else { - parent.right = adding; - if(parent == last) last = adding; - } - fixAfterInsertion(adding); - size++; - return getDefaultReturnValue(); - } - - @Override - public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { -#if TYPE_OBJECT - validate(key); -#endif - if(tree == null) { - tree = first = last = new NodeKV_BRACES(key, value, null); - size++; - return getDefaultReturnValue(); - } - int compare = 0; - Node KEY_VALUE_GENERIC_TYPE parent = tree; - while(true) { - if((compare = compare(key, parent.key)) == 0) { - if(VALUE_EQUALS(parent.value, getDefaultReturnValue())) return parent.setValue(value); - return parent.value; - } - if(compare < 0) { - if(parent.left == null) break; - parent = parent.left; - } - else if(compare > 0) { - if(parent.right == null) break; - parent = parent.right; - } - } - Node KEY_VALUE_GENERIC_TYPE adding = new NodeKV_BRACES(key, value, parent); - if(compare < 0) { - parent.left = adding; - if(parent == first) first = adding; - } - else { - parent.right = adding; - if(parent == last) last = adding; - } - fixAfterInsertion(adding); - size++; - return getDefaultReturnValue(); - } - -#if VALUE_PRIMITIVES - @Override - public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { -#if TYPE_OBJECT - validate(key); -#endif - if(tree == null) { - tree = first = last = new NodeKV_BRACES(key, value, null); - size++; - return getDefaultReturnValue(); - } - int compare = 0; - Node KEY_VALUE_GENERIC_TYPE parent = tree; - while(true) { - if((compare = compare(key, parent.key)) == 0) return parent.addTo(value); - if(compare < 0) { - if(parent.left == null) break; - parent = parent.left; - } - else if(compare > 0) { - if(parent.right == null) break; - parent = parent.right; - } - } - Node KEY_VALUE_GENERIC_TYPE adding = new NodeKV_BRACES(key, value, parent); - if(compare < 0) { - parent.left = adding; - if(parent == first) first = adding; - } - else { - parent.right = adding; - if(parent == last) last = adding; - } - fixAfterInsertion(adding); - size++; - return getDefaultReturnValue(); - } - - @Override - public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { - if(tree == null) return getDefaultReturnValue(); - int compare = 0; - Node KEY_VALUE_GENERIC_TYPE parent = tree; - while(true) { - if((compare = compare(key, parent.key)) == 0) - { - VALUE_TYPE oldValue = parent.subFrom(value); - if(value < 0 ? (parent.value >= getDefaultReturnValue()) : (parent.value <= getDefaultReturnValue())) removeNode(parent); - return oldValue; - } - if(compare < 0) { - if(parent.left == null) break; - parent = parent.left; - } - else if(compare > 0) { - if(parent.right == null) break; - parent = parent.right; - } - } - return getDefaultReturnValue(); - } - -#endif - @Override - public COMPARATOR KEY_GENERIC_TYPE comparator() { return comparator; } - -#if TYPE_OBJECT - @Override - public boolean containsKey(Object key) { - return findNode((KEY_TYPE)key) != null; - } - -#else - @Override - public boolean containsKey(KEY_TYPE key) { - return findNode(key) != null; - } - -#endif - @Override - public VALUE_TYPE GET_VALUE(KEY_TYPE key) { - Node KEY_VALUE_GENERIC_TYPE node = findNode(key); - return node == null ? getDefaultReturnValue() : node.value; - } - -#if TYPE_OBJECT && VALUE_OBJECT - @Override - public VALUE_TYPE getOrDefault(Object key, VALUE_TYPE defaultValue) { - Node KEY_VALUE_GENERIC_TYPE node = findNode((CLASS_TYPE)key); - return node == null ? defaultValue : node.value; - } - -#else - @Override - public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { - Node KEY_VALUE_GENERIC_TYPE node = findNode(key); - return node == null ? defaultValue : node.value; - } - -#endif - @Override - public KEY_TYPE FIRST_ENTRY_KEY() { - if(tree == null) throw new NoSuchElementException(); - return first.key; - } - - @Override - public KEY_TYPE POLL_FIRST_ENTRY_KEY() { - if(tree == null) return getDefaultMinValue(); - KEY_TYPE result = first.key; - removeNode(first); - return result; - } - - @Override - public KEY_TYPE LAST_ENTRY_KEY() { - if(tree == null) throw new NoSuchElementException(); - return last.key; - } - - @Override - public KEY_TYPE POLL_LAST_ENTRY_KEY() { - if(tree == null) return getDefaultMaxValue(); - KEY_TYPE result = last.key; - removeNode(last); - return result; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE firstEntry() { - if(tree == null) return null; - return first.export(); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE lastEntry() { - if(tree == null) return null; - return last.export(); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirstEntry() { - if(tree == null) return null; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = first.export(); - removeNode(first); - return entry; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLastEntry() { - if(tree == null) return null; - BasicEntry KEY_VALUE_GENERIC_TYPE entry = last.export(); - removeNode(last); - return entry; - } - - @Override - public VALUE_TYPE FIRST_ENTRY_VALUE() { - if(tree == null) throw new NoSuchElementException(); - return first.value; - } - - @Override - public VALUE_TYPE LAST_ENTRY_VALUE() { - if(tree == null) throw new NoSuchElementException(); - return last.value; - } - - @Override - public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { - Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); - if(entry == null) return getDefaultReturnValue(); - VALUE_TYPE value = entry.value; - removeNode(entry); - return value; - } - - @Override - public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { - Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); - if(entry == null) return defaultValue; - VALUE_TYPE value = entry.value; - removeNode(entry); - return value; - } - -#if TYPE_OBJECT && VALUE_OBJECT - @Override - public boolean remove(Object key, Object value) { - Node KEY_VALUE_GENERIC_TYPE entry = findNode((CLASS_TYPE)key); - if(entry == null || !Objects.equals(value, entry.value)) return false; - removeNode(entry); - return true; - } - -#else - @Override - public boolean remove(KEY_TYPE key, VALUE_TYPE value) { - Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); - if(entry == null || entry.value != value) return false; - removeNode(entry); - return true; - } - -#endif - @Override - public boolean replace(KEY_TYPE key, VALUE_TYPE oldValue, VALUE_TYPE newValue) { - Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); - if(entry == null || entry.value != oldValue) return false; - entry.value = newValue; - return true; - } - - @Override - public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value) { - Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); - if(entry == null) return getDefaultReturnValue(); - VALUE_TYPE oldValue = entry.value; - entry.value = value; - return oldValue; - } - - @Override - public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); -#if TYPE_OBJECT - validate(key); -#endif - Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); - if(entry == null) { - VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, getDefaultReturnValue()); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - put(key, newValue); - return newValue; - } - VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, entry.value); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - removeNode(entry); - return newValue; - } - entry.value = newValue; - return newValue; - } - - @Override - public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); -#if TYPE_OBJECT - validate(key); -#endif - Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); - if(entry == null) { - VALUE_TYPE newValue = mappingFunction.APPLY(key); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - put(key, newValue); - return newValue; - } - if(Objects.equals(entry.value, getDefaultReturnValue())) { - VALUE_TYPE newValue = mappingFunction.APPLY(key); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - entry.value = newValue; - } - return entry.value; - } - - @Override - public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) { - Objects.requireNonNull(valueProvider); -#if TYPE_OBJECT - validate(key); -#endif - Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); - if(entry == null) { - VALUE_TYPE newValue = valueProvider.VALUE_SUPPLY_GET(); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - put(key, newValue); - return newValue; - } - if(VALUE_EQUALS(entry.value, getDefaultReturnValue())) { - VALUE_TYPE newValue = valueProvider.VALUE_SUPPLY_GET(); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; - entry.value = newValue; - } - return entry.value; - } - - @Override - public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); -#if TYPE_OBJECT - validate(key); -#endif - Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); - if(entry == null || VALUE_EQUALS(entry.value, getDefaultReturnValue())) return getDefaultReturnValue(); - VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, entry.value); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - removeNode(entry); - return newValue; - } - entry.value = newValue; - return newValue; - } - - @Override - public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); -#if TYPE_OBJECT - validate(key); -#endif - Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); - VALUE_TYPE newValue = entry == null || VALUE_EQUALS(entry.value, getDefaultReturnValue()) ? value : mappingFunction.APPLY_VALUE(entry.value, value); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - if(entry != null) - removeNode(entry); - } - else if(entry == null) put(key, newValue); - else entry.value = newValue; - return newValue; - } - - @Override - public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); - for(MAP.Entry KEY_VALUE_GENERIC_TYPE entry : getFastIterable(m)) { - KEY_TYPE key = entry.ENTRY_KEY(); - Node KEY_VALUE_GENERIC_TYPE subEntry = findNode(key); - VALUE_TYPE newValue = subEntry == null || VALUE_EQUALS(subEntry.value, getDefaultReturnValue()) ? entry.ENTRY_VALUE() : mappingFunction.APPLY_VALUE(subEntry.value, entry.ENTRY_VALUE()); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - if(subEntry != null) - removeNode(subEntry); - } - else if(subEntry == null) put(key, newValue); - else subEntry.value = newValue; - } - } - - @Override - public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - action.accept(entry.key, entry.value); - } - - @Override - public int size() { return size; } - - @Override - public void clear() { - size = 0; - first = null; - last = null; - tree = null; - } - - protected BI_ITERATOR KEY_GENERIC_TYPE keyIterator() { - return new AscendingKeyIterator(first); - } - - protected BI_ITERATOR KEY_GENERIC_TYPE keyIterator(KEY_TYPE element) { - return new AscendingKeyIterator(findNode(element)); - } - - protected BI_ITERATOR KEY_GENERIC_TYPE descendingKeyIterator() { - return new DescendingKeyIterator(last); - } - - @Override - public RB_TREE_MAP KEY_VALUE_GENERIC_TYPE copy() { - RB_TREE_MAP KEY_VALUE_GENERIC_TYPE set = new RB_TREE_MAPKV_BRACES(); - set.size = size; - if(tree != null) { - set.tree = tree.copy(); - Node KEY_VALUE_GENERIC_TYPE lastFound = null; - for(Node KEY_VALUE_GENERIC_TYPE entry = tree;entry != null;entry = entry.left) lastFound = entry; - set.first = lastFound; - lastFound = null; - for(Node KEY_VALUE_GENERIC_TYPE entry = tree;entry != null;entry = entry.right) lastFound = entry; - set.last = lastFound; - } - return set; - } - - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE keySet() { - return navigableKeySet(); - } - - @Override - public ObjectSet ENTRY_SET() { - if(entrySet == null) entrySet = new EntrySet(); - return entrySet; - } - - @Override - public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { - if(values == null) values = new Values(); - return values; - } - - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE navigableKeySet() { - if(keySet == null) keySet = new KeySetKV_BRACES(this); - return keySet; - } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap() { - return new DescendingNaivgableSubMapKV_BRACES(this, true, EMPTY_KEY_VALUE, true, true, EMPTY_KEY_VALUE, true); - } - - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE descendingKeySet() { - return descendingMap().navigableKeySet(); - } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, boolean fromInclusive, KEY_TYPE toKey, boolean toInclusive) { - return new AscendingNaivgableSubMapKV_BRACES(this, false, fromKey, fromInclusive, false, toKey, toInclusive); - } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey, boolean inclusive) { - return new AscendingNaivgableSubMapKV_BRACES(this, true, EMPTY_KEY_VALUE, true, false, toKey, inclusive); - } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey, boolean inclusive) { - return new AscendingNaivgableSubMapKV_BRACES(this, false, fromKey, inclusive, true, EMPTY_KEY_VALUE, true); - } - - @Override - public KEY_TYPE lowerKey(KEY_TYPE e) { - Node KEY_VALUE_GENERIC_TYPE node = findLowerNode(e); - return node != null ? node.key : getDefaultMinValue(); - } - - @Override - public KEY_TYPE floorKey(KEY_TYPE e) { - Node KEY_VALUE_GENERIC_TYPE node = findFloorNode(e); - return node != null ? node.key : getDefaultMinValue(); - } - - @Override - public KEY_TYPE higherKey(KEY_TYPE e) { - Node KEY_VALUE_GENERIC_TYPE node = findHigherNode(e); - return node != null ? node.key : getDefaultMaxValue(); - } - - @Override - public KEY_TYPE ceilingKey(KEY_TYPE e) { - Node KEY_VALUE_GENERIC_TYPE node = findCeilingNode(e); - return node != null ? node.key : getDefaultMaxValue(); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE lowerEntry(KEY_TYPE key) { - Node KEY_VALUE_GENERIC_TYPE node = findLowerNode(key); - return node != null ? node.export() : null; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE higherEntry(KEY_TYPE key) { - Node KEY_VALUE_GENERIC_TYPE node = findHigherNode(key); - return node != null ? node.export() : null; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE floorEntry(KEY_TYPE key) { - Node KEY_VALUE_GENERIC_TYPE node = findFloorNode(key); - return node != null ? node.export() : null; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE ceilingEntry(KEY_TYPE key) { - Node KEY_VALUE_GENERIC_TYPE node = findCeilingNode(key); - return node != null ? node.export() : null; - } - - protected Node KEY_VALUE_GENERIC_TYPE findLowerNode(KEY_TYPE key) { - Node KEY_VALUE_GENERIC_TYPE entry = tree; - while(entry != null) { - if(compare(key, entry.key) > 0) { - if(entry.right != null) entry = entry.right; - else return entry; - } - else { - if(entry.left != null) entry = entry.left; - else { - Node KEY_VALUE_GENERIC_TYPE parent = entry.parent; - while(parent != null && parent.left == entry) { - entry = parent; - parent = parent.parent; - } - return parent; - } - } - } - return null; - } - - protected Node KEY_VALUE_GENERIC_TYPE findFloorNode(KEY_TYPE key) { - Node KEY_VALUE_GENERIC_TYPE entry = tree; - int compare; - while(entry != null) { - if((compare = compare(key, entry.key)) > 0) { - if(entry.right == null) break; - entry = entry.right; - continue; - } - else if(compare < 0) { - if(entry.left != null) entry = entry.left; - else { - Node KEY_VALUE_GENERIC_TYPE parent = entry.parent; - while(parent != null && parent.left == entry) { - entry = parent; - parent = parent.parent; - } - return parent; - } - continue; - } - break; - } - return entry; - } - - protected Node KEY_VALUE_GENERIC_TYPE findCeilingNode(KEY_TYPE key) { - Node KEY_VALUE_GENERIC_TYPE entry = tree; - int compare; - while(entry != null) { - if((compare = compare(key, entry.key)) < 0) { - if(entry.left == null) break; - entry = entry.left; - continue; - } - else if(compare > 0) { - if(entry.right != null) entry = entry.right; - else { - Node KEY_VALUE_GENERIC_TYPE parent = entry.parent; - while(parent != null && parent.right == entry) { - entry = parent; - parent = parent.parent; - } - return parent; - } - continue; - } - break; - } - return entry; - } - - protected Node KEY_VALUE_GENERIC_TYPE findHigherNode(KEY_TYPE key) { - Node KEY_VALUE_GENERIC_TYPE entry = tree; - while(entry != null) { - if(compare(key, entry.key) < 0) { - if(entry.left != null) entry = entry.left; - else return entry; - } - else { - if(entry.right != null) entry = entry.right; - else { - Node KEY_VALUE_GENERIC_TYPE parent = entry.parent; - while(parent != null && parent.right == entry) { - entry = parent; - parent = parent.parent; - } - return parent; - } - } - } - return null; - } - - protected Node KEY_VALUE_GENERIC_TYPE findNode(KEY_TYPE key) { - Node KEY_VALUE_GENERIC_TYPE node = tree; - int compare; - while(node != null) { - if((compare = compare(key, node.key)) == 0) return node; - if(compare < 0) node = node.left; - else node = node.right; - } - return null; - } - - protected void removeNode(Node KEY_VALUE_GENERIC_TYPE entry) { - size--; - if(entry.needsSuccessor()) { - Node KEY_VALUE_GENERIC_TYPE successor = entry.next(); - entry.key = successor.key; - entry.value = successor.value; - entry = successor; - } - Node KEY_VALUE_GENERIC_TYPE replacement = entry.left != null ? entry.left : entry.right; - if(replacement != null) { - if(entry.replace(replacement)) tree = replacement; - if(entry == first) first = replacement; - if(entry == last) last = entry.right != null ? entry.right : replacement; - entry.left = entry.right = entry.parent = null; - if(entry.isBlack()) fixAfterDeletion(replacement); - } - else if(entry.parent == null) tree = first = last = null; - else { - if(entry.isBlack()) - fixAfterDeletion(entry); - entry.replace(null); - if(entry.parent != null) { - Node KEY_VALUE_GENERIC_TYPE parent = entry.parent; - if(entry == first) first = parent.left != null ? parent.left : parent; - if(entry == last) last = entry.right != null ? parent.right : parent; - } - entry.parent = null; - } - } - - protected void validate(KEY_TYPE k) { compare(k, k); } - protected int compare(KEY_TYPE k, KEY_TYPE v) { return comparator != null ? comparator.compare(k, v) : COMPAREABLE_TO_KEY(k, v);} - protected static GENERIC_KEY_VALUE_BRACES boolean isBlack(Node KEY_VALUE_GENERIC_TYPE p) { return p == null || p.isBlack(); } - protected static GENERIC_KEY_VALUE_BRACES Node KEY_VALUE_GENERIC_TYPE parentOf(Node KEY_VALUE_GENERIC_TYPE p) { return (p == null ? null : p.parent); } - protected static GENERIC_KEY_VALUE_BRACES void setBlack(Node KEY_VALUE_GENERIC_TYPE p, boolean c) { if(p != null) p.setBlack(c); } - protected static GENERIC_KEY_VALUE_BRACES Node KEY_VALUE_GENERIC_TYPE leftOf(Node KEY_VALUE_GENERIC_TYPE p) { return p == null ? null : p.left; } - protected static GENERIC_KEY_VALUE_BRACES Node KEY_VALUE_GENERIC_TYPE rightOf(Node KEY_VALUE_GENERIC_TYPE p) { return (p == null) ? null : p.right; } - - protected void rotateLeft(Node KEY_VALUE_GENERIC_TYPE entry) { - if(entry != null) { - Node KEY_VALUE_GENERIC_TYPE right = entry.right; - entry.right = right.left; - if(right.left != null) right.left.parent = entry; - right.parent = entry.parent; - if(entry.parent == null) tree = right; - else if(entry.parent.left == entry) entry.parent.left = right; - else entry.parent.right = right; - right.left = entry; - entry.parent = right; - } - } - - protected void rotateRight(Node KEY_VALUE_GENERIC_TYPE entry) { - if(entry != null) { - Node KEY_VALUE_GENERIC_TYPE left = entry.left; - entry.left = left.right; - if(left.right != null) left.right.parent = entry; - left.parent = entry.parent; - if(entry.parent == null) tree = left; - else if(entry.parent.right == entry) entry.parent.right = left; - else entry.parent.left = left; - left.right = entry; - entry.parent = left; - } - } - - protected void fixAfterInsertion(Node KEY_VALUE_GENERIC_TYPE entry) { - entry.setBlack(false); - while(entry != null && entry != tree && !entry.parent.isBlack()) { - if(parentOf(entry) == leftOf(parentOf(parentOf(entry)))) { - Node KEY_VALUE_GENERIC_TYPE y = rightOf(parentOf(parentOf(entry))); - if(!isBlack(y)) { - setBlack(parentOf(entry), true); - setBlack(y, true); - setBlack(parentOf(parentOf(entry)), false); - entry = parentOf(parentOf(entry)); - } - else { - if(entry == rightOf(parentOf(entry))) { - entry = parentOf(entry); - rotateLeft(entry); - } - setBlack(parentOf(entry), true); - setBlack(parentOf(parentOf(entry)), false); - rotateRight(parentOf(parentOf(entry))); - } - } - else { - Node KEY_VALUE_GENERIC_TYPE y = leftOf(parentOf(parentOf(entry))); - if(!isBlack(y)) { - setBlack(parentOf(entry), true); - setBlack(y, true); - setBlack(parentOf(parentOf(entry)), false); - entry = parentOf(parentOf(entry)); - } - else { - if(entry == leftOf(parentOf(entry))) { - entry = parentOf(entry); - rotateRight(entry); - } - setBlack(parentOf(entry), true); - setBlack(parentOf(parentOf(entry)), false); - rotateLeft(parentOf(parentOf(entry))); - } - } - } - tree.setBlack(true); - } - - protected void fixAfterDeletion(Node KEY_VALUE_GENERIC_TYPE entry) { - while(entry != tree && isBlack(entry)) { - if(entry == leftOf(parentOf(entry))) { - Node KEY_VALUE_GENERIC_TYPE sib = rightOf(parentOf(entry)); - if(!isBlack(sib)) { - setBlack(sib, true); - setBlack(parentOf(entry), false); - rotateLeft(parentOf(entry)); - sib = rightOf(parentOf(entry)); - } - if(isBlack(leftOf(sib)) && isBlack(rightOf(sib))) { - setBlack(sib, false); - entry = parentOf(entry); - } - else { - if(isBlack(rightOf(sib))) { - setBlack(leftOf(sib), true); - setBlack(sib, false); - rotateRight(sib); - sib = rightOf(parentOf(entry)); - } - setBlack(sib, isBlack(parentOf(entry))); - setBlack(parentOf(entry), true); - setBlack(rightOf(sib), true); - rotateLeft(parentOf(entry)); - entry = tree; - } - } - else { - Node KEY_VALUE_GENERIC_TYPE sib = leftOf(parentOf(entry)); - if(!isBlack(sib)) { - setBlack(sib, true); - setBlack(parentOf(entry), false); - rotateRight(parentOf(entry)); - sib = leftOf(parentOf(entry)); - } - if(isBlack(rightOf(sib)) && isBlack(leftOf(sib))) { - setBlack(sib, false); - entry = parentOf(entry); - } - else { - if(isBlack(leftOf(sib))) { - setBlack(rightOf(sib), true); - setBlack(sib, false); - rotateLeft(sib); - sib = leftOf(parentOf(entry)); - } - setBlack(sib, isBlack(parentOf(entry))); - setBlack(parentOf(entry), true); - setBlack(leftOf(sib), true); - rotateRight(parentOf(entry)); - entry = tree; - } - } - } - setBlack(entry, true); - } - - static class KeySet KEY_VALUE_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE implements NAVIGABLE_SET KEY_GENERIC_TYPE - { - NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map; - - public KeySet(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map) { - this.map = map; - } - -#if !TYPE_OBJECT - @Override - public void setDefaultMaxValue(KEY_TYPE e) { map.setDefaultMaxValue(e); } - @Override - public KEY_TYPE getDefaultMaxValue() { return map.getDefaultMaxValue(); } - @Override - public void setDefaultMinValue(KEY_TYPE e) { map.setDefaultMinValue(e); } - @Override - public KEY_TYPE getDefaultMinValue() { return map.getDefaultMinValue(); } -#endif - @Override - public KEY_TYPE lower(KEY_TYPE e) { return map.lowerKey(e); } - @Override - public KEY_TYPE floor(KEY_TYPE e) { return map.floorKey(e); } - @Override - public KEY_TYPE ceiling(KEY_TYPE e) { return map.ceilingKey(e); } - @Override - public KEY_TYPE higher(KEY_TYPE e) { return map.higherKey(e); } - -#if !TYPE_OBJECT - @Override - public CLASS_TYPE lower(CLASS_TYPE e) { - MAP.Entry KEY_VALUE_GENERIC_TYPE node = map.lowerEntry(OBJ_TO_KEY(e)); - return node != null ? node.getKey() : null; - } - - @Override - public CLASS_TYPE floor(CLASS_TYPE e) { - MAP.Entry KEY_VALUE_GENERIC_TYPE node = map.floorEntry(OBJ_TO_KEY(e)); - return node != null ? node.getKey() : null; - } - - @Override - public CLASS_TYPE higher(CLASS_TYPE e) { - MAP.Entry KEY_VALUE_GENERIC_TYPE node = map.higherEntry(OBJ_TO_KEY(e)); - return node != null ? node.getKey() : null; - } - - @Override - public CLASS_TYPE ceiling(CLASS_TYPE e) { - MAP.Entry KEY_VALUE_GENERIC_TYPE node = map.ceilingEntry(OBJ_TO_KEY(e)); - return node != null ? node.getKey() : null; - } - -#endif - @Override - public KEY_TYPE POLL_FIRST_KEY() { return map.POLL_FIRST_ENTRY_KEY(); } - @Override - public KEY_TYPE POLL_LAST_KEY() { return map.POLL_LAST_ENTRY_KEY(); } - @Override - public COMPARATOR KEY_GENERIC_TYPE comparator() { return map.comparator(); } - @Override - public KEY_TYPE FIRST_KEY() { return map.FIRST_ENTRY_KEY(); } - @Override - public KEY_TYPE LAST_KEY() { return map.LAST_ENTRY_KEY(); } - @Override - public void clear() { map.clear(); } - -#if TYPE_OBJECT - @Override - public boolean remove(Object o) { - int oldSize = map.size(); - map.remove(o); - return oldSize != map.size(); - } - -#else - @Override - public boolean remove(KEY_TYPE o) { - int oldSize = map.size(); - map.remove(o); - return oldSize != map.size(); - } - -#endif - @Override - public boolean add(KEY_TYPE e) { throw new UnsupportedOperationException(); } - @Override - public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { - if(map instanceof RB_TREE_MAP) return ((RB_TREE_MAP KEY_VALUE_GENERIC_TYPE)map).keyIterator(fromElement); - return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).keyIterator(fromElement); - } - - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, boolean fromInclusive, KEY_TYPE toElement, boolean toInclusive) { return new KeySetKV_BRACES(map.subMap(fromElement, fromInclusive, toElement, toInclusive)); } - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement, boolean inclusive) { return new KeySetKV_BRACES(map.headMap(toElement, inclusive)); } - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement, boolean inclusive) { return new KeySetKV_BRACES(map.tailMap(fromElement, inclusive)); } - - @Override - public BI_ITERATOR KEY_GENERIC_TYPE iterator() { - if(map instanceof RB_TREE_MAP) return ((RB_TREE_MAP KEY_VALUE_GENERIC_TYPE)map).keyIterator(); - return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).keyIterator(); - } - - @Override - public BI_ITERATOR KEY_GENERIC_TYPE descendingIterator() { - if(map instanceof RB_TREE_MAP) return ((RB_TREE_MAP KEY_VALUE_GENERIC_TYPE)map).descendingKeyIterator(); - return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).descendingKeyIterator(); - } - - protected Node KEY_VALUE_GENERIC_TYPE start() { - if(map instanceof RB_TREE_MAP) return ((RB_TREE_MAP KEY_VALUE_GENERIC_TYPE)map).first; - return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).subLowest(); - } - - protected Node KEY_VALUE_GENERIC_TYPE end() { - if(map instanceof RB_TREE_MAP) return null; - return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).subHighest(); - } - - protected Node KEY_VALUE_GENERIC_TYPE next(Node KEY_VALUE_GENERIC_TYPE entry) { - if(map instanceof RB_TREE_MAP) return entry.next(); - return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).next(entry); - } - - protected Node KEY_VALUE_GENERIC_TYPE previous(Node KEY_VALUE_GENERIC_TYPE entry) { - if(map instanceof RB_TREE_MAP) return entry.previous(); - return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).previous(entry); - } - - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE descendingSet() { return new KeySetKV_BRACES(map.descendingMap()); } - @Override - public KeySet KEY_VALUE_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); } - @Override - public boolean isEmpty() { return map.isEmpty(); } - @Override - public int size() { return map.size(); } - - @Override - public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { - Objects.requireNonNull(action); - for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) - action.accept(entry.key); - } - - @Override - public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) { - Objects.requireNonNull(action); - int index = 0; - for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) - action.accept(index++, entry.key); - } - - @Override - public void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { - Objects.requireNonNull(action); - for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) - action.accept(input, entry.key); - } - - @Override - public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) - if(filter.test(entry.key)) return true; - return false; - } - - @Override - public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) - if(filter.test(entry.key)) return false; - return true; - } - - @Override - public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) - if(!filter.test(entry.key)) return false; - return true; - } - -#if !TYPE_OBJECT - @Override - public KEY_TYPE reduce(KEY_TYPE identity, SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - KEY_TYPE state = identity; - for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) - state = operator.APPLY_KEY_VALUE(state, entry.key); - return state; - } - -#else - @Override - public KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) { - Objects.requireNonNull(operator); - KEY_SPECIAL_TYPE state = identity; - for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) - state = operator.apply(state, entry.key); - return state; - } - -#endif - @Override - public KEY_TYPE reduce(SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - KEY_TYPE state = EMPTY_KEY_VALUE; - boolean empty = true; - for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) { - if(empty) { - empty = false; - state = entry.key; - continue; - } - state = operator.APPLY_KEY_VALUE(state, entry.key); - } - return state; - } - - @Override - public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) - if(filter.test(entry.key)) return entry.key; - return EMPTY_KEY_VALUE; - } - - @Override - public int count(PREDICATE KEY_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - int result = 0; - for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) - if(filter.test(entry.key)) result++; - return result; - } - } - - static class AscendingNaivgableSubMap KEY_VALUE_GENERIC_TYPE extends NavigableSubMap KEY_VALUE_GENERIC_TYPE - { - AscendingNaivgableSubMap(RB_TREE_MAP KEY_VALUE_GENERIC_TYPE map, boolean fromStart, KEY_TYPE lo, boolean loInclusive, boolean toEnd, KEY_TYPE hi, boolean hiInclusive) { - super(map, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); - } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap() { - if(inverse == null) inverse = new DescendingNaivgableSubMapKV_BRACES(map, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); - return inverse; - } - - @Override - public ObjectSet ENTRY_SET() { - if(entrySet == null) entrySet = new AscendingSubEntrySet(); - return entrySet; - } - - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE navigableKeySet() { - if(keySet == null) keySet = new KeySetKV_BRACES(this); - return keySet; - } - - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE keySet() { - return navigableKeySet(); - } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, boolean fromInclusive, KEY_TYPE toKey, boolean toInclusive) { - if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range"); - if (!inRange(toKey, toInclusive)) throw new IllegalArgumentException("toKey out of range"); - return new AscendingNaivgableSubMapKV_BRACES(map, false, fromKey, fromInclusive, false, toKey, toInclusive); - } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey, boolean inclusive) { - if (!inRange(toKey, inclusive)) throw new IllegalArgumentException("toKey out of range"); - return new AscendingNaivgableSubMapKV_BRACES(map, fromStart, lo, loInclusive, false, toKey, inclusive); - } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey, boolean inclusive) { - if (!inRange(fromKey, inclusive)) throw new IllegalArgumentException("fromKey out of range"); - return new AscendingNaivgableSubMapKV_BRACES(map, false, fromKey, inclusive, toEnd, hi, hiInclusive); - } - - @Override - protected Node KEY_VALUE_GENERIC_TYPE subLowest() { return absLowest(); } - @Override - protected Node KEY_VALUE_GENERIC_TYPE subHighest() { return absHighest(); } - @Override - protected Node KEY_VALUE_GENERIC_TYPE subCeiling(KEY_TYPE key) { return absCeiling(key); } - @Override - protected Node KEY_VALUE_GENERIC_TYPE subHigher(KEY_TYPE key) { return absHigher(key); } - @Override - protected Node KEY_VALUE_GENERIC_TYPE subFloor(KEY_TYPE key) { return absFloor(key); } - @Override - protected Node KEY_VALUE_GENERIC_TYPE subLower(KEY_TYPE key) { return absLower(key); } - - @Override - protected BI_ITERATOR KEY_GENERIC_TYPE keyIterator() { - return new AcsendingSubKeyIterator(absLowest(), absHighFence(), absLowFence()); - } - @Override - protected BI_ITERATOR KEY_GENERIC_TYPE keyIterator(KEY_TYPE element) { - return new AcsendingSubKeyIterator(absLower(element), absHighFence(), absLowFence()); - } - - @Override - protected VALUE_BI_ITERATOR VALUE_GENERIC_TYPE valueIterator() { - return new AcsendingSubValueIterator(absLowest(), absHighFence(), absLowFence()); - } - - @Override - protected BI_ITERATOR KEY_GENERIC_TYPE descendingKeyIterator() { - return new DecsendingSubKeyIterator(absHighest(), absLowFence(), absHighFence()); - } - - class AscendingSubEntrySet extends SubEntrySet { - @Override - public ObjectIterator iterator() { - return new AcsendingSubEntryIterator(absLowest(), absHighFence(), absLowFence()); - } - } - } - - static class DescendingNaivgableSubMap KEY_VALUE_GENERIC_TYPE extends NavigableSubMap KEY_VALUE_GENERIC_TYPE - { - COMPARATOR KEY_GENERIC_TYPE comparator; - DescendingNaivgableSubMap(RB_TREE_MAP KEY_VALUE_GENERIC_TYPE map, boolean fromStart, KEY_TYPE lo, boolean loInclusive, boolean toEnd, KEY_TYPE hi, boolean hiInclusive) { - super(map, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); -#if TYPE_OBJECT - comparator = Collections.reverseOrder(map.comparator()); -#else - comparator = map.comparator() == null ? COMPARATOR.of(Collections.reverseOrder()) : map.comparator().reversed(); -#endif - } - - @Override - public COMPARATOR KEY_GENERIC_TYPE comparator() { return comparator; } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap() { - if(inverse == null) inverse = new AscendingNaivgableSubMapKV_BRACES(map, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); - return inverse; - } - - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE navigableKeySet() { - if(keySet == null) keySet = new KeySetKV_BRACES(this); - return keySet; - } - - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE keySet() { - return navigableKeySet(); - } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, boolean fromInclusive, KEY_TYPE toKey, boolean toInclusive) { - if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range"); - if (!inRange(toKey, toInclusive)) throw new IllegalArgumentException("toKey out of range"); - return new DescendingNaivgableSubMapKV_BRACES(map, false, toKey, toInclusive, false, fromKey, fromInclusive); - } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey, boolean inclusive) { - if (!inRange(toKey, inclusive)) throw new IllegalArgumentException("toKey out of range"); - return new DescendingNaivgableSubMapKV_BRACES(map, false, toKey, inclusive, toEnd, hi, hiInclusive); - } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey, boolean inclusive) { - if (!inRange(fromKey, inclusive)) throw new IllegalArgumentException("fromKey out of range"); - return new DescendingNaivgableSubMapKV_BRACES(map, fromStart, lo, loInclusive, false, fromKey, inclusive); - } - - @Override - public ObjectSet ENTRY_SET() { - if(entrySet == null) entrySet = new DescendingSubEntrySet(); - return entrySet; - } - - @Override - protected Node KEY_VALUE_GENERIC_TYPE subLowest() { return absHighest(); } - @Override - protected Node KEY_VALUE_GENERIC_TYPE subHighest() { return absLowest(); } - @Override - protected Node KEY_VALUE_GENERIC_TYPE subCeiling(KEY_TYPE key) { return absFloor(key); } - @Override - protected Node KEY_VALUE_GENERIC_TYPE subHigher(KEY_TYPE key) { return absLower(key); } - @Override - protected Node KEY_VALUE_GENERIC_TYPE subFloor(KEY_TYPE key) { return absCeiling(key); } - @Override - protected Node KEY_VALUE_GENERIC_TYPE subLower(KEY_TYPE key) { return absHigher(key); } - @Override - protected Node KEY_VALUE_GENERIC_TYPE next(Node KEY_VALUE_GENERIC_TYPE entry) { return entry.previous(); } - @Override - protected Node KEY_VALUE_GENERIC_TYPE previous(Node KEY_VALUE_GENERIC_TYPE entry) { return entry.next(); } - - @Override - protected BI_ITERATOR KEY_GENERIC_TYPE keyIterator() { - return new DecsendingSubKeyIterator(absHighest(), absLowFence(), absHighFence()); - } - - @Override - protected BI_ITERATOR KEY_GENERIC_TYPE keyIterator(KEY_TYPE element) { - return new DecsendingSubKeyIterator(absHigher(element), absLowFence(), absHighFence()); - } - - @Override - protected VALUE_BI_ITERATOR VALUE_GENERIC_TYPE valueIterator() { - return new DecsendingSubValueIterator(absHighest(), absLowFence(), absHighFence()); - } - - @Override - protected BI_ITERATOR KEY_GENERIC_TYPE descendingKeyIterator() { - return new AcsendingSubKeyIterator(absLowest(), absHighFence(), absLowFence()); - } - - class DescendingSubEntrySet extends SubEntrySet { - @Override - public ObjectIterator iterator() { - return new DecsendingSubEntryIterator(absHighest(), absLowFence(), absHighFence()); - } - } - } - - static abstract class NavigableSubMap KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE - { - final RB_TREE_MAP KEY_VALUE_GENERIC_TYPE map; - final KEY_TYPE lo, hi; - final boolean fromStart, toEnd; - final boolean loInclusive, hiInclusive; - - NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE inverse; - NAVIGABLE_SET KEY_GENERIC_TYPE keySet; - ObjectSet entrySet; - VALUE_COLLECTION VALUE_GENERIC_TYPE values; - - NavigableSubMap(RB_TREE_MAP KEY_VALUE_GENERIC_TYPE map, boolean fromStart, KEY_TYPE lo, boolean loInclusive, boolean toEnd, KEY_TYPE hi, boolean hiInclusive) { - if (!fromStart && !toEnd) { - if (map.compare(lo, hi) > 0) throw new IllegalArgumentException("fromKey > toKey"); - } - else { - if (!fromStart) map.validate(lo); - if (!toEnd) map.validate(hi); - } - this.map = map; - this.fromStart = fromStart; - this.lo = lo; - this.loInclusive = loInclusive; - this.toEnd = toEnd; - this.hi = hi; - this.hiInclusive = hiInclusive; - } - -#if TYPE_OBJECT - public KEY_TYPE getDefaultMaxValue() { return map.getDefaultMaxValue(); } - public KEY_TYPE getDefaultMinValue() { return map.getDefaultMinValue(); } -#else - @Override - public void setDefaultMaxValue(KEY_TYPE e) { map.setDefaultMaxValue(e); } - @Override - public KEY_TYPE getDefaultMaxValue() { return map.getDefaultMaxValue(); } - @Override - public void setDefaultMinValue(KEY_TYPE e) { map.setDefaultMinValue(e); } - @Override - public KEY_TYPE getDefaultMinValue() { return map.getDefaultMinValue(); } -#endif - protected boolean isNullComparator() { return map.comparator() == null; } - - @Override - public ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE setDefaultReturnValue(VALUE_TYPE v) { - map.setDefaultReturnValue(v); - return this; - } - - @Override - public VALUE_TYPE getDefaultReturnValue() { return map.getDefaultReturnValue(); } - - @Override - public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { - if(values == null) values = new SubMapValues(); - return values; - } - - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE descendingKeySet() { - return descendingMap().navigableKeySet(); - } - - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE keySet() { - return navigableKeySet(); - } - - protected abstract Node KEY_VALUE_GENERIC_TYPE subLowest(); - protected abstract Node KEY_VALUE_GENERIC_TYPE subHighest(); - protected abstract Node KEY_VALUE_GENERIC_TYPE subCeiling(KEY_TYPE key); - protected abstract Node KEY_VALUE_GENERIC_TYPE subHigher(KEY_TYPE key); - protected abstract Node KEY_VALUE_GENERIC_TYPE subFloor(KEY_TYPE key); - protected abstract Node KEY_VALUE_GENERIC_TYPE subLower(KEY_TYPE key); - protected abstract BI_ITERATOR KEY_GENERIC_TYPE keyIterator(); - protected abstract BI_ITERATOR KEY_GENERIC_TYPE keyIterator(KEY_TYPE element); - protected abstract VALUE_BI_ITERATOR VALUE_GENERIC_TYPE valueIterator(); - protected abstract BI_ITERATOR KEY_GENERIC_TYPE descendingKeyIterator(); - protected KEY_TYPE lowKeyOrNull(Node KEY_VALUE_GENERIC_TYPE entry) { return entry == null ? getDefaultMinValue() : entry.key; } - protected KEY_TYPE highKeyOrNull(Node KEY_VALUE_GENERIC_TYPE entry) { return entry == null ? getDefaultMaxValue() : entry.key; } - protected Node KEY_VALUE_GENERIC_TYPE next(Node KEY_VALUE_GENERIC_TYPE entry) { return entry.next(); } - protected Node KEY_VALUE_GENERIC_TYPE previous(Node KEY_VALUE_GENERIC_TYPE entry) { return entry.previous(); } - - protected boolean tooLow(KEY_TYPE key) { - if (!fromStart) { - int c = map.compare(key, lo); - if (c < 0 || (c == 0 && !loInclusive)) return true; - } - return false; - } - - protected boolean tooHigh(KEY_TYPE key) { - if (!toEnd) { - int c = map.compare(key, hi); - if (c > 0 || (c == 0 && !hiInclusive)) return true; - } - return false; - } - protected boolean inRange(KEY_TYPE key) { return !tooLow(key) && !tooHigh(key); } - protected boolean inClosedRange(KEY_TYPE key) { return (fromStart || map.compare(key, lo) >= 0) && (toEnd || map.compare(hi, key) >= 0); } - protected boolean inRange(KEY_TYPE key, boolean inclusive) { return inclusive ? inRange(key) : inClosedRange(key); } - - protected Node KEY_VALUE_GENERIC_TYPE absLowest() { - Node KEY_VALUE_GENERIC_TYPE e = (fromStart ? map.first : (loInclusive ? map.findCeilingNode(lo) : map.findHigherNode(lo))); - return (e == null || tooHigh(e.key)) ? null : e; - } - - protected Node KEY_VALUE_GENERIC_TYPE absHighest() { - Node KEY_VALUE_GENERIC_TYPE e = (toEnd ? map.last : (hiInclusive ? map.findFloorNode(hi) : map.findLowerNode(hi))); - return (e == null || tooLow(e.key)) ? null : e; - } - - protected Node KEY_VALUE_GENERIC_TYPE absCeiling(KEY_TYPE key) { - if (tooLow(key)) return absLowest(); - Node KEY_VALUE_GENERIC_TYPE e = map.findCeilingNode(key); - return (e == null || tooHigh(e.key)) ? null : e; - } - - protected Node KEY_VALUE_GENERIC_TYPE absHigher(KEY_TYPE key) { - if (tooLow(key)) return absLowest(); - Node KEY_VALUE_GENERIC_TYPE e = map.findHigherNode(key); - return (e == null || tooHigh(e.key)) ? null : e; - } - - protected Node KEY_VALUE_GENERIC_TYPE absFloor(KEY_TYPE key) { - if (tooHigh(key)) return absHighest(); - Node KEY_VALUE_GENERIC_TYPE e = map.findFloorNode(key); - return (e == null || tooLow(e.key)) ? null : e; - } - - protected Node KEY_VALUE_GENERIC_TYPE absLower(KEY_TYPE key) { - if (tooHigh(key)) return absHighest(); - Node KEY_VALUE_GENERIC_TYPE e = map.findLowerNode(key); - return (e == null || tooLow(e.key)) ? null : e; - } - - protected Node KEY_VALUE_GENERIC_TYPE absHighFence() { return (toEnd ? null : (hiInclusive ? map.findHigherNode(hi) : map.findCeilingNode(hi))); } - protected Node KEY_VALUE_GENERIC_TYPE absLowFence() { return (fromStart ? null : (loInclusive ? map.findLowerNode(lo) : map.findFloorNode(lo))); } - - @Override - public COMPARATOR KEY_GENERIC_TYPE comparator() { return map.comparator(); } - - @Override - public KEY_TYPE POLL_FIRST_ENTRY_KEY() { - Node KEY_VALUE_GENERIC_TYPE entry = subLowest(); - if(entry != null) { - KEY_TYPE result = entry.key; - map.removeNode(entry); - return result; - } - return getDefaultMinValue(); - } - - @Override - public KEY_TYPE POLL_LAST_ENTRY_KEY() { - Node KEY_VALUE_GENERIC_TYPE entry = subHighest(); - if(entry != null) { - KEY_TYPE result = entry.key; - map.removeNode(entry); - return result; - } - return getDefaultMaxValue(); - } - - @Override - public VALUE_TYPE FIRST_ENTRY_VALUE() { - Node KEY_VALUE_GENERIC_TYPE entry = subLowest(); - if(entry == null) throw new NoSuchElementException(); - return entry.value; - } - - @Override - public VALUE_TYPE LAST_ENTRY_VALUE() { - Node KEY_VALUE_GENERIC_TYPE entry = subHighest(); - if(entry == null) throw new NoSuchElementException(); - return entry.value; - } - - @Override - public KEY_TYPE FIRST_ENTRY_KEY() { - Node KEY_VALUE_GENERIC_TYPE entry = subLowest(); - if(entry == null) throw new NoSuchElementException(); - return entry.key; - } - - @Override - public KEY_TYPE LAST_ENTRY_KEY() { - Node KEY_VALUE_GENERIC_TYPE entry = subHighest(); - if(entry == null) throw new NoSuchElementException(); - return entry.key; - } - - @Override - public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { - if (!inRange(key)) throw new IllegalArgumentException("key out of range"); - return map.put(key, value); - } - - @Override - public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { - if (!inRange(key)) throw new IllegalArgumentException("key out of range"); - return map.putIfAbsent(key, value); - } - -#if VALUE_PRIMITIVES - @Override - public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { - if(!inRange(key)) throw new IllegalArgumentException("key out of range"); - return map.addTo(key, value); - } - - @Override - public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { - if(!inRange(key)) throw new IllegalArgumentException("key out of range"); - return map.subFrom(key, value); - } - -#endif -#if TYPE_OBJECT - @Override - public boolean containsKey(Object key) { return inRange((CLASS_TYPE)key) && map.containsKey(key); } -#else - @Override - public boolean containsKey(KEY_TYPE key) { return inRange(key) && map.containsKey(key); } - -#endif - @Override - public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { - Objects.requireNonNull(mappingFunction); -#if TYPE_OBJECT - map.validate(key); -#endif - if(!inRange(key)) return getDefaultReturnValue(); - Node KEY_VALUE_GENERIC_TYPE entry = map.findNode(key); - if(entry == null || VALUE_EQUALS(entry.value, getDefaultReturnValue())) return getDefaultReturnValue(); - VALUE_TYPE newValue = mappingFunction.apply(key, entry.value); - if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { - map.removeNode(entry); - return newValue; - } - entry.value = newValue; - return newValue; - } - - @Override - public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { - return inRange(key) ? map.REMOVE_VALUE(key) : getDefaultReturnValue(); - } - - @Override - public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { - return inRange(key) ? map.REMOVE_VALUEOrDefault(key, defaultValue) : defaultValue; - } - -#if TYPE_OBJECT && VALUE_OBJECT - @Override - public boolean remove(Object key, Object value) { - return inRange((CLASS_TYPE)key) && map.remove(key, value); - } - -#else - @Override - public boolean remove(KEY_TYPE key, VALUE_TYPE value) { - return inRange(key) && map.remove(key, value); - } - -#endif - - @Override - public VALUE_TYPE GET_VALUE(KEY_TYPE key) { - return inRange(key) ? map.GET_VALUE(key) : getDefaultReturnValue(); - } - -#if TYPE_OBJECT && VALUE_OBJECT - @Override - public VALUE_TYPE getOrDefault(Object key, VALUE_TYPE defaultValue) { - return inRange((CLASS_TYPE)key) ? map.getOrDefault(key, defaultValue) : getDefaultReturnValue(); - } - -#else - @Override - public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { - return inRange(key) ? map.getOrDefault(key, defaultValue) : getDefaultReturnValue(); - } - -#endif - - @Override - public KEY_TYPE lowerKey(KEY_TYPE key) { return lowKeyOrNull(subLower(key)); } - @Override - public KEY_TYPE floorKey(KEY_TYPE key) { return lowKeyOrNull(subFloor(key)); } - @Override - public KEY_TYPE ceilingKey(KEY_TYPE key) { return highKeyOrNull(subCeiling(key)); } - @Override - public KEY_TYPE higherKey(KEY_TYPE key) { return highKeyOrNull(subHigher(key)); } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE lowerEntry(KEY_TYPE key) { return subLower(key); } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE floorEntry(KEY_TYPE key) { return subFloor(key); } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE ceilingEntry(KEY_TYPE key) { return subCeiling(key); } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE higherEntry(KEY_TYPE key) { return subHigher(key); } - - @Override - public boolean isEmpty() { - if(fromStart && toEnd) return map.isEmpty(); - Node KEY_VALUE_GENERIC_TYPE n = absLowest(); - return n == null || tooHigh(n.key); - } - - @Override - public int size() { return fromStart && toEnd ? map.size() : entrySet().size(); } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE firstEntry() { - Node KEY_VALUE_GENERIC_TYPE entry = subLowest(); - return entry == null ? null : entry.export(); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE lastEntry() { - Node KEY_VALUE_GENERIC_TYPE entry = subHighest(); - return entry == null ? null : entry.export(); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirstEntry() { - Node KEY_VALUE_GENERIC_TYPE entry = subLowest(); - if(entry != null) { - MAP.Entry KEY_VALUE_GENERIC_TYPE result = entry.export(); - map.removeNode(entry); - return result; - } - return null; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLastEntry() { - Node KEY_VALUE_GENERIC_TYPE entry = subHighest(); - if(entry != null) { - MAP.Entry KEY_VALUE_GENERIC_TYPE result = entry.export(); - map.removeNode(entry); - return result; - } - return null; - } - - abstract class SubEntrySet extends AbstractObjectSet { - @Override - public int size() { - if (fromStart && toEnd) return map.size(); - int size = 0; - for(ObjectIterator iter = iterator();iter.hasNext();iter.next(),size++); - return size; - } - - @Override - public boolean isEmpty() { - Node KEY_VALUE_GENERIC_TYPE n = absLowest(); - return n == null || tooHigh(n.key); - } - - @Override - public boolean contains(Object o) { - if (!(o instanceof Map.Entry)) return false; - if(o instanceof MAP.Entry) - { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE) o; -#if TYPE_OBJECT - if(entry.ENTRY_KEY() == null && isNullComparator()) return false; -#endif - KEY_TYPE key = entry.ENTRY_KEY(); - if (!inRange(key)) return false; - Node KEY_VALUE_GENERIC_TYPE node = map.findNode(key); - return node != null && VALUE_EQUALS(entry.ENTRY_VALUE(), node.ENTRY_VALUE()); - } - Map.Entry entry = (Map.Entry) o; - if(entry.getKey() == null && isNullComparator()) return false; - CLASS_TYPE key = (CLASS_TYPE)entry.getKey(); - if (!inRange(key)) return false; - Node KEY_VALUE_GENERIC_TYPE node = map.findNode(key); - return node != null && Objects.equals(entry.getValue(), VALUE_TO_OBJ(node.ENTRY_VALUE())); - } - - @Override - public boolean remove(Object o) { - if (!(o instanceof Map.Entry)) return false; - if(o instanceof MAP.Entry) - { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE) o; - KEY_TYPE key = entry.ENTRY_KEY(); - if (!inRange(key)) return false; - Node KEY_VALUE_GENERIC_TYPE node = map.findNode(key); - if (node != null && VALUE_EQUALS(node.ENTRY_VALUE(), entry.ENTRY_VALUE())) { - map.removeNode(node); - return true; - } - return false; - } - Map.Entry entry = (Map.Entry) o; - CLASS_TYPE key = (CLASS_TYPE)entry.getKey(); - if (!inRange(key)) return false; - Node KEY_VALUE_GENERIC_TYPE node = map.findNode(key); - if (node != null && Objects.equals(node.getValue(), entry.getValue())) { - map.removeNode(node); - return true; - } - return false; - } - - @Override - public void forEach(Consumer action) { - Objects.requireNonNull(action); - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) - action.accept(new BasicEntryKV_BRACES(entry.key, entry.value)); - } - - @Override - public void forEachIndexed(IntObjectConsumer action) { - Objects.requireNonNull(action); - int index = 0; - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) - action.accept(index++, new BasicEntryKV_BRACES(entry.key, entry.value)); - } - - @Override - public void forEach(E input, ObjectObjectConsumer action) { - Objects.requireNonNull(action); - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) - action.accept(input, new BasicEntryKV_BRACES(entry.key, entry.value)); - } - - @Override - public boolean matchesAny(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return false; - BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { - subEntry.set(entry.key, entry.value); - if(filter.test(subEntry)) return true; - } - return false; - } - - @Override - public boolean matchesNone(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { - subEntry.set(entry.key, entry.value); - if(filter.test(subEntry)) return false; - } - return true; - } - - @Override - public boolean matchesAll(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { - subEntry.set(entry.key, entry.value); - if(!filter.test(subEntry)) return false; - } - return true; - } - - @Override - public E reduce(E identity, BiFunction operator) { - Objects.requireNonNull(operator); - E state = identity; - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { - state = operator.apply(state, new BasicEntryKV_BRACES(entry.key, entry.value)); - } - return state; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE reduce(ObjectObjectUnaryOperator operator) { - Objects.requireNonNull(operator); - MAP.Entry KEY_VALUE_GENERIC_TYPE state = null; - boolean empty = true; - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { - if(empty) { - empty = false; - state = new BasicEntryKV_BRACES(entry.key, entry.value); - continue; - } - state = operator.apply(state, new BasicEntryKV_BRACES(entry.key, entry.value)); - } - return state; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE findFirst(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return null; - BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { - subEntry.set(entry.key, entry.value); - if(filter.test(subEntry)) return subEntry; - } - return null; - } - - @Override - public int count(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return 0; - int result = 0; - BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { - subEntry.set(entry.key, entry.value); - if(filter.test(subEntry)) result++; - } - return result; - } - } - - final class SubMapValues extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { - @Override - public boolean add(VALUE_TYPE o) { throw new UnsupportedOperationException(); } - -#if VALUE_OBJECT - @Override - public boolean contains(Object e) { - return containsValue(e); - } - -#else - @Override - public boolean contains(VALUE_TYPE e) { - return containsValue(e); - } - -#endif - @Override - public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() { return valueIterator(); } - - @Override - public int size() { - return NavigableSubMap.this.size(); - } - - @Override - public void clear() { - NavigableSubMap.this.clear(); - } - - @Override - public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) { - Objects.requireNonNull(action); - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) - action.accept(entry.value); - } - - @Override - public void forEachIndexed(VALUE_BI_FROM_INT_CONSUMER VALUE_GENERIC_TYPE action) { - Objects.requireNonNull(action); - int index = 0; - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) - action.accept(index++, entry.value); - } - - @Override - public void forEach(E input, VALUE_BI_FROM_OBJECT_CONSUMER VSV_GENERIC_TYPE action) { - Objects.requireNonNull(action); - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) - action.accept(input, entry.value); - } - - @Override - public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) - if(filter.test(entry.value)) return true; - return false; - } - - @Override - public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) - if(filter.test(entry.value)) return false; - return true; - } - - @Override - public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) - if(!filter.test(entry.value)) return false; - return true; - } - -#if !VALUE_OBJECT - @Override - public VALUE_TYPE reduce(VALUE_TYPE identity, VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - VALUE_TYPE state = identity; - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) - state = operator.APPLY_VALUE(state, entry.value); - return state; - } - -#else - @Override - public VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction operator) { - Objects.requireNonNull(operator); - VALUE_SPECIAL_TYPE state = identity; - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) - state = operator.apply(state, entry.value); - return state; - } - -#endif - @Override - public VALUE_TYPE reduce(VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - VALUE_TYPE state = EMPTY_VALUE; - boolean empty = true; - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { - if(empty) { - empty = false; - state = entry.value; - continue; - } - state = operator.APPLY_VALUE(state, entry.value); - } - return state; - } - - @Override - public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) - if(filter.test(entry.value)) return entry.value; - return EMPTY_VALUE; - } - - @Override - public int count(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - int result = 0; - for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) - if(filter.test(entry.value)) result++; - return result; - } - } - - class DecsendingSubEntryIterator extends SubMapEntryIterator implements ObjectBidirectionalIterator - { - public DecsendingSubEntryIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence) { - super(first, forwardFence, backwardFence, false); - } - - @Override - protected Node KEY_VALUE_GENERIC_TYPE moveNext(Node KEY_VALUE_GENERIC_TYPE node) { - return node.previous(); - } - - @Override - protected Node KEY_VALUE_GENERIC_TYPE movePrevious(Node KEY_VALUE_GENERIC_TYPE node) { - return node.next(); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { - if(!hasPrevious()) throw new NoSuchElementException(); - return previousEntry(); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { - if(!hasNext()) throw new NoSuchElementException(); - return nextEntry(); - } - } - - class AcsendingSubEntryIterator extends SubMapEntryIterator implements ObjectBidirectionalIterator - { - public AcsendingSubEntryIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence) { - super(first, forwardFence, backwardFence, true); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { - if(!hasPrevious()) throw new NoSuchElementException(); - return previousEntry(); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { - if(!hasNext()) throw new NoSuchElementException(); - return nextEntry(); - } - } - - class DecsendingSubKeyIterator extends SubMapEntryIterator implements BI_ITERATOR KEY_GENERIC_TYPE - { - public DecsendingSubKeyIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence) { - super(first, forwardFence, backwardFence, false); - } - - @Override - protected Node KEY_VALUE_GENERIC_TYPE moveNext(Node KEY_VALUE_GENERIC_TYPE node) { - return node.previous(); - } - - @Override - protected Node KEY_VALUE_GENERIC_TYPE movePrevious(Node KEY_VALUE_GENERIC_TYPE node) { - return node.next(); - } - - @Override - public KEY_TYPE PREVIOUS() { - if(!hasPrevious()) throw new NoSuchElementException(); - return previousEntry().key; - } - - @Override - public KEY_TYPE NEXT() { - if(!hasNext()) throw new NoSuchElementException(); - return nextEntry().key; - } - } - - class AcsendingSubKeyIterator extends SubMapEntryIterator implements BI_ITERATOR KEY_GENERIC_TYPE - { - public AcsendingSubKeyIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence) { - super(first, forwardFence, backwardFence, true); - } - - @Override - public KEY_TYPE PREVIOUS() { - if(!hasPrevious()) throw new NoSuchElementException(); - return previousEntry().key; - } - - @Override - public KEY_TYPE NEXT() { - if(!hasNext()) throw new NoSuchElementException(); - return nextEntry().key; - } - } - - class AcsendingSubValueIterator extends SubMapEntryIterator implements VALUE_BI_ITERATOR VALUE_GENERIC_TYPE - { - public AcsendingSubValueIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence) { - super(first, forwardFence, backwardFence, true); - } - - @Override - public VALUE_TYPE VALUE_PREVIOUS() { - if(!hasPrevious()) throw new NoSuchElementException(); - return previousEntry().value; - } - - @Override - public VALUE_TYPE VALUE_NEXT() { - if(!hasNext()) throw new NoSuchElementException(); - return nextEntry().value; - } - } - - class DecsendingSubValueIterator extends SubMapEntryIterator implements VALUE_BI_ITERATOR VALUE_GENERIC_TYPE - { - public DecsendingSubValueIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence) { - super(first, forwardFence, backwardFence, false); - } - - @Override - protected Node KEY_VALUE_GENERIC_TYPE moveNext(Node KEY_VALUE_GENERIC_TYPE node) { - return node.previous(); - } - - @Override - protected Node KEY_VALUE_GENERIC_TYPE movePrevious(Node KEY_VALUE_GENERIC_TYPE node) { - return node.next(); - } - - @Override - public VALUE_TYPE VALUE_PREVIOUS() { - if(!hasPrevious()) throw new NoSuchElementException(); - return previousEntry().value; - } - - @Override - public VALUE_TYPE VALUE_NEXT() { - if(!hasNext()) throw new NoSuchElementException(); - return nextEntry().value; - } - } - - abstract class SubMapEntryIterator - { - final boolean isForward; - boolean wasForward; - Node KEY_VALUE_GENERIC_TYPE lastReturned; - Node KEY_VALUE_GENERIC_TYPE next; - Node KEY_VALUE_GENERIC_TYPE previous; - boolean unboundForwardFence; - boolean unboundBackwardFence; - KEY_TYPE forwardFence; - KEY_TYPE backwardFence; - - public SubMapEntryIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence, boolean isForward) { - next = first; - previous = first == null ? null : movePrevious(first); - this.forwardFence = forwardFence == null ? EMPTY_KEY_VALUE : forwardFence.key; - this.backwardFence = backwardFence == null ? EMPTY_KEY_VALUE : backwardFence.key; - unboundForwardFence = forwardFence == null; - unboundBackwardFence = backwardFence == null; - this.isForward = isForward; - } - - protected Node KEY_VALUE_GENERIC_TYPE moveNext(Node KEY_VALUE_GENERIC_TYPE node) { - return node.next(); - } - - protected Node KEY_VALUE_GENERIC_TYPE movePrevious(Node KEY_VALUE_GENERIC_TYPE node) { - return node.previous(); - } - - public boolean hasNext() { - return next != null && (unboundForwardFence || next.key != forwardFence); - } - - protected Node KEY_VALUE_GENERIC_TYPE nextEntry() { - lastReturned = next; - previous = next; - Node KEY_VALUE_GENERIC_TYPE result = next; - next = moveNext(next); - wasForward = isForward; - return result; - } - - public boolean hasPrevious() { - return previous != null && (unboundBackwardFence || previous.key != backwardFence); - } - - protected Node KEY_VALUE_GENERIC_TYPE previousEntry() { - lastReturned = previous; - next = previous; - Node KEY_VALUE_GENERIC_TYPE result = previous; - previous = movePrevious(previous); - wasForward = !isForward; - return result; - } - - public void remove() { - if(lastReturned == null) throw new IllegalStateException(); - if(next == lastReturned) next = moveNext(next); - if(previous == lastReturned) previous = movePrevious(previous); - if(wasForward && lastReturned.needsSuccessor()) next = lastReturned; - map.removeNode(lastReturned); - lastReturned = null; - } - } - } - - class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE - { - @Override - public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() { - return new AscendingValueIterator(first); - } - - @Override - public boolean add(VALUE_TYPE e) { throw new UnsupportedOperationException(); } - - @Override - public void clear() { - RB_TREE_MAP.this.clear(); - } - - @Override - public int size() { - return RB_TREE_MAP.this.size; - } - -#if VALUE_OBJECT - @Override - public boolean contains(Object e) { - return containsValue(e); - } - -#else - @Override - public boolean contains(VALUE_TYPE e) { - return containsValue(e); - } - -#endif - @Override - public boolean remove(Object o) { - for(Node KEY_VALUE_GENERIC_TYPE entry = first; entry != null; entry = entry.next()) { - if(Objects.equals(entry.getValue(), o)) { - removeNode(entry); - return true; - } - } - return false; - } - - @Override - public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) { - Objects.requireNonNull(action); - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - action.accept(entry.value); - } - - @Override - public void forEachIndexed(VALUE_BI_FROM_INT_CONSUMER VALUE_GENERIC_TYPE action) { - Objects.requireNonNull(action); - int index = 0; - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - action.accept(index++, entry.value); - } - - @Override - public void forEach(E input, VALUE_BI_FROM_OBJECT_CONSUMER VSV_GENERIC_TYPE action) { - Objects.requireNonNull(action); - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - action.accept(input, entry.value); - } - - @Override - public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - if(filter.test(entry.value)) return true; - return false; - } - - @Override - public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - if(filter.test(entry.value)) return false; - return true; - } - - @Override - public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - if(!filter.test(entry.value)) return false; - return true; - } - - #if !VALUE_OBJECT - @Override - public VALUE_TYPE reduce(VALUE_TYPE identity, VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - VALUE_TYPE state = identity; - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - state = operator.APPLY_VALUE(state, entry.value); - return state; - } - - #else - @Override - public VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction operator) { - Objects.requireNonNull(operator); - VALUE_SPECIAL_TYPE state = identity; - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - state = operator.apply(state, entry.value); - return state; - } - - #endif - @Override - public VALUE_TYPE reduce(VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { - Objects.requireNonNull(operator); - VALUE_TYPE state = EMPTY_VALUE; - boolean empty = true; - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { - if(empty) { - empty = false; - state = entry.value; - continue; - } - state = operator.APPLY_VALUE(state, entry.value); - } - return state; - } - - @Override - public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - if(filter.test(entry.value)) return entry.value; - return EMPTY_VALUE; - } - - @Override - public int count(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { - Objects.requireNonNull(filter); - int result = 0; - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - if(filter.test(entry.value)) result++; - return result; - } - } - - class EntrySet extends AbstractObjectSet { - - @Override - public ObjectIterator iterator() { - return new AscendingMapEntryIterator(first); - } - - @Override - public void clear() { - RB_TREE_MAP.this.clear(); - } - - @Override - public int size() { - return RB_TREE_MAP.this.size; - } - - @Override - public boolean contains(Object o) { - if (!(o instanceof Map.Entry)) return false; - if(o instanceof MAP.Entry) - { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE) o; -#if TYPE_OBJECT - if(entry.getKey() == null && comparator() == null) return false; -#endif - KEY_TYPE key = entry.ENTRY_KEY(); - Node KEY_VALUE_GENERIC_TYPE node = findNode(key); - return node != null && VALUE_EQUALS(entry.ENTRY_VALUE(), node.ENTRY_VALUE()); - } - Map.Entry entry = (Map.Entry) o; - if(entry.getKey() == null && comparator() == null) return false; -#if !TYPE_OBJECT - if(!(entry.getKey() instanceof CLASS_TYPE)) return false; -#endif - CLASS_TYPE key = (CLASS_TYPE)entry.getKey(); - Node KEY_VALUE_GENERIC_TYPE node = findNode(key); - return node != null && Objects.equals(entry.getValue(), VALUE_TO_OBJ(node.ENTRY_VALUE())); - } - - @Override - public boolean remove(Object o) { - if (!(o instanceof Map.Entry)) return false; - if(o instanceof MAP.Entry) - { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE) o; - KEY_TYPE key = entry.ENTRY_KEY(); - Node KEY_VALUE_GENERIC_TYPE node = findNode(key); - if (node != null && VALUE_EQUALS(entry.ENTRY_VALUE(), node.ENTRY_VALUE())) { - removeNode(node); - return true; - } - return false; - } - Map.Entry entry = (Map.Entry) o; - CLASS_TYPE key = (CLASS_TYPE)entry.getKey(); - Node KEY_VALUE_GENERIC_TYPE node = findNode(key); - if (node != null && Objects.equals(entry.getValue(), VALUE_TO_OBJ(node.ENTRY_VALUE()))) { - removeNode(node); - return true; - } - return false; - } - - @Override - public void forEach(Consumer action) { - Objects.requireNonNull(action); - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - action.accept(new BasicEntryKV_BRACES(entry.key, entry.value)); - } - - @Override - public void forEachIndexed(IntObjectConsumer action) { - Objects.requireNonNull(action); - int index = 0; - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - action.accept(index++, new BasicEntryKV_BRACES(entry.key, entry.value)); - } - - @Override - public void forEach(E input, ObjectObjectConsumer action) { - Objects.requireNonNull(action); - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) - action.accept(input, new BasicEntryKV_BRACES(entry.key, entry.value)); - } - - @Override - public boolean matchesAny(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return false; - BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { - subEntry.set(entry.key, entry.value); - if(filter.test(subEntry)) return true; - } - return false; - } - - @Override - public boolean matchesNone(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { - subEntry.set(entry.key, entry.value); - if(filter.test(subEntry)) return false; - } - return true; - } - - @Override - public boolean matchesAll(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return true; - BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { - subEntry.set(entry.key, entry.value); - if(!filter.test(subEntry)) return false; - } - return true; - } - - @Override - public E reduce(E identity, BiFunction operator) { - Objects.requireNonNull(operator); - E state = identity; - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { - state = operator.apply(state, new BasicEntryKV_BRACES(entry.key, entry.value)); - } - return state; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE reduce(ObjectObjectUnaryOperator operator) { - Objects.requireNonNull(operator); - MAP.Entry KEY_VALUE_GENERIC_TYPE state = null; - boolean empty = true; - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { - if(empty) { - empty = false; - state = new BasicEntryKV_BRACES(entry.key, entry.value); - continue; - } - state = operator.apply(state, new BasicEntryKV_BRACES(entry.key, entry.value)); - } - return state; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE findFirst(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return null; - BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { - subEntry.set(entry.key, entry.value); - if(filter.test(subEntry)) return subEntry; - } - return null; - } - - @Override - public int count(Predicate filter) { - Objects.requireNonNull(filter); - if(size() <= 0) return 0; - int result = 0; - BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); - for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { - subEntry.set(entry.key, entry.value); - if(filter.test(subEntry)) result++; - } - return result; - } - } - - class DescendingKeyIterator extends MapEntryIterator implements BI_ITERATOR KEY_GENERIC_TYPE - { - public DescendingKeyIterator(Node KEY_VALUE_GENERIC_TYPE first) { - super(first, false); - } - - @Override - protected Node KEY_VALUE_GENERIC_TYPE moveNext(Node KEY_VALUE_GENERIC_TYPE node) { - return node.previous(); - } - - @Override - protected Node KEY_VALUE_GENERIC_TYPE movePrevious(Node KEY_VALUE_GENERIC_TYPE node) { - return node.next(); - } - - @Override - public KEY_TYPE PREVIOUS() { - if(!hasPrevious()) throw new NoSuchElementException(); - return previousEntry().key; - } - - @Override - public KEY_TYPE NEXT() { - if(!hasNext()) throw new NoSuchElementException(); - return nextEntry().key; - } - } - - class AscendingMapEntryIterator extends MapEntryIterator implements ObjectBidirectionalIterator - { - public AscendingMapEntryIterator(Node KEY_VALUE_GENERIC_TYPE first) - { - super(first, true); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { - if(!hasPrevious()) throw new NoSuchElementException(); - return previousEntry(); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { - if(!hasNext()) throw new NoSuchElementException(); - return nextEntry(); - } - } - - class AscendingValueIterator extends MapEntryIterator implements VALUE_BI_ITERATOR VALUE_GENERIC_TYPE - { - public AscendingValueIterator(Node KEY_VALUE_GENERIC_TYPE first) { - super(first, true); - } - - @Override - public VALUE_TYPE VALUE_PREVIOUS() { - if(!hasPrevious()) throw new NoSuchElementException(); - return previousEntry().value; - } - - @Override - public VALUE_TYPE VALUE_NEXT() { - if(!hasNext()) throw new NoSuchElementException(); - return nextEntry().value; - } - } - - class AscendingKeyIterator extends MapEntryIterator implements BI_ITERATOR KEY_GENERIC_TYPE - { - public AscendingKeyIterator(Node KEY_VALUE_GENERIC_TYPE first) { - super(first, true); - } - - @Override - public KEY_TYPE PREVIOUS() { - if(!hasPrevious()) throw new NoSuchElementException(); - return previousEntry().key; - } - - @Override - public KEY_TYPE NEXT() { - if(!hasNext()) throw new NoSuchElementException(); - return nextEntry().key; - } - } - - abstract class MapEntryIterator - { - final boolean isForward; - boolean wasMoved = false; - Node KEY_VALUE_GENERIC_TYPE lastReturned; - Node KEY_VALUE_GENERIC_TYPE next; - Node KEY_VALUE_GENERIC_TYPE previous; - - public MapEntryIterator(Node KEY_VALUE_GENERIC_TYPE first, boolean isForward) { - next = first; - previous = first == null ? null : movePrevious(first); - this.isForward = isForward; - } - - protected Node KEY_VALUE_GENERIC_TYPE moveNext(Node KEY_VALUE_GENERIC_TYPE node) { - return node.next(); - } - - protected Node KEY_VALUE_GENERIC_TYPE movePrevious(Node KEY_VALUE_GENERIC_TYPE node) { - return node.previous(); - } - - public boolean hasNext() { - return next != null; - } - - protected Node KEY_VALUE_GENERIC_TYPE nextEntry() { - lastReturned = next; - previous = next; - Node KEY_VALUE_GENERIC_TYPE result = next; - next = moveNext(next); - wasMoved = isForward; - return result; - } - - public boolean hasPrevious() { - return previous != null; - } - - protected Node KEY_VALUE_GENERIC_TYPE previousEntry() { - lastReturned = previous; - next = previous; - Node KEY_VALUE_GENERIC_TYPE result = previous; - previous = movePrevious(previous); - wasMoved = !isForward; - return result; - } - - public void remove() { - if(lastReturned == null) throw new IllegalStateException(); - if(next == lastReturned) next = moveNext(next); - if(previous == lastReturned) previous = movePrevious(previous); - if(wasMoved && lastReturned.needsSuccessor()) next = lastReturned; - removeNode(lastReturned); - lastReturned = null; - } - } - - private static final class Node KEY_VALUE_GENERIC_TYPE implements MAP.Entry KEY_VALUE_GENERIC_TYPE - { - static final int BLACK = 1; - - KEY_TYPE key; - VALUE_TYPE value; - int state; - Node KEY_VALUE_GENERIC_TYPE parent; - Node KEY_VALUE_GENERIC_TYPE left; - Node KEY_VALUE_GENERIC_TYPE right; - - Node(KEY_TYPE key, VALUE_TYPE value, Node KEY_VALUE_GENERIC_TYPE parent) { - this.key = key; - this.value = value; - this.parent = parent; - } - - Node KEY_VALUE_GENERIC_TYPE copy() { - Node KEY_VALUE_GENERIC_TYPE entry = new NodeKV_BRACES(key, value, null); - entry.state = state; - if(left != null) { - Node KEY_VALUE_GENERIC_TYPE newLeft = left.copy(); - entry.left = newLeft; - newLeft.parent = entry; - } - if(right != null) { - Node KEY_VALUE_GENERIC_TYPE newRight = right.copy(); - entry.right = newRight; - newRight.parent = entry; - } - return entry; - } - - public BasicEntry KEY_VALUE_GENERIC_TYPE export() { - return new BasicEntryKV_BRACES(key, value); - } - - @Override - public KEY_TYPE ENTRY_KEY() { - return key; - } - - @Override - public VALUE_TYPE ENTRY_VALUE() { - return value; - } - - @Override - public VALUE_TYPE setValue(VALUE_TYPE value) { - VALUE_TYPE oldValue = this.value; - this.value = value; - return oldValue; - } - -#if VALUE_PRIMITIVES - VALUE_TYPE addTo(VALUE_TYPE value) { - VALUE_TYPE oldValue = this.value; - this.value += value; - return oldValue; - } - - VALUE_TYPE subFrom(VALUE_TYPE value) { - VALUE_TYPE oldValue = this.value; - this.value -= value; - return oldValue; - } - -#endif - @Override - public boolean equals(Object obj) { - if(obj instanceof Map.Entry) { - if(obj instanceof MAP.Entry) { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)obj; -#if TYPE_OBJECT - if(entry.ENTRY_KEY() == null) return false; -#endif - return KEY_EQUALS(key, entry.ENTRY_KEY()) && VALUE_EQUALS(value, entry.ENTRY_VALUE()); - } - Map.Entry entry = (Map.Entry)obj; - Object otherKey = entry.getKey(); - if(otherKey == null) return false; - Object otherValue = entry.getValue(); -#if TYPE_OBJECT && VALUE_OBJECT - return KEY_EQUALS(key, otherKey) && VALUE_EQUALS(value, otherValue); -#else if TYPE_OBJECT - return otherValue instanceof CLASS_VALUE_TYPE && KEY_EQUALS(key, otherKey) && VALUE_EQUALS(value, CLASS_TO_VALUE(otherValue)); -#else if VALUE_OBJECT - return otherKey instanceof CLASS_TYPE && KEY_EQUALS(key, CLASS_TO_KEY(otherKey)) && VALUE_EQUALS(value, otherValue); -#else - return otherKey instanceof CLASS_TYPE && otherValue instanceof CLASS_VALUE_TYPE && KEY_EQUALS(key, CLASS_TO_KEY(otherKey)) && VALUE_EQUALS(value, CLASS_TO_VALUE(otherValue)); -#endif - } - return false; - } - - @Override - public int hashCode() { - return KEY_TO_HASH(key) ^ VALUE_TO_HASH(value); - } - - @Override - public String toString() { - return KEY_TO_STRING(key) + "=" + VALUE_TO_STRING(value); - } - - boolean isBlack() { - return (state & BLACK) != 0; - } - - void setBlack(boolean value) { - if(value) state |= BLACK; - else state &= ~BLACK; - } - - boolean needsSuccessor() { return left != null && right != null; } - - boolean replace(Node KEY_VALUE_GENERIC_TYPE entry) { - if(entry != null) entry.parent = parent; - if(parent != null) { - if(parent.left == this) parent.left = entry; - else parent.right = entry; - } - return parent == null; - } - - Node KEY_VALUE_GENERIC_TYPE next() { - if(right != null) { - Node KEY_VALUE_GENERIC_TYPE parent = right; - while(parent.left != null) parent = parent.left; - return parent; - } - Node KEY_VALUE_GENERIC_TYPE parent = this.parent; - Node KEY_VALUE_GENERIC_TYPE control = this; - while(parent != null && control == parent.right) { - control = parent; - parent = parent.parent; - } - return parent; - } - - Node KEY_VALUE_GENERIC_TYPE previous() { - if(left != null) { - Node KEY_VALUE_GENERIC_TYPE parent = left; - while(parent.right != null) parent = parent.right; - return parent; - } - Node KEY_VALUE_GENERIC_TYPE parent = this.parent; - Node KEY_VALUE_GENERIC_TYPE control = this; - while(parent != null && control == parent.left) { - control = parent; - parent = parent.parent; - } - return parent; - } - } +package speiger.src.collections.PACKAGE.maps.impl.tree; + +import java.util.Collections; +import java.util.Map; +#if TYPE_OBJECT +import java.util.Comparator; +#endif +import java.util.Objects; +import java.util.NoSuchElementException; +import java.util.function.Consumer; +import java.util.function.BiFunction; +import java.util.function.Predicate; +#if !TYPE_OBJECT && JDK_TYPE +import java.util.function.PREDICATE; +#endif +#if !SAME_TYPE && JDK_VALUE && !VALUE_OBJECT +import java.util.function.VALUE_PREDICATE; +#endif + +import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.functions.COMPARATOR; +import speiger.src.collections.PACKAGE.functions.CONSUMER; +import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; +#endif +import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER; +#if !TYPE_OBJECT && !VALUE_OBJECT +import speiger.src.collections.ints.functions.consumer.IntObjectConsumer; +#endif +#if !SAME_TYPE && !TYPE_INT +import speiger.src.collections.ints.functions.consumer.VALUE_BI_FROM_INT_CONSUMER; +#endif +#if !VALUE_BOOLEAN || !JDK_TYPE +import speiger.src.collections.PACKAGE.functions.function.FUNCTION; +#endif +#if !TYPE_INT || !SAME_TYPE +import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; +#endif +#if !TYPE_OBJECT && !VALUE_BOOLEAN && !JDK_TYPE +import speiger.src.collections.PACKAGE.functions.function.PREDICATE; +#endif +import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; +#if !SAME_TYPE +import speiger.src.collections.PACKAGE.functions.function.SINGLE_UNARY_OPERATOR; +#endif +import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.NAVIGABLE_MAP; +import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET; +import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET; +#if TYPE_OBJECT +import speiger.src.collections.PACKAGE.sets.SET; +#endif +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; +import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_SUPPLIER; +#if !SAME_TYPE +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_BI_ITERATOR; +import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR; +#endif +#if !VALUE_OBJECT && !SAME_TYPE +import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER; +#endif +#if !TYPE_OBJECT && !VALUE_OBJECT || !VALUE_OBJECT +import speiger.src.collections.objects.functions.consumer.ObjectObjectConsumer; +#endif +#if !SAME_TYPE +#if !TYPE_OBJECT +import speiger.src.collections.objects.functions.consumer.VALUE_BI_FROM_OBJECT_CONSUMER; + +#endif +#if !JDK_VALUE +import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE; +#endif +#endif +#if !TYPE_OBJECT && !VALUE_OBJECT +import speiger.src.collections.objects.collections.ObjectBidirectionalIterator; +#endif +#if !VALUE_OBJECT +import speiger.src.collections.objects.collections.ObjectIterator; +#endif +#if !TYPE_OBJECT +#if !VALUE_OBJECT +import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator; + +#endif +import speiger.src.collections.objects.sets.AbstractObjectSet; +import speiger.src.collections.objects.sets.ObjectSet; +#endif + +/** + * A Simple Type Specific RB TreeMap implementation that reduces boxing/unboxing. + * It is using a bit more memory then FastUtil, + * but it saves a lot of Performance on the Optimized removal and iteration logic. + * Which makes the implementation actually useable and does not get outperformed by Javas default implementation. + * @Type(T) + * @ValueType(V) + */ +public class RB_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE +{ + /** The center of the Tree */ + protected transient Node KEY_VALUE_GENERIC_TYPE tree; + /** The Lowest possible Node */ + protected transient Node KEY_VALUE_GENERIC_TYPE first; + /** The Highest possible Node */ + protected transient Node KEY_VALUE_GENERIC_TYPE last; + /** The amount of elements stored in the Map */ + protected int size = 0; + /** The Sorter of the Tree */ + protected transient COMPARATOR KEY_GENERIC_TYPE comparator; + +#if !TYPE_OBJECT + /** the default return value for max searches */ + protected KEY_TYPE defaultMaxNotFound = CLASS_TYPE.MIN_VALUE; + /** the default return value for min searches */ + protected KEY_TYPE defaultMinNotFound = CLASS_TYPE.MAX_VALUE; +#endif + + /** KeySet Cache */ + protected NAVIGABLE_SET KEY_GENERIC_TYPE keySet; + /** Values Cache */ + protected VALUE_COLLECTION VALUE_GENERIC_TYPE values; + /** EntrySet Cache */ + protected ObjectSet entrySet; + + /** + * Default Constructor + */ + public RB_TREE_MAP() { + } + + /** + * Constructor that allows to define the sorter + * @param comp the function that decides how the tree is sorted, can be null + */ + public RB_TREE_MAP(COMPARATOR KEY_GENERIC_TYPE comp) { + comparator = comp; + } + +#if !TYPE_OBJECT || !VALUE_OBJECT + /** + * Helper constructor that allow to create a map from boxed values (it will unbox them) + * @param keys the keys that should be put into the map + * @param values the values that should be put into the map. + * @throws IllegalStateException if the keys and values do not match in lenght + */ + public RB_TREE_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values) { + this(keys, values, null); + } + + /** + * Helper constructor that has a custom sorter and allow to create a map from boxed values (it will unbox them) + * @param keys the keys that should be put into the map + * @param values the values that should be put into the map. + * @param comp the function that decides how the tree is sorted, can be null + * @throws IllegalStateException if the keys and values do not match in lenght + */ + public RB_TREE_MAP(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, COMPARATOR KEY_GENERIC_TYPE comp) { + comparator = comp; + if(keys.length != values.length) throw new IllegalStateException("Input Arrays are not equal size"); + for(int i = 0,m=keys.length;i map) { + this(map, null); + } + + /** + * A Helper constructor that has a custom sorter and allows to create a Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + * @param comp the function that decides how the tree is sorted, can be null + */ + public RB_TREE_MAP(Map map, COMPARATOR KEY_GENERIC_TYPE comp) { + comparator = comp; + putAll(map); + } + + /** + * A Type Specific Helper function that allows to create a new Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + */ + public RB_TREE_MAP(MAP KEY_VALUE_GENERIC_TYPE map) { + this(map, null); + } + + /** + * A Type Specific Helper function that has a custom sorter and allows to create a new Map with exactly the same values as the provided map. + * @param map the values that should be present in the map + * @param comp the function that decides how the tree is sorted, can be null + */ + public RB_TREE_MAP(MAP KEY_VALUE_GENERIC_TYPE map, COMPARATOR KEY_GENERIC_TYPE comp) { + comparator = comp; + putAll(map); + } + +#if TYPE_OBJECT + /** only used for primitives + * @return null + */ + public KEY_TYPE getDefaultMaxValue() { return null; } + /** only used for primitives + * @return null + */ + public KEY_TYPE getDefaultMinValue() { return null; } + +#else + @Override + public void setDefaultMaxValue(KEY_TYPE value) { defaultMaxNotFound = value; } + @Override + public KEY_TYPE getDefaultMaxValue() { return defaultMaxNotFound; } + @Override + public void setDefaultMinValue(KEY_TYPE value) { defaultMinNotFound = value; } + @Override + public KEY_TYPE getDefaultMinValue() { return defaultMinNotFound; } + +#endif + + @Override + public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { +#if TYPE_OBJECT + validate(key); +#endif + if(tree == null) { + tree = first = last = new NodeKV_BRACES(key, value, null); + size++; + return getDefaultReturnValue(); + } + int compare = 0; + Node KEY_VALUE_GENERIC_TYPE parent = tree; + while(true) { + if((compare = compare(key, parent.key)) == 0) return parent.setValue(value); + if(compare < 0) { + if(parent.left == null) break; + parent = parent.left; + } + else if(compare > 0) { + if(parent.right == null) break; + parent = parent.right; + } + } + Node KEY_VALUE_GENERIC_TYPE adding = new NodeKV_BRACES(key, value, parent); + if(compare < 0) { + parent.left = adding; + if(parent == first) first = adding; + } + else { + parent.right = adding; + if(parent == last) last = adding; + } + fixAfterInsertion(adding); + size++; + return getDefaultReturnValue(); + } + + @Override + public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { +#if TYPE_OBJECT + validate(key); +#endif + if(tree == null) { + tree = first = last = new NodeKV_BRACES(key, value, null); + size++; + return getDefaultReturnValue(); + } + int compare = 0; + Node KEY_VALUE_GENERIC_TYPE parent = tree; + while(true) { + if((compare = compare(key, parent.key)) == 0) { + if(VALUE_EQUALS(parent.value, getDefaultReturnValue())) return parent.setValue(value); + return parent.value; + } + if(compare < 0) { + if(parent.left == null) break; + parent = parent.left; + } + else if(compare > 0) { + if(parent.right == null) break; + parent = parent.right; + } + } + Node KEY_VALUE_GENERIC_TYPE adding = new NodeKV_BRACES(key, value, parent); + if(compare < 0) { + parent.left = adding; + if(parent == first) first = adding; + } + else { + parent.right = adding; + if(parent == last) last = adding; + } + fixAfterInsertion(adding); + size++; + return getDefaultReturnValue(); + } + +#if VALUE_PRIMITIVES + @Override + public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { +#if TYPE_OBJECT + validate(key); +#endif + if(tree == null) { + tree = first = last = new NodeKV_BRACES(key, value, null); + size++; + return getDefaultReturnValue(); + } + int compare = 0; + Node KEY_VALUE_GENERIC_TYPE parent = tree; + while(true) { + if((compare = compare(key, parent.key)) == 0) return parent.addTo(value); + if(compare < 0) { + if(parent.left == null) break; + parent = parent.left; + } + else if(compare > 0) { + if(parent.right == null) break; + parent = parent.right; + } + } + Node KEY_VALUE_GENERIC_TYPE adding = new NodeKV_BRACES(key, value, parent); + if(compare < 0) { + parent.left = adding; + if(parent == first) first = adding; + } + else { + parent.right = adding; + if(parent == last) last = adding; + } + fixAfterInsertion(adding); + size++; + return getDefaultReturnValue(); + } + + @Override + public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { + if(tree == null) return getDefaultReturnValue(); + int compare = 0; + Node KEY_VALUE_GENERIC_TYPE parent = tree; + while(true) { + if((compare = compare(key, parent.key)) == 0) + { + VALUE_TYPE oldValue = parent.subFrom(value); + if(value < 0 ? (parent.value >= getDefaultReturnValue()) : (parent.value <= getDefaultReturnValue())) removeNode(parent); + return oldValue; + } + if(compare < 0) { + if(parent.left == null) break; + parent = parent.left; + } + else if(compare > 0) { + if(parent.right == null) break; + parent = parent.right; + } + } + return getDefaultReturnValue(); + } + +#endif + @Override + public COMPARATOR KEY_GENERIC_TYPE comparator() { return comparator; } + +#if TYPE_OBJECT + @Override + public boolean containsKey(Object key) { + return findNode((KEY_TYPE)key) != null; + } + +#else + @Override + public boolean containsKey(KEY_TYPE key) { + return findNode(key) != null; + } + +#endif + @Override + public VALUE_TYPE GET_VALUE(KEY_TYPE key) { + Node KEY_VALUE_GENERIC_TYPE node = findNode(key); + return node == null ? getDefaultReturnValue() : node.value; + } + +#if TYPE_OBJECT && VALUE_OBJECT + @Override + public VALUE_TYPE getOrDefault(Object key, VALUE_TYPE defaultValue) { + Node KEY_VALUE_GENERIC_TYPE node = findNode((CLASS_TYPE)key); + return node == null ? defaultValue : node.value; + } + +#else + @Override + public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { + Node KEY_VALUE_GENERIC_TYPE node = findNode(key); + return node == null ? defaultValue : node.value; + } + +#endif + @Override + public KEY_TYPE FIRST_ENTRY_KEY() { + if(tree == null) throw new NoSuchElementException(); + return first.key; + } + + @Override + public KEY_TYPE POLL_FIRST_ENTRY_KEY() { + if(tree == null) return getDefaultMinValue(); + KEY_TYPE result = first.key; + removeNode(first); + return result; + } + + @Override + public KEY_TYPE LAST_ENTRY_KEY() { + if(tree == null) throw new NoSuchElementException(); + return last.key; + } + + @Override + public KEY_TYPE POLL_LAST_ENTRY_KEY() { + if(tree == null) return getDefaultMaxValue(); + KEY_TYPE result = last.key; + removeNode(last); + return result; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE firstEntry() { + if(tree == null) return null; + return first.export(); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE lastEntry() { + if(tree == null) return null; + return last.export(); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirstEntry() { + if(tree == null) return null; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = first.export(); + removeNode(first); + return entry; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLastEntry() { + if(tree == null) return null; + BasicEntry KEY_VALUE_GENERIC_TYPE entry = last.export(); + removeNode(last); + return entry; + } + + @Override + public VALUE_TYPE FIRST_ENTRY_VALUE() { + if(tree == null) throw new NoSuchElementException(); + return first.value; + } + + @Override + public VALUE_TYPE LAST_ENTRY_VALUE() { + if(tree == null) throw new NoSuchElementException(); + return last.value; + } + + @Override + public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { + Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); + if(entry == null) return getDefaultReturnValue(); + VALUE_TYPE value = entry.value; + removeNode(entry); + return value; + } + + @Override + public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { + Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); + if(entry == null) return defaultValue; + VALUE_TYPE value = entry.value; + removeNode(entry); + return value; + } + +#if TYPE_OBJECT && VALUE_OBJECT + @Override + public boolean remove(Object key, Object value) { + Node KEY_VALUE_GENERIC_TYPE entry = findNode((CLASS_TYPE)key); + if(entry == null || !Objects.equals(value, entry.value)) return false; + removeNode(entry); + return true; + } + +#else + @Override + public boolean remove(KEY_TYPE key, VALUE_TYPE value) { + Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); + if(entry == null || entry.value != value) return false; + removeNode(entry); + return true; + } + +#endif + @Override + public boolean replace(KEY_TYPE key, VALUE_TYPE oldValue, VALUE_TYPE newValue) { + Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); + if(entry == null || entry.value != oldValue) return false; + entry.value = newValue; + return true; + } + + @Override + public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value) { + Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); + if(entry == null) return getDefaultReturnValue(); + VALUE_TYPE oldValue = entry.value; + entry.value = value; + return oldValue; + } + + @Override + public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); +#if TYPE_OBJECT + validate(key); +#endif + Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); + if(entry == null) { + VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, getDefaultReturnValue()); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + put(key, newValue); + return newValue; + } + VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, entry.value); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + removeNode(entry); + return newValue; + } + entry.value = newValue; + return newValue; + } + + @Override + public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); +#if TYPE_OBJECT + validate(key); +#endif + Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); + if(entry == null) { + VALUE_TYPE newValue = mappingFunction.APPLY(key); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + put(key, newValue); + return newValue; + } + if(Objects.equals(entry.value, getDefaultReturnValue())) { + VALUE_TYPE newValue = mappingFunction.APPLY(key); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + entry.value = newValue; + } + return entry.value; + } + + @Override + public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) { + Objects.requireNonNull(valueProvider); +#if TYPE_OBJECT + validate(key); +#endif + Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); + if(entry == null) { + VALUE_TYPE newValue = valueProvider.VALUE_SUPPLY_GET(); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + put(key, newValue); + return newValue; + } + if(VALUE_EQUALS(entry.value, getDefaultReturnValue())) { + VALUE_TYPE newValue = valueProvider.VALUE_SUPPLY_GET(); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue; + entry.value = newValue; + } + return entry.value; + } + + @Override + public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); +#if TYPE_OBJECT + validate(key); +#endif + Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); + if(entry == null || VALUE_EQUALS(entry.value, getDefaultReturnValue())) return getDefaultReturnValue(); + VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, entry.value); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + removeNode(entry); + return newValue; + } + entry.value = newValue; + return newValue; + } + + @Override + public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); +#if TYPE_OBJECT + validate(key); +#endif + Node KEY_VALUE_GENERIC_TYPE entry = findNode(key); + VALUE_TYPE newValue = entry == null || VALUE_EQUALS(entry.value, getDefaultReturnValue()) ? value : mappingFunction.APPLY_VALUE(entry.value, value); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + if(entry != null) + removeNode(entry); + } + else if(entry == null) put(key, newValue); + else entry.value = newValue; + return newValue; + } + + @Override + public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); + for(MAP.Entry KEY_VALUE_GENERIC_TYPE entry : getFastIterable(m)) { + KEY_TYPE key = entry.ENTRY_KEY(); + Node KEY_VALUE_GENERIC_TYPE subEntry = findNode(key); + VALUE_TYPE newValue = subEntry == null || VALUE_EQUALS(subEntry.value, getDefaultReturnValue()) ? entry.ENTRY_VALUE() : mappingFunction.APPLY_VALUE(subEntry.value, entry.ENTRY_VALUE()); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + if(subEntry != null) + removeNode(subEntry); + } + else if(subEntry == null) put(key, newValue); + else subEntry.value = newValue; + } + } + + @Override + public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + action.accept(entry.key, entry.value); + } + + @Override + public int size() { return size; } + + @Override + public void clear() { + size = 0; + first = null; + last = null; + tree = null; + } + + protected BI_ITERATOR KEY_GENERIC_TYPE keyIterator() { + return new AscendingKeyIterator(first); + } + + protected BI_ITERATOR KEY_GENERIC_TYPE keyIterator(KEY_TYPE element) { + return new AscendingKeyIterator(findNode(element)); + } + + protected BI_ITERATOR KEY_GENERIC_TYPE descendingKeyIterator() { + return new DescendingKeyIterator(last); + } + + @Override + public RB_TREE_MAP KEY_VALUE_GENERIC_TYPE copy() { + RB_TREE_MAP KEY_VALUE_GENERIC_TYPE set = new RB_TREE_MAPKV_BRACES(); + set.size = size; + if(tree != null) { + set.tree = tree.copy(); + Node KEY_VALUE_GENERIC_TYPE lastFound = null; + for(Node KEY_VALUE_GENERIC_TYPE entry = tree;entry != null;entry = entry.left) lastFound = entry; + set.first = lastFound; + lastFound = null; + for(Node KEY_VALUE_GENERIC_TYPE entry = tree;entry != null;entry = entry.right) lastFound = entry; + set.last = lastFound; + } + return set; + } + + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE keySet() { + return navigableKeySet(); + } + + @Override + public ObjectSet ENTRY_SET() { + if(entrySet == null) entrySet = new EntrySet(); + return entrySet; + } + + @Override + public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { + if(values == null) values = new Values(); + return values; + } + + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE navigableKeySet() { + if(keySet == null) keySet = new KeySetKV_BRACES(this); + return keySet; + } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap() { + return new DescendingNaivgableSubMapKV_BRACES(this, true, EMPTY_KEY_VALUE, true, true, EMPTY_KEY_VALUE, true); + } + + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE descendingKeySet() { + return descendingMap().navigableKeySet(); + } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, boolean fromInclusive, KEY_TYPE toKey, boolean toInclusive) { + return new AscendingNaivgableSubMapKV_BRACES(this, false, fromKey, fromInclusive, false, toKey, toInclusive); + } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey, boolean inclusive) { + return new AscendingNaivgableSubMapKV_BRACES(this, true, EMPTY_KEY_VALUE, true, false, toKey, inclusive); + } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey, boolean inclusive) { + return new AscendingNaivgableSubMapKV_BRACES(this, false, fromKey, inclusive, true, EMPTY_KEY_VALUE, true); + } + + @Override + public KEY_TYPE lowerKey(KEY_TYPE e) { + Node KEY_VALUE_GENERIC_TYPE node = findLowerNode(e); + return node != null ? node.key : getDefaultMinValue(); + } + + @Override + public KEY_TYPE floorKey(KEY_TYPE e) { + Node KEY_VALUE_GENERIC_TYPE node = findFloorNode(e); + return node != null ? node.key : getDefaultMinValue(); + } + + @Override + public KEY_TYPE higherKey(KEY_TYPE e) { + Node KEY_VALUE_GENERIC_TYPE node = findHigherNode(e); + return node != null ? node.key : getDefaultMaxValue(); + } + + @Override + public KEY_TYPE ceilingKey(KEY_TYPE e) { + Node KEY_VALUE_GENERIC_TYPE node = findCeilingNode(e); + return node != null ? node.key : getDefaultMaxValue(); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE lowerEntry(KEY_TYPE key) { + Node KEY_VALUE_GENERIC_TYPE node = findLowerNode(key); + return node != null ? node.export() : null; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE higherEntry(KEY_TYPE key) { + Node KEY_VALUE_GENERIC_TYPE node = findHigherNode(key); + return node != null ? node.export() : null; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE floorEntry(KEY_TYPE key) { + Node KEY_VALUE_GENERIC_TYPE node = findFloorNode(key); + return node != null ? node.export() : null; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE ceilingEntry(KEY_TYPE key) { + Node KEY_VALUE_GENERIC_TYPE node = findCeilingNode(key); + return node != null ? node.export() : null; + } + + protected Node KEY_VALUE_GENERIC_TYPE findLowerNode(KEY_TYPE key) { + Node KEY_VALUE_GENERIC_TYPE entry = tree; + while(entry != null) { + if(compare(key, entry.key) > 0) { + if(entry.right != null) entry = entry.right; + else return entry; + } + else { + if(entry.left != null) entry = entry.left; + else { + Node KEY_VALUE_GENERIC_TYPE parent = entry.parent; + while(parent != null && parent.left == entry) { + entry = parent; + parent = parent.parent; + } + return parent; + } + } + } + return null; + } + + protected Node KEY_VALUE_GENERIC_TYPE findFloorNode(KEY_TYPE key) { + Node KEY_VALUE_GENERIC_TYPE entry = tree; + int compare; + while(entry != null) { + if((compare = compare(key, entry.key)) > 0) { + if(entry.right == null) break; + entry = entry.right; + continue; + } + else if(compare < 0) { + if(entry.left != null) entry = entry.left; + else { + Node KEY_VALUE_GENERIC_TYPE parent = entry.parent; + while(parent != null && parent.left == entry) { + entry = parent; + parent = parent.parent; + } + return parent; + } + continue; + } + break; + } + return entry; + } + + protected Node KEY_VALUE_GENERIC_TYPE findCeilingNode(KEY_TYPE key) { + Node KEY_VALUE_GENERIC_TYPE entry = tree; + int compare; + while(entry != null) { + if((compare = compare(key, entry.key)) < 0) { + if(entry.left == null) break; + entry = entry.left; + continue; + } + else if(compare > 0) { + if(entry.right != null) entry = entry.right; + else { + Node KEY_VALUE_GENERIC_TYPE parent = entry.parent; + while(parent != null && parent.right == entry) { + entry = parent; + parent = parent.parent; + } + return parent; + } + continue; + } + break; + } + return entry; + } + + protected Node KEY_VALUE_GENERIC_TYPE findHigherNode(KEY_TYPE key) { + Node KEY_VALUE_GENERIC_TYPE entry = tree; + while(entry != null) { + if(compare(key, entry.key) < 0) { + if(entry.left != null) entry = entry.left; + else return entry; + } + else { + if(entry.right != null) entry = entry.right; + else { + Node KEY_VALUE_GENERIC_TYPE parent = entry.parent; + while(parent != null && parent.right == entry) { + entry = parent; + parent = parent.parent; + } + return parent; + } + } + } + return null; + } + + protected Node KEY_VALUE_GENERIC_TYPE findNode(KEY_TYPE key) { + Node KEY_VALUE_GENERIC_TYPE node = tree; + int compare; + while(node != null) { + if((compare = compare(key, node.key)) == 0) return node; + if(compare < 0) node = node.left; + else node = node.right; + } + return null; + } + + protected void removeNode(Node KEY_VALUE_GENERIC_TYPE entry) { + size--; + if(entry.needsSuccessor()) { + Node KEY_VALUE_GENERIC_TYPE successor = entry.next(); + entry.key = successor.key; + entry.value = successor.value; + entry = successor; + } + Node KEY_VALUE_GENERIC_TYPE replacement = entry.left != null ? entry.left : entry.right; + if(replacement != null) { + if(entry.replace(replacement)) tree = replacement; + if(entry == first) first = replacement; + if(entry == last) last = entry.right != null ? entry.right : replacement; + entry.left = entry.right = entry.parent = null; + if(entry.isBlack()) fixAfterDeletion(replacement); + } + else if(entry.parent == null) tree = first = last = null; + else { + if(entry.isBlack()) + fixAfterDeletion(entry); + entry.replace(null); + if(entry.parent != null) { + Node KEY_VALUE_GENERIC_TYPE parent = entry.parent; + if(entry == first) first = parent.left != null ? parent.left : parent; + if(entry == last) last = entry.right != null ? parent.right : parent; + } + entry.parent = null; + } + } + + protected void validate(KEY_TYPE k) { compare(k, k); } + protected int compare(KEY_TYPE k, KEY_TYPE v) { return comparator != null ? comparator.compare(k, v) : COMPAREABLE_TO_KEY(k, v);} + protected static GENERIC_KEY_VALUE_BRACES boolean isBlack(Node KEY_VALUE_GENERIC_TYPE p) { return p == null || p.isBlack(); } + protected static GENERIC_KEY_VALUE_BRACES Node KEY_VALUE_GENERIC_TYPE parentOf(Node KEY_VALUE_GENERIC_TYPE p) { return (p == null ? null : p.parent); } + protected static GENERIC_KEY_VALUE_BRACES void setBlack(Node KEY_VALUE_GENERIC_TYPE p, boolean c) { if(p != null) p.setBlack(c); } + protected static GENERIC_KEY_VALUE_BRACES Node KEY_VALUE_GENERIC_TYPE leftOf(Node KEY_VALUE_GENERIC_TYPE p) { return p == null ? null : p.left; } + protected static GENERIC_KEY_VALUE_BRACES Node KEY_VALUE_GENERIC_TYPE rightOf(Node KEY_VALUE_GENERIC_TYPE p) { return (p == null) ? null : p.right; } + + protected void rotateLeft(Node KEY_VALUE_GENERIC_TYPE entry) { + if(entry != null) { + Node KEY_VALUE_GENERIC_TYPE right = entry.right; + entry.right = right.left; + if(right.left != null) right.left.parent = entry; + right.parent = entry.parent; + if(entry.parent == null) tree = right; + else if(entry.parent.left == entry) entry.parent.left = right; + else entry.parent.right = right; + right.left = entry; + entry.parent = right; + } + } + + protected void rotateRight(Node KEY_VALUE_GENERIC_TYPE entry) { + if(entry != null) { + Node KEY_VALUE_GENERIC_TYPE left = entry.left; + entry.left = left.right; + if(left.right != null) left.right.parent = entry; + left.parent = entry.parent; + if(entry.parent == null) tree = left; + else if(entry.parent.right == entry) entry.parent.right = left; + else entry.parent.left = left; + left.right = entry; + entry.parent = left; + } + } + + protected void fixAfterInsertion(Node KEY_VALUE_GENERIC_TYPE entry) { + entry.setBlack(false); + while(entry != null && entry != tree && !entry.parent.isBlack()) { + if(parentOf(entry) == leftOf(parentOf(parentOf(entry)))) { + Node KEY_VALUE_GENERIC_TYPE y = rightOf(parentOf(parentOf(entry))); + if(!isBlack(y)) { + setBlack(parentOf(entry), true); + setBlack(y, true); + setBlack(parentOf(parentOf(entry)), false); + entry = parentOf(parentOf(entry)); + } + else { + if(entry == rightOf(parentOf(entry))) { + entry = parentOf(entry); + rotateLeft(entry); + } + setBlack(parentOf(entry), true); + setBlack(parentOf(parentOf(entry)), false); + rotateRight(parentOf(parentOf(entry))); + } + } + else { + Node KEY_VALUE_GENERIC_TYPE y = leftOf(parentOf(parentOf(entry))); + if(!isBlack(y)) { + setBlack(parentOf(entry), true); + setBlack(y, true); + setBlack(parentOf(parentOf(entry)), false); + entry = parentOf(parentOf(entry)); + } + else { + if(entry == leftOf(parentOf(entry))) { + entry = parentOf(entry); + rotateRight(entry); + } + setBlack(parentOf(entry), true); + setBlack(parentOf(parentOf(entry)), false); + rotateLeft(parentOf(parentOf(entry))); + } + } + } + tree.setBlack(true); + } + + protected void fixAfterDeletion(Node KEY_VALUE_GENERIC_TYPE entry) { + while(entry != tree && isBlack(entry)) { + if(entry == leftOf(parentOf(entry))) { + Node KEY_VALUE_GENERIC_TYPE sib = rightOf(parentOf(entry)); + if(!isBlack(sib)) { + setBlack(sib, true); + setBlack(parentOf(entry), false); + rotateLeft(parentOf(entry)); + sib = rightOf(parentOf(entry)); + } + if(isBlack(leftOf(sib)) && isBlack(rightOf(sib))) { + setBlack(sib, false); + entry = parentOf(entry); + } + else { + if(isBlack(rightOf(sib))) { + setBlack(leftOf(sib), true); + setBlack(sib, false); + rotateRight(sib); + sib = rightOf(parentOf(entry)); + } + setBlack(sib, isBlack(parentOf(entry))); + setBlack(parentOf(entry), true); + setBlack(rightOf(sib), true); + rotateLeft(parentOf(entry)); + entry = tree; + } + } + else { + Node KEY_VALUE_GENERIC_TYPE sib = leftOf(parentOf(entry)); + if(!isBlack(sib)) { + setBlack(sib, true); + setBlack(parentOf(entry), false); + rotateRight(parentOf(entry)); + sib = leftOf(parentOf(entry)); + } + if(isBlack(rightOf(sib)) && isBlack(leftOf(sib))) { + setBlack(sib, false); + entry = parentOf(entry); + } + else { + if(isBlack(leftOf(sib))) { + setBlack(rightOf(sib), true); + setBlack(sib, false); + rotateLeft(sib); + sib = leftOf(parentOf(entry)); + } + setBlack(sib, isBlack(parentOf(entry))); + setBlack(parentOf(entry), true); + setBlack(leftOf(sib), true); + rotateRight(parentOf(entry)); + entry = tree; + } + } + } + setBlack(entry, true); + } + + static class KeySet KEY_VALUE_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE implements NAVIGABLE_SET KEY_GENERIC_TYPE + { + NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map; + + public KeySet(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map) { + this.map = map; + } + +#if !TYPE_OBJECT + @Override + public void setDefaultMaxValue(KEY_TYPE e) { map.setDefaultMaxValue(e); } + @Override + public KEY_TYPE getDefaultMaxValue() { return map.getDefaultMaxValue(); } + @Override + public void setDefaultMinValue(KEY_TYPE e) { map.setDefaultMinValue(e); } + @Override + public KEY_TYPE getDefaultMinValue() { return map.getDefaultMinValue(); } +#endif + @Override + public KEY_TYPE lower(KEY_TYPE e) { return map.lowerKey(e); } + @Override + public KEY_TYPE floor(KEY_TYPE e) { return map.floorKey(e); } + @Override + public KEY_TYPE ceiling(KEY_TYPE e) { return map.ceilingKey(e); } + @Override + public KEY_TYPE higher(KEY_TYPE e) { return map.higherKey(e); } + +#if !TYPE_OBJECT + @Override + public CLASS_TYPE lower(CLASS_TYPE e) { + MAP.Entry KEY_VALUE_GENERIC_TYPE node = map.lowerEntry(OBJ_TO_KEY(e)); + return node != null ? node.getKey() : null; + } + + @Override + public CLASS_TYPE floor(CLASS_TYPE e) { + MAP.Entry KEY_VALUE_GENERIC_TYPE node = map.floorEntry(OBJ_TO_KEY(e)); + return node != null ? node.getKey() : null; + } + + @Override + public CLASS_TYPE higher(CLASS_TYPE e) { + MAP.Entry KEY_VALUE_GENERIC_TYPE node = map.higherEntry(OBJ_TO_KEY(e)); + return node != null ? node.getKey() : null; + } + + @Override + public CLASS_TYPE ceiling(CLASS_TYPE e) { + MAP.Entry KEY_VALUE_GENERIC_TYPE node = map.ceilingEntry(OBJ_TO_KEY(e)); + return node != null ? node.getKey() : null; + } + +#endif + @Override + public KEY_TYPE POLL_FIRST_KEY() { return map.POLL_FIRST_ENTRY_KEY(); } + @Override + public KEY_TYPE POLL_LAST_KEY() { return map.POLL_LAST_ENTRY_KEY(); } + @Override + public COMPARATOR KEY_GENERIC_TYPE comparator() { return map.comparator(); } + @Override + public KEY_TYPE FIRST_KEY() { return map.FIRST_ENTRY_KEY(); } + @Override + public KEY_TYPE LAST_KEY() { return map.LAST_ENTRY_KEY(); } + @Override + public void clear() { map.clear(); } + +#if TYPE_OBJECT + @Override + public boolean remove(Object o) { + int oldSize = map.size(); + map.remove(o); + return oldSize != map.size(); + } + +#else + @Override + public boolean remove(KEY_TYPE o) { + int oldSize = map.size(); + map.remove(o); + return oldSize != map.size(); + } + +#endif + @Override + public boolean add(KEY_TYPE e) { throw new UnsupportedOperationException(); } + @Override + public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { + if(map instanceof RB_TREE_MAP) return ((RB_TREE_MAP KEY_VALUE_GENERIC_TYPE)map).keyIterator(fromElement); + return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).keyIterator(fromElement); + } + + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, boolean fromInclusive, KEY_TYPE toElement, boolean toInclusive) { return new KeySetKV_BRACES(map.subMap(fromElement, fromInclusive, toElement, toInclusive)); } + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement, boolean inclusive) { return new KeySetKV_BRACES(map.headMap(toElement, inclusive)); } + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement, boolean inclusive) { return new KeySetKV_BRACES(map.tailMap(fromElement, inclusive)); } + + @Override + public BI_ITERATOR KEY_GENERIC_TYPE iterator() { + if(map instanceof RB_TREE_MAP) return ((RB_TREE_MAP KEY_VALUE_GENERIC_TYPE)map).keyIterator(); + return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).keyIterator(); + } + + @Override + public BI_ITERATOR KEY_GENERIC_TYPE descendingIterator() { + if(map instanceof RB_TREE_MAP) return ((RB_TREE_MAP KEY_VALUE_GENERIC_TYPE)map).descendingKeyIterator(); + return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).descendingKeyIterator(); + } + + protected Node KEY_VALUE_GENERIC_TYPE start() { + if(map instanceof RB_TREE_MAP) return ((RB_TREE_MAP KEY_VALUE_GENERIC_TYPE)map).first; + return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).subLowest(); + } + + protected Node KEY_VALUE_GENERIC_TYPE end() { + if(map instanceof RB_TREE_MAP) return null; + return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).subHighest(); + } + + protected Node KEY_VALUE_GENERIC_TYPE next(Node KEY_VALUE_GENERIC_TYPE entry) { + if(map instanceof RB_TREE_MAP) return entry.next(); + return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).next(entry); + } + + protected Node KEY_VALUE_GENERIC_TYPE previous(Node KEY_VALUE_GENERIC_TYPE entry) { + if(map instanceof RB_TREE_MAP) return entry.previous(); + return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)map).previous(entry); + } + + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE descendingSet() { return new KeySetKV_BRACES(map.descendingMap()); } + @Override + public KeySet KEY_VALUE_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); } + @Override + public boolean isEmpty() { return map.isEmpty(); } + @Override + public int size() { return map.size(); } + + @Override + public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { + Objects.requireNonNull(action); + for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) + action.accept(entry.key); + } + + @Override + public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) { + Objects.requireNonNull(action); + int index = 0; + for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) + action.accept(index++, entry.key); + } + + @Override + public void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { + Objects.requireNonNull(action); + for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) + action.accept(input, entry.key); + } + + @Override + public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) + if(filter.test(entry.key)) return true; + return false; + } + + @Override + public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) + if(filter.test(entry.key)) return false; + return true; + } + + @Override + public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) + if(!filter.test(entry.key)) return false; + return true; + } + +#if !TYPE_OBJECT + @Override + public KEY_TYPE reduce(KEY_TYPE identity, SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + KEY_TYPE state = identity; + for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) + state = operator.APPLY_KEY_VALUE(state, entry.key); + return state; + } + +#else + @Override + public KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) { + Objects.requireNonNull(operator); + KEY_SPECIAL_TYPE state = identity; + for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) + state = operator.apply(state, entry.key); + return state; + } + +#endif + @Override + public KEY_TYPE reduce(SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + KEY_TYPE state = EMPTY_KEY_VALUE; + boolean empty = true; + for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) { + if(empty) { + empty = false; + state = entry.key; + continue; + } + state = operator.APPLY_KEY_VALUE(state, entry.key); + } + return state; + } + + @Override + public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) + if(filter.test(entry.key)) return entry.key; + return EMPTY_KEY_VALUE; + } + + @Override + public int count(PREDICATE KEY_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + int result = 0; + for(Node KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry)) + if(filter.test(entry.key)) result++; + return result; + } + } + + static class AscendingNaivgableSubMap KEY_VALUE_GENERIC_TYPE extends NavigableSubMap KEY_VALUE_GENERIC_TYPE + { + AscendingNaivgableSubMap(RB_TREE_MAP KEY_VALUE_GENERIC_TYPE map, boolean fromStart, KEY_TYPE lo, boolean loInclusive, boolean toEnd, KEY_TYPE hi, boolean hiInclusive) { + super(map, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); + } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap() { + if(inverse == null) inverse = new DescendingNaivgableSubMapKV_BRACES(map, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); + return inverse; + } + + @Override + public ObjectSet ENTRY_SET() { + if(entrySet == null) entrySet = new AscendingSubEntrySet(); + return entrySet; + } + + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE navigableKeySet() { + if(keySet == null) keySet = new KeySetKV_BRACES(this); + return keySet; + } + + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE keySet() { + return navigableKeySet(); + } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, boolean fromInclusive, KEY_TYPE toKey, boolean toInclusive) { + if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range"); + if (!inRange(toKey, toInclusive)) throw new IllegalArgumentException("toKey out of range"); + return new AscendingNaivgableSubMapKV_BRACES(map, false, fromKey, fromInclusive, false, toKey, toInclusive); + } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey, boolean inclusive) { + if (!inRange(toKey, inclusive)) throw new IllegalArgumentException("toKey out of range"); + return new AscendingNaivgableSubMapKV_BRACES(map, fromStart, lo, loInclusive, false, toKey, inclusive); + } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey, boolean inclusive) { + if (!inRange(fromKey, inclusive)) throw new IllegalArgumentException("fromKey out of range"); + return new AscendingNaivgableSubMapKV_BRACES(map, false, fromKey, inclusive, toEnd, hi, hiInclusive); + } + + @Override + protected Node KEY_VALUE_GENERIC_TYPE subLowest() { return absLowest(); } + @Override + protected Node KEY_VALUE_GENERIC_TYPE subHighest() { return absHighest(); } + @Override + protected Node KEY_VALUE_GENERIC_TYPE subCeiling(KEY_TYPE key) { return absCeiling(key); } + @Override + protected Node KEY_VALUE_GENERIC_TYPE subHigher(KEY_TYPE key) { return absHigher(key); } + @Override + protected Node KEY_VALUE_GENERIC_TYPE subFloor(KEY_TYPE key) { return absFloor(key); } + @Override + protected Node KEY_VALUE_GENERIC_TYPE subLower(KEY_TYPE key) { return absLower(key); } + + @Override + protected BI_ITERATOR KEY_GENERIC_TYPE keyIterator() { + return new AcsendingSubKeyIterator(absLowest(), absHighFence(), absLowFence()); + } + @Override + protected BI_ITERATOR KEY_GENERIC_TYPE keyIterator(KEY_TYPE element) { + return new AcsendingSubKeyIterator(absLower(element), absHighFence(), absLowFence()); + } + + @Override + protected VALUE_BI_ITERATOR VALUE_GENERIC_TYPE valueIterator() { + return new AcsendingSubValueIterator(absLowest(), absHighFence(), absLowFence()); + } + + @Override + protected BI_ITERATOR KEY_GENERIC_TYPE descendingKeyIterator() { + return new DecsendingSubKeyIterator(absHighest(), absLowFence(), absHighFence()); + } + + class AscendingSubEntrySet extends SubEntrySet { + @Override + public ObjectIterator iterator() { + return new AcsendingSubEntryIterator(absLowest(), absHighFence(), absLowFence()); + } + } + } + + static class DescendingNaivgableSubMap KEY_VALUE_GENERIC_TYPE extends NavigableSubMap KEY_VALUE_GENERIC_TYPE + { + COMPARATOR KEY_GENERIC_TYPE comparator; + DescendingNaivgableSubMap(RB_TREE_MAP KEY_VALUE_GENERIC_TYPE map, boolean fromStart, KEY_TYPE lo, boolean loInclusive, boolean toEnd, KEY_TYPE hi, boolean hiInclusive) { + super(map, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); +#if TYPE_OBJECT + comparator = Collections.reverseOrder(map.comparator()); +#else + comparator = map.comparator() == null ? COMPARATOR.of(Collections.reverseOrder()) : map.comparator().reversed(); +#endif + } + + @Override + public COMPARATOR KEY_GENERIC_TYPE comparator() { return comparator; } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap() { + if(inverse == null) inverse = new AscendingNaivgableSubMapKV_BRACES(map, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); + return inverse; + } + + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE navigableKeySet() { + if(keySet == null) keySet = new KeySetKV_BRACES(this); + return keySet; + } + + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE keySet() { + return navigableKeySet(); + } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, boolean fromInclusive, KEY_TYPE toKey, boolean toInclusive) { + if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range"); + if (!inRange(toKey, toInclusive)) throw new IllegalArgumentException("toKey out of range"); + return new DescendingNaivgableSubMapKV_BRACES(map, false, toKey, toInclusive, false, fromKey, fromInclusive); + } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey, boolean inclusive) { + if (!inRange(toKey, inclusive)) throw new IllegalArgumentException("toKey out of range"); + return new DescendingNaivgableSubMapKV_BRACES(map, false, toKey, inclusive, toEnd, hi, hiInclusive); + } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey, boolean inclusive) { + if (!inRange(fromKey, inclusive)) throw new IllegalArgumentException("fromKey out of range"); + return new DescendingNaivgableSubMapKV_BRACES(map, fromStart, lo, loInclusive, false, fromKey, inclusive); + } + + @Override + public ObjectSet ENTRY_SET() { + if(entrySet == null) entrySet = new DescendingSubEntrySet(); + return entrySet; + } + + @Override + protected Node KEY_VALUE_GENERIC_TYPE subLowest() { return absHighest(); } + @Override + protected Node KEY_VALUE_GENERIC_TYPE subHighest() { return absLowest(); } + @Override + protected Node KEY_VALUE_GENERIC_TYPE subCeiling(KEY_TYPE key) { return absFloor(key); } + @Override + protected Node KEY_VALUE_GENERIC_TYPE subHigher(KEY_TYPE key) { return absLower(key); } + @Override + protected Node KEY_VALUE_GENERIC_TYPE subFloor(KEY_TYPE key) { return absCeiling(key); } + @Override + protected Node KEY_VALUE_GENERIC_TYPE subLower(KEY_TYPE key) { return absHigher(key); } + @Override + protected Node KEY_VALUE_GENERIC_TYPE next(Node KEY_VALUE_GENERIC_TYPE entry) { return entry.previous(); } + @Override + protected Node KEY_VALUE_GENERIC_TYPE previous(Node KEY_VALUE_GENERIC_TYPE entry) { return entry.next(); } + + @Override + protected BI_ITERATOR KEY_GENERIC_TYPE keyIterator() { + return new DecsendingSubKeyIterator(absHighest(), absLowFence(), absHighFence()); + } + + @Override + protected BI_ITERATOR KEY_GENERIC_TYPE keyIterator(KEY_TYPE element) { + return new DecsendingSubKeyIterator(absHigher(element), absLowFence(), absHighFence()); + } + + @Override + protected VALUE_BI_ITERATOR VALUE_GENERIC_TYPE valueIterator() { + return new DecsendingSubValueIterator(absHighest(), absLowFence(), absHighFence()); + } + + @Override + protected BI_ITERATOR KEY_GENERIC_TYPE descendingKeyIterator() { + return new AcsendingSubKeyIterator(absLowest(), absHighFence(), absLowFence()); + } + + class DescendingSubEntrySet extends SubEntrySet { + @Override + public ObjectIterator iterator() { + return new DecsendingSubEntryIterator(absHighest(), absLowFence(), absHighFence()); + } + } + } + + static abstract class NavigableSubMap KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE + { + final RB_TREE_MAP KEY_VALUE_GENERIC_TYPE map; + final KEY_TYPE lo, hi; + final boolean fromStart, toEnd; + final boolean loInclusive, hiInclusive; + + NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE inverse; + NAVIGABLE_SET KEY_GENERIC_TYPE keySet; + ObjectSet entrySet; + VALUE_COLLECTION VALUE_GENERIC_TYPE values; + + NavigableSubMap(RB_TREE_MAP KEY_VALUE_GENERIC_TYPE map, boolean fromStart, KEY_TYPE lo, boolean loInclusive, boolean toEnd, KEY_TYPE hi, boolean hiInclusive) { + if (!fromStart && !toEnd) { + if (map.compare(lo, hi) > 0) throw new IllegalArgumentException("fromKey > toKey"); + } + else { + if (!fromStart) map.validate(lo); + if (!toEnd) map.validate(hi); + } + this.map = map; + this.fromStart = fromStart; + this.lo = lo; + this.loInclusive = loInclusive; + this.toEnd = toEnd; + this.hi = hi; + this.hiInclusive = hiInclusive; + } + +#if TYPE_OBJECT + public KEY_TYPE getDefaultMaxValue() { return map.getDefaultMaxValue(); } + public KEY_TYPE getDefaultMinValue() { return map.getDefaultMinValue(); } +#else + @Override + public void setDefaultMaxValue(KEY_TYPE e) { map.setDefaultMaxValue(e); } + @Override + public KEY_TYPE getDefaultMaxValue() { return map.getDefaultMaxValue(); } + @Override + public void setDefaultMinValue(KEY_TYPE e) { map.setDefaultMinValue(e); } + @Override + public KEY_TYPE getDefaultMinValue() { return map.getDefaultMinValue(); } +#endif + protected boolean isNullComparator() { return map.comparator() == null; } + + @Override + public ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE setDefaultReturnValue(VALUE_TYPE v) { + map.setDefaultReturnValue(v); + return this; + } + + @Override + public VALUE_TYPE getDefaultReturnValue() { return map.getDefaultReturnValue(); } + + @Override + public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { + if(values == null) values = new SubMapValues(); + return values; + } + + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE descendingKeySet() { + return descendingMap().navigableKeySet(); + } + + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE keySet() { + return navigableKeySet(); + } + + protected abstract Node KEY_VALUE_GENERIC_TYPE subLowest(); + protected abstract Node KEY_VALUE_GENERIC_TYPE subHighest(); + protected abstract Node KEY_VALUE_GENERIC_TYPE subCeiling(KEY_TYPE key); + protected abstract Node KEY_VALUE_GENERIC_TYPE subHigher(KEY_TYPE key); + protected abstract Node KEY_VALUE_GENERIC_TYPE subFloor(KEY_TYPE key); + protected abstract Node KEY_VALUE_GENERIC_TYPE subLower(KEY_TYPE key); + protected abstract BI_ITERATOR KEY_GENERIC_TYPE keyIterator(); + protected abstract BI_ITERATOR KEY_GENERIC_TYPE keyIterator(KEY_TYPE element); + protected abstract VALUE_BI_ITERATOR VALUE_GENERIC_TYPE valueIterator(); + protected abstract BI_ITERATOR KEY_GENERIC_TYPE descendingKeyIterator(); + protected KEY_TYPE lowKeyOrNull(Node KEY_VALUE_GENERIC_TYPE entry) { return entry == null ? getDefaultMinValue() : entry.key; } + protected KEY_TYPE highKeyOrNull(Node KEY_VALUE_GENERIC_TYPE entry) { return entry == null ? getDefaultMaxValue() : entry.key; } + protected Node KEY_VALUE_GENERIC_TYPE next(Node KEY_VALUE_GENERIC_TYPE entry) { return entry.next(); } + protected Node KEY_VALUE_GENERIC_TYPE previous(Node KEY_VALUE_GENERIC_TYPE entry) { return entry.previous(); } + + protected boolean tooLow(KEY_TYPE key) { + if (!fromStart) { + int c = map.compare(key, lo); + if (c < 0 || (c == 0 && !loInclusive)) return true; + } + return false; + } + + protected boolean tooHigh(KEY_TYPE key) { + if (!toEnd) { + int c = map.compare(key, hi); + if (c > 0 || (c == 0 && !hiInclusive)) return true; + } + return false; + } + protected boolean inRange(KEY_TYPE key) { return !tooLow(key) && !tooHigh(key); } + protected boolean inClosedRange(KEY_TYPE key) { return (fromStart || map.compare(key, lo) >= 0) && (toEnd || map.compare(hi, key) >= 0); } + protected boolean inRange(KEY_TYPE key, boolean inclusive) { return inclusive ? inRange(key) : inClosedRange(key); } + + protected Node KEY_VALUE_GENERIC_TYPE absLowest() { + Node KEY_VALUE_GENERIC_TYPE e = (fromStart ? map.first : (loInclusive ? map.findCeilingNode(lo) : map.findHigherNode(lo))); + return (e == null || tooHigh(e.key)) ? null : e; + } + + protected Node KEY_VALUE_GENERIC_TYPE absHighest() { + Node KEY_VALUE_GENERIC_TYPE e = (toEnd ? map.last : (hiInclusive ? map.findFloorNode(hi) : map.findLowerNode(hi))); + return (e == null || tooLow(e.key)) ? null : e; + } + + protected Node KEY_VALUE_GENERIC_TYPE absCeiling(KEY_TYPE key) { + if (tooLow(key)) return absLowest(); + Node KEY_VALUE_GENERIC_TYPE e = map.findCeilingNode(key); + return (e == null || tooHigh(e.key)) ? null : e; + } + + protected Node KEY_VALUE_GENERIC_TYPE absHigher(KEY_TYPE key) { + if (tooLow(key)) return absLowest(); + Node KEY_VALUE_GENERIC_TYPE e = map.findHigherNode(key); + return (e == null || tooHigh(e.key)) ? null : e; + } + + protected Node KEY_VALUE_GENERIC_TYPE absFloor(KEY_TYPE key) { + if (tooHigh(key)) return absHighest(); + Node KEY_VALUE_GENERIC_TYPE e = map.findFloorNode(key); + return (e == null || tooLow(e.key)) ? null : e; + } + + protected Node KEY_VALUE_GENERIC_TYPE absLower(KEY_TYPE key) { + if (tooHigh(key)) return absHighest(); + Node KEY_VALUE_GENERIC_TYPE e = map.findLowerNode(key); + return (e == null || tooLow(e.key)) ? null : e; + } + + protected Node KEY_VALUE_GENERIC_TYPE absHighFence() { return (toEnd ? null : (hiInclusive ? map.findHigherNode(hi) : map.findCeilingNode(hi))); } + protected Node KEY_VALUE_GENERIC_TYPE absLowFence() { return (fromStart ? null : (loInclusive ? map.findLowerNode(lo) : map.findFloorNode(lo))); } + + @Override + public COMPARATOR KEY_GENERIC_TYPE comparator() { return map.comparator(); } + + @Override + public KEY_TYPE POLL_FIRST_ENTRY_KEY() { + Node KEY_VALUE_GENERIC_TYPE entry = subLowest(); + if(entry != null) { + KEY_TYPE result = entry.key; + map.removeNode(entry); + return result; + } + return getDefaultMinValue(); + } + + @Override + public KEY_TYPE POLL_LAST_ENTRY_KEY() { + Node KEY_VALUE_GENERIC_TYPE entry = subHighest(); + if(entry != null) { + KEY_TYPE result = entry.key; + map.removeNode(entry); + return result; + } + return getDefaultMaxValue(); + } + + @Override + public VALUE_TYPE FIRST_ENTRY_VALUE() { + Node KEY_VALUE_GENERIC_TYPE entry = subLowest(); + if(entry == null) throw new NoSuchElementException(); + return entry.value; + } + + @Override + public VALUE_TYPE LAST_ENTRY_VALUE() { + Node KEY_VALUE_GENERIC_TYPE entry = subHighest(); + if(entry == null) throw new NoSuchElementException(); + return entry.value; + } + + @Override + public KEY_TYPE FIRST_ENTRY_KEY() { + Node KEY_VALUE_GENERIC_TYPE entry = subLowest(); + if(entry == null) throw new NoSuchElementException(); + return entry.key; + } + + @Override + public KEY_TYPE LAST_ENTRY_KEY() { + Node KEY_VALUE_GENERIC_TYPE entry = subHighest(); + if(entry == null) throw new NoSuchElementException(); + return entry.key; + } + + @Override + public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { + if (!inRange(key)) throw new IllegalArgumentException("key out of range"); + return map.put(key, value); + } + + @Override + public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { + if (!inRange(key)) throw new IllegalArgumentException("key out of range"); + return map.putIfAbsent(key, value); + } + +#if VALUE_PRIMITIVES + @Override + public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { + if(!inRange(key)) throw new IllegalArgumentException("key out of range"); + return map.addTo(key, value); + } + + @Override + public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { + if(!inRange(key)) throw new IllegalArgumentException("key out of range"); + return map.subFrom(key, value); + } + +#endif +#if TYPE_OBJECT + @Override + public boolean containsKey(Object key) { return inRange((CLASS_TYPE)key) && map.containsKey(key); } +#else + @Override + public boolean containsKey(KEY_TYPE key) { return inRange(key) && map.containsKey(key); } + +#endif + @Override + public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { + Objects.requireNonNull(mappingFunction); +#if TYPE_OBJECT + map.validate(key); +#endif + if(!inRange(key)) return getDefaultReturnValue(); + Node KEY_VALUE_GENERIC_TYPE entry = map.findNode(key); + if(entry == null || VALUE_EQUALS(entry.value, getDefaultReturnValue())) return getDefaultReturnValue(); + VALUE_TYPE newValue = mappingFunction.apply(key, entry.value); + if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { + map.removeNode(entry); + return newValue; + } + entry.value = newValue; + return newValue; + } + + @Override + public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { + return inRange(key) ? map.REMOVE_VALUE(key) : getDefaultReturnValue(); + } + + @Override + public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { + return inRange(key) ? map.REMOVE_VALUEOrDefault(key, defaultValue) : defaultValue; + } + +#if TYPE_OBJECT && VALUE_OBJECT + @Override + public boolean remove(Object key, Object value) { + return inRange((CLASS_TYPE)key) && map.remove(key, value); + } + +#else + @Override + public boolean remove(KEY_TYPE key, VALUE_TYPE value) { + return inRange(key) && map.remove(key, value); + } + +#endif + + @Override + public VALUE_TYPE GET_VALUE(KEY_TYPE key) { + return inRange(key) ? map.GET_VALUE(key) : getDefaultReturnValue(); + } + +#if TYPE_OBJECT && VALUE_OBJECT + @Override + public VALUE_TYPE getOrDefault(Object key, VALUE_TYPE defaultValue) { + return inRange((CLASS_TYPE)key) ? map.getOrDefault(key, defaultValue) : getDefaultReturnValue(); + } + +#else + @Override + public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { + return inRange(key) ? map.getOrDefault(key, defaultValue) : getDefaultReturnValue(); + } + +#endif + + @Override + public KEY_TYPE lowerKey(KEY_TYPE key) { return lowKeyOrNull(subLower(key)); } + @Override + public KEY_TYPE floorKey(KEY_TYPE key) { return lowKeyOrNull(subFloor(key)); } + @Override + public KEY_TYPE ceilingKey(KEY_TYPE key) { return highKeyOrNull(subCeiling(key)); } + @Override + public KEY_TYPE higherKey(KEY_TYPE key) { return highKeyOrNull(subHigher(key)); } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE lowerEntry(KEY_TYPE key) { return subLower(key); } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE floorEntry(KEY_TYPE key) { return subFloor(key); } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE ceilingEntry(KEY_TYPE key) { return subCeiling(key); } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE higherEntry(KEY_TYPE key) { return subHigher(key); } + + @Override + public boolean isEmpty() { + if(fromStart && toEnd) return map.isEmpty(); + Node KEY_VALUE_GENERIC_TYPE n = absLowest(); + return n == null || tooHigh(n.key); + } + + @Override + public int size() { return fromStart && toEnd ? map.size() : entrySet().size(); } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE firstEntry() { + Node KEY_VALUE_GENERIC_TYPE entry = subLowest(); + return entry == null ? null : entry.export(); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE lastEntry() { + Node KEY_VALUE_GENERIC_TYPE entry = subHighest(); + return entry == null ? null : entry.export(); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirstEntry() { + Node KEY_VALUE_GENERIC_TYPE entry = subLowest(); + if(entry != null) { + MAP.Entry KEY_VALUE_GENERIC_TYPE result = entry.export(); + map.removeNode(entry); + return result; + } + return null; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLastEntry() { + Node KEY_VALUE_GENERIC_TYPE entry = subHighest(); + if(entry != null) { + MAP.Entry KEY_VALUE_GENERIC_TYPE result = entry.export(); + map.removeNode(entry); + return result; + } + return null; + } + + abstract class SubEntrySet extends AbstractObjectSet { + @Override + public int size() { + if (fromStart && toEnd) return map.size(); + int size = 0; + for(ObjectIterator iter = iterator();iter.hasNext();iter.next(),size++); + return size; + } + + @Override + public boolean isEmpty() { + Node KEY_VALUE_GENERIC_TYPE n = absLowest(); + return n == null || tooHigh(n.key); + } + + @Override + public boolean contains(Object o) { + if (!(o instanceof Map.Entry)) return false; + if(o instanceof MAP.Entry) + { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE) o; +#if TYPE_OBJECT + if(entry.ENTRY_KEY() == null && isNullComparator()) return false; +#endif + KEY_TYPE key = entry.ENTRY_KEY(); + if (!inRange(key)) return false; + Node KEY_VALUE_GENERIC_TYPE node = map.findNode(key); + return node != null && VALUE_EQUALS(entry.ENTRY_VALUE(), node.ENTRY_VALUE()); + } + Map.Entry entry = (Map.Entry) o; + if(entry.getKey() == null && isNullComparator()) return false; + CLASS_TYPE key = (CLASS_TYPE)entry.getKey(); + if (!inRange(key)) return false; + Node KEY_VALUE_GENERIC_TYPE node = map.findNode(key); + return node != null && Objects.equals(entry.getValue(), VALUE_TO_OBJ(node.ENTRY_VALUE())); + } + + @Override + public boolean remove(Object o) { + if (!(o instanceof Map.Entry)) return false; + if(o instanceof MAP.Entry) + { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE) o; + KEY_TYPE key = entry.ENTRY_KEY(); + if (!inRange(key)) return false; + Node KEY_VALUE_GENERIC_TYPE node = map.findNode(key); + if (node != null && VALUE_EQUALS(node.ENTRY_VALUE(), entry.ENTRY_VALUE())) { + map.removeNode(node); + return true; + } + return false; + } + Map.Entry entry = (Map.Entry) o; + CLASS_TYPE key = (CLASS_TYPE)entry.getKey(); + if (!inRange(key)) return false; + Node KEY_VALUE_GENERIC_TYPE node = map.findNode(key); + if (node != null && Objects.equals(node.getValue(), entry.getValue())) { + map.removeNode(node); + return true; + } + return false; + } + + @Override + public void forEach(Consumer action) { + Objects.requireNonNull(action); + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) + action.accept(new BasicEntryKV_BRACES(entry.key, entry.value)); + } + + @Override + public void forEachIndexed(IntObjectConsumer action) { + Objects.requireNonNull(action); + int index = 0; + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) + action.accept(index++, new BasicEntryKV_BRACES(entry.key, entry.value)); + } + + @Override + public void forEach(E input, ObjectObjectConsumer action) { + Objects.requireNonNull(action); + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) + action.accept(input, new BasicEntryKV_BRACES(entry.key, entry.value)); + } + + @Override + public boolean matchesAny(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return false; + BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { + subEntry.set(entry.key, entry.value); + if(filter.test(subEntry)) return true; + } + return false; + } + + @Override + public boolean matchesNone(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { + subEntry.set(entry.key, entry.value); + if(filter.test(subEntry)) return false; + } + return true; + } + + @Override + public boolean matchesAll(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { + subEntry.set(entry.key, entry.value); + if(!filter.test(subEntry)) return false; + } + return true; + } + + @Override + public E reduce(E identity, BiFunction operator) { + Objects.requireNonNull(operator); + E state = identity; + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { + state = operator.apply(state, new BasicEntryKV_BRACES(entry.key, entry.value)); + } + return state; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE reduce(ObjectObjectUnaryOperator operator) { + Objects.requireNonNull(operator); + MAP.Entry KEY_VALUE_GENERIC_TYPE state = null; + boolean empty = true; + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { + if(empty) { + empty = false; + state = new BasicEntryKV_BRACES(entry.key, entry.value); + continue; + } + state = operator.apply(state, new BasicEntryKV_BRACES(entry.key, entry.value)); + } + return state; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE findFirst(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return null; + BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { + subEntry.set(entry.key, entry.value); + if(filter.test(subEntry)) return subEntry; + } + return null; + } + + @Override + public int count(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return 0; + int result = 0; + BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { + subEntry.set(entry.key, entry.value); + if(filter.test(subEntry)) result++; + } + return result; + } + } + + final class SubMapValues extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { + @Override + public boolean add(VALUE_TYPE o) { throw new UnsupportedOperationException(); } + +#if VALUE_OBJECT + @Override + public boolean contains(Object e) { + return containsValue(e); + } + +#else + @Override + public boolean contains(VALUE_TYPE e) { + return containsValue(e); + } + +#endif + @Override + public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() { return valueIterator(); } + + @Override + public int size() { + return NavigableSubMap.this.size(); + } + + @Override + public void clear() { + NavigableSubMap.this.clear(); + } + + @Override + public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) { + Objects.requireNonNull(action); + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) + action.accept(entry.value); + } + + @Override + public void forEachIndexed(VALUE_BI_FROM_INT_CONSUMER VALUE_GENERIC_TYPE action) { + Objects.requireNonNull(action); + int index = 0; + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) + action.accept(index++, entry.value); + } + + @Override + public void forEach(E input, VALUE_BI_FROM_OBJECT_CONSUMER VSV_GENERIC_TYPE action) { + Objects.requireNonNull(action); + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) + action.accept(input, entry.value); + } + + @Override + public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) + if(filter.test(entry.value)) return true; + return false; + } + + @Override + public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) + if(filter.test(entry.value)) return false; + return true; + } + + @Override + public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) + if(!filter.test(entry.value)) return false; + return true; + } + +#if !VALUE_OBJECT + @Override + public VALUE_TYPE reduce(VALUE_TYPE identity, VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + VALUE_TYPE state = identity; + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) + state = operator.APPLY_VALUE(state, entry.value); + return state; + } + +#else + @Override + public VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction operator) { + Objects.requireNonNull(operator); + VALUE_SPECIAL_TYPE state = identity; + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) + state = operator.apply(state, entry.value); + return state; + } + +#endif + @Override + public VALUE_TYPE reduce(VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + VALUE_TYPE state = EMPTY_VALUE; + boolean empty = true; + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) { + if(empty) { + empty = false; + state = entry.value; + continue; + } + state = operator.APPLY_VALUE(state, entry.value); + } + return state; + } + + @Override + public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) + if(filter.test(entry.value)) return entry.value; + return EMPTY_VALUE; + } + + @Override + public int count(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + int result = 0; + for(Node KEY_VALUE_GENERIC_TYPE entry = subLowest(), last = subHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) + if(filter.test(entry.value)) result++; + return result; + } + } + + class DecsendingSubEntryIterator extends SubMapEntryIterator implements ObjectBidirectionalIterator + { + public DecsendingSubEntryIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence) { + super(first, forwardFence, backwardFence, false); + } + + @Override + protected Node KEY_VALUE_GENERIC_TYPE moveNext(Node KEY_VALUE_GENERIC_TYPE node) { + return node.previous(); + } + + @Override + protected Node KEY_VALUE_GENERIC_TYPE movePrevious(Node KEY_VALUE_GENERIC_TYPE node) { + return node.next(); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { + if(!hasPrevious()) throw new NoSuchElementException(); + return previousEntry(); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { + if(!hasNext()) throw new NoSuchElementException(); + return nextEntry(); + } + } + + class AcsendingSubEntryIterator extends SubMapEntryIterator implements ObjectBidirectionalIterator + { + public AcsendingSubEntryIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence) { + super(first, forwardFence, backwardFence, true); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { + if(!hasPrevious()) throw new NoSuchElementException(); + return previousEntry(); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { + if(!hasNext()) throw new NoSuchElementException(); + return nextEntry(); + } + } + + class DecsendingSubKeyIterator extends SubMapEntryIterator implements BI_ITERATOR KEY_GENERIC_TYPE + { + public DecsendingSubKeyIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence) { + super(first, forwardFence, backwardFence, false); + } + + @Override + protected Node KEY_VALUE_GENERIC_TYPE moveNext(Node KEY_VALUE_GENERIC_TYPE node) { + return node.previous(); + } + + @Override + protected Node KEY_VALUE_GENERIC_TYPE movePrevious(Node KEY_VALUE_GENERIC_TYPE node) { + return node.next(); + } + + @Override + public KEY_TYPE PREVIOUS() { + if(!hasPrevious()) throw new NoSuchElementException(); + return previousEntry().key; + } + + @Override + public KEY_TYPE NEXT() { + if(!hasNext()) throw new NoSuchElementException(); + return nextEntry().key; + } + } + + class AcsendingSubKeyIterator extends SubMapEntryIterator implements BI_ITERATOR KEY_GENERIC_TYPE + { + public AcsendingSubKeyIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence) { + super(first, forwardFence, backwardFence, true); + } + + @Override + public KEY_TYPE PREVIOUS() { + if(!hasPrevious()) throw new NoSuchElementException(); + return previousEntry().key; + } + + @Override + public KEY_TYPE NEXT() { + if(!hasNext()) throw new NoSuchElementException(); + return nextEntry().key; + } + } + + class AcsendingSubValueIterator extends SubMapEntryIterator implements VALUE_BI_ITERATOR VALUE_GENERIC_TYPE + { + public AcsendingSubValueIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence) { + super(first, forwardFence, backwardFence, true); + } + + @Override + public VALUE_TYPE VALUE_PREVIOUS() { + if(!hasPrevious()) throw new NoSuchElementException(); + return previousEntry().value; + } + + @Override + public VALUE_TYPE VALUE_NEXT() { + if(!hasNext()) throw new NoSuchElementException(); + return nextEntry().value; + } + } + + class DecsendingSubValueIterator extends SubMapEntryIterator implements VALUE_BI_ITERATOR VALUE_GENERIC_TYPE + { + public DecsendingSubValueIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence) { + super(first, forwardFence, backwardFence, false); + } + + @Override + protected Node KEY_VALUE_GENERIC_TYPE moveNext(Node KEY_VALUE_GENERIC_TYPE node) { + return node.previous(); + } + + @Override + protected Node KEY_VALUE_GENERIC_TYPE movePrevious(Node KEY_VALUE_GENERIC_TYPE node) { + return node.next(); + } + + @Override + public VALUE_TYPE VALUE_PREVIOUS() { + if(!hasPrevious()) throw new NoSuchElementException(); + return previousEntry().value; + } + + @Override + public VALUE_TYPE VALUE_NEXT() { + if(!hasNext()) throw new NoSuchElementException(); + return nextEntry().value; + } + } + + abstract class SubMapEntryIterator + { + final boolean isForward; + boolean wasForward; + Node KEY_VALUE_GENERIC_TYPE lastReturned; + Node KEY_VALUE_GENERIC_TYPE next; + Node KEY_VALUE_GENERIC_TYPE previous; + boolean unboundForwardFence; + boolean unboundBackwardFence; + KEY_TYPE forwardFence; + KEY_TYPE backwardFence; + + public SubMapEntryIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence, boolean isForward) { + next = first; + previous = first == null ? null : movePrevious(first); + this.forwardFence = forwardFence == null ? EMPTY_KEY_VALUE : forwardFence.key; + this.backwardFence = backwardFence == null ? EMPTY_KEY_VALUE : backwardFence.key; + unboundForwardFence = forwardFence == null; + unboundBackwardFence = backwardFence == null; + this.isForward = isForward; + } + + protected Node KEY_VALUE_GENERIC_TYPE moveNext(Node KEY_VALUE_GENERIC_TYPE node) { + return node.next(); + } + + protected Node KEY_VALUE_GENERIC_TYPE movePrevious(Node KEY_VALUE_GENERIC_TYPE node) { + return node.previous(); + } + + public boolean hasNext() { + return next != null && (unboundForwardFence || next.key != forwardFence); + } + + protected Node KEY_VALUE_GENERIC_TYPE nextEntry() { + lastReturned = next; + previous = next; + Node KEY_VALUE_GENERIC_TYPE result = next; + next = moveNext(next); + wasForward = isForward; + return result; + } + + public boolean hasPrevious() { + return previous != null && (unboundBackwardFence || previous.key != backwardFence); + } + + protected Node KEY_VALUE_GENERIC_TYPE previousEntry() { + lastReturned = previous; + next = previous; + Node KEY_VALUE_GENERIC_TYPE result = previous; + previous = movePrevious(previous); + wasForward = !isForward; + return result; + } + + public void remove() { + if(lastReturned == null) throw new IllegalStateException(); + if(next == lastReturned) next = moveNext(next); + if(previous == lastReturned) previous = movePrevious(previous); + if(wasForward && lastReturned.needsSuccessor()) next = lastReturned; + map.removeNode(lastReturned); + lastReturned = null; + } + } + } + + class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE + { + @Override + public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() { + return new AscendingValueIterator(first); + } + + @Override + public boolean add(VALUE_TYPE e) { throw new UnsupportedOperationException(); } + + @Override + public void clear() { + RB_TREE_MAP.this.clear(); + } + + @Override + public int size() { + return RB_TREE_MAP.this.size; + } + +#if VALUE_OBJECT + @Override + public boolean contains(Object e) { + return containsValue(e); + } + +#else + @Override + public boolean contains(VALUE_TYPE e) { + return containsValue(e); + } + +#endif + @Override + public boolean remove(Object o) { + for(Node KEY_VALUE_GENERIC_TYPE entry = first; entry != null; entry = entry.next()) { + if(Objects.equals(entry.getValue(), o)) { + removeNode(entry); + return true; + } + } + return false; + } + + @Override + public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) { + Objects.requireNonNull(action); + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + action.accept(entry.value); + } + + @Override + public void forEachIndexed(VALUE_BI_FROM_INT_CONSUMER VALUE_GENERIC_TYPE action) { + Objects.requireNonNull(action); + int index = 0; + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + action.accept(index++, entry.value); + } + + @Override + public void forEach(E input, VALUE_BI_FROM_OBJECT_CONSUMER VSV_GENERIC_TYPE action) { + Objects.requireNonNull(action); + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + action.accept(input, entry.value); + } + + @Override + public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + if(filter.test(entry.value)) return true; + return false; + } + + @Override + public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + if(filter.test(entry.value)) return false; + return true; + } + + @Override + public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + if(!filter.test(entry.value)) return false; + return true; + } + + #if !VALUE_OBJECT + @Override + public VALUE_TYPE reduce(VALUE_TYPE identity, VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + VALUE_TYPE state = identity; + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + state = operator.APPLY_VALUE(state, entry.value); + return state; + } + + #else + @Override + public VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction operator) { + Objects.requireNonNull(operator); + VALUE_SPECIAL_TYPE state = identity; + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + state = operator.apply(state, entry.value); + return state; + } + + #endif + @Override + public VALUE_TYPE reduce(VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) { + Objects.requireNonNull(operator); + VALUE_TYPE state = EMPTY_VALUE; + boolean empty = true; + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { + if(empty) { + empty = false; + state = entry.value; + continue; + } + state = operator.APPLY_VALUE(state, entry.value); + } + return state; + } + + @Override + public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + if(filter.test(entry.value)) return entry.value; + return EMPTY_VALUE; + } + + @Override + public int count(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) { + Objects.requireNonNull(filter); + int result = 0; + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + if(filter.test(entry.value)) result++; + return result; + } + } + + class EntrySet extends AbstractObjectSet { + + @Override + public ObjectIterator iterator() { + return new AscendingMapEntryIterator(first); + } + + @Override + public void clear() { + RB_TREE_MAP.this.clear(); + } + + @Override + public int size() { + return RB_TREE_MAP.this.size; + } + + @Override + public boolean contains(Object o) { + if (!(o instanceof Map.Entry)) return false; + if(o instanceof MAP.Entry) + { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE) o; +#if TYPE_OBJECT + if(entry.getKey() == null && comparator() == null) return false; +#endif + KEY_TYPE key = entry.ENTRY_KEY(); + Node KEY_VALUE_GENERIC_TYPE node = findNode(key); + return node != null && VALUE_EQUALS(entry.ENTRY_VALUE(), node.ENTRY_VALUE()); + } + Map.Entry entry = (Map.Entry) o; + if(entry.getKey() == null && comparator() == null) return false; +#if !TYPE_OBJECT + if(!(entry.getKey() instanceof CLASS_TYPE)) return false; +#endif + CLASS_TYPE key = (CLASS_TYPE)entry.getKey(); + Node KEY_VALUE_GENERIC_TYPE node = findNode(key); + return node != null && Objects.equals(entry.getValue(), VALUE_TO_OBJ(node.ENTRY_VALUE())); + } + + @Override + public boolean remove(Object o) { + if (!(o instanceof Map.Entry)) return false; + if(o instanceof MAP.Entry) + { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE) o; + KEY_TYPE key = entry.ENTRY_KEY(); + Node KEY_VALUE_GENERIC_TYPE node = findNode(key); + if (node != null && VALUE_EQUALS(entry.ENTRY_VALUE(), node.ENTRY_VALUE())) { + removeNode(node); + return true; + } + return false; + } + Map.Entry entry = (Map.Entry) o; + CLASS_TYPE key = (CLASS_TYPE)entry.getKey(); + Node KEY_VALUE_GENERIC_TYPE node = findNode(key); + if (node != null && Objects.equals(entry.getValue(), VALUE_TO_OBJ(node.ENTRY_VALUE()))) { + removeNode(node); + return true; + } + return false; + } + + @Override + public void forEach(Consumer action) { + Objects.requireNonNull(action); + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + action.accept(new BasicEntryKV_BRACES(entry.key, entry.value)); + } + + @Override + public void forEachIndexed(IntObjectConsumer action) { + Objects.requireNonNull(action); + int index = 0; + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + action.accept(index++, new BasicEntryKV_BRACES(entry.key, entry.value)); + } + + @Override + public void forEach(E input, ObjectObjectConsumer action) { + Objects.requireNonNull(action); + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) + action.accept(input, new BasicEntryKV_BRACES(entry.key, entry.value)); + } + + @Override + public boolean matchesAny(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return false; + BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { + subEntry.set(entry.key, entry.value); + if(filter.test(subEntry)) return true; + } + return false; + } + + @Override + public boolean matchesNone(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { + subEntry.set(entry.key, entry.value); + if(filter.test(subEntry)) return false; + } + return true; + } + + @Override + public boolean matchesAll(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return true; + BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { + subEntry.set(entry.key, entry.value); + if(!filter.test(subEntry)) return false; + } + return true; + } + + @Override + public E reduce(E identity, BiFunction operator) { + Objects.requireNonNull(operator); + E state = identity; + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { + state = operator.apply(state, new BasicEntryKV_BRACES(entry.key, entry.value)); + } + return state; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE reduce(ObjectObjectUnaryOperator operator) { + Objects.requireNonNull(operator); + MAP.Entry KEY_VALUE_GENERIC_TYPE state = null; + boolean empty = true; + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { + if(empty) { + empty = false; + state = new BasicEntryKV_BRACES(entry.key, entry.value); + continue; + } + state = operator.apply(state, new BasicEntryKV_BRACES(entry.key, entry.value)); + } + return state; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE findFirst(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return null; + BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { + subEntry.set(entry.key, entry.value); + if(filter.test(subEntry)) return subEntry; + } + return null; + } + + @Override + public int count(Predicate filter) { + Objects.requireNonNull(filter); + if(size() <= 0) return 0; + int result = 0; + BasicEntry KEY_VALUE_GENERIC_TYPE subEntry = new BasicEntryKV_BRACES(); + for(Node KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) { + subEntry.set(entry.key, entry.value); + if(filter.test(subEntry)) result++; + } + return result; + } + } + + class DescendingKeyIterator extends MapEntryIterator implements BI_ITERATOR KEY_GENERIC_TYPE + { + public DescendingKeyIterator(Node KEY_VALUE_GENERIC_TYPE first) { + super(first, false); + } + + @Override + protected Node KEY_VALUE_GENERIC_TYPE moveNext(Node KEY_VALUE_GENERIC_TYPE node) { + return node.previous(); + } + + @Override + protected Node KEY_VALUE_GENERIC_TYPE movePrevious(Node KEY_VALUE_GENERIC_TYPE node) { + return node.next(); + } + + @Override + public KEY_TYPE PREVIOUS() { + if(!hasPrevious()) throw new NoSuchElementException(); + return previousEntry().key; + } + + @Override + public KEY_TYPE NEXT() { + if(!hasNext()) throw new NoSuchElementException(); + return nextEntry().key; + } + } + + class AscendingMapEntryIterator extends MapEntryIterator implements ObjectBidirectionalIterator + { + public AscendingMapEntryIterator(Node KEY_VALUE_GENERIC_TYPE first) + { + super(first, true); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() { + if(!hasPrevious()) throw new NoSuchElementException(); + return previousEntry(); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { + if(!hasNext()) throw new NoSuchElementException(); + return nextEntry(); + } + } + + class AscendingValueIterator extends MapEntryIterator implements VALUE_BI_ITERATOR VALUE_GENERIC_TYPE + { + public AscendingValueIterator(Node KEY_VALUE_GENERIC_TYPE first) { + super(first, true); + } + + @Override + public VALUE_TYPE VALUE_PREVIOUS() { + if(!hasPrevious()) throw new NoSuchElementException(); + return previousEntry().value; + } + + @Override + public VALUE_TYPE VALUE_NEXT() { + if(!hasNext()) throw new NoSuchElementException(); + return nextEntry().value; + } + } + + class AscendingKeyIterator extends MapEntryIterator implements BI_ITERATOR KEY_GENERIC_TYPE + { + public AscendingKeyIterator(Node KEY_VALUE_GENERIC_TYPE first) { + super(first, true); + } + + @Override + public KEY_TYPE PREVIOUS() { + if(!hasPrevious()) throw new NoSuchElementException(); + return previousEntry().key; + } + + @Override + public KEY_TYPE NEXT() { + if(!hasNext()) throw new NoSuchElementException(); + return nextEntry().key; + } + } + + abstract class MapEntryIterator + { + final boolean isForward; + boolean wasMoved = false; + Node KEY_VALUE_GENERIC_TYPE lastReturned; + Node KEY_VALUE_GENERIC_TYPE next; + Node KEY_VALUE_GENERIC_TYPE previous; + + public MapEntryIterator(Node KEY_VALUE_GENERIC_TYPE first, boolean isForward) { + next = first; + previous = first == null ? null : movePrevious(first); + this.isForward = isForward; + } + + protected Node KEY_VALUE_GENERIC_TYPE moveNext(Node KEY_VALUE_GENERIC_TYPE node) { + return node.next(); + } + + protected Node KEY_VALUE_GENERIC_TYPE movePrevious(Node KEY_VALUE_GENERIC_TYPE node) { + return node.previous(); + } + + public boolean hasNext() { + return next != null; + } + + protected Node KEY_VALUE_GENERIC_TYPE nextEntry() { + lastReturned = next; + previous = next; + Node KEY_VALUE_GENERIC_TYPE result = next; + next = moveNext(next); + wasMoved = isForward; + return result; + } + + public boolean hasPrevious() { + return previous != null; + } + + protected Node KEY_VALUE_GENERIC_TYPE previousEntry() { + lastReturned = previous; + next = previous; + Node KEY_VALUE_GENERIC_TYPE result = previous; + previous = movePrevious(previous); + wasMoved = !isForward; + return result; + } + + public void remove() { + if(lastReturned == null) throw new IllegalStateException(); + if(next == lastReturned) next = moveNext(next); + if(previous == lastReturned) previous = movePrevious(previous); + if(wasMoved && lastReturned.needsSuccessor()) next = lastReturned; + removeNode(lastReturned); + lastReturned = null; + } + } + + private static final class Node KEY_VALUE_GENERIC_TYPE implements MAP.Entry KEY_VALUE_GENERIC_TYPE + { + static final int BLACK = 1; + + KEY_TYPE key; + VALUE_TYPE value; + int state; + Node KEY_VALUE_GENERIC_TYPE parent; + Node KEY_VALUE_GENERIC_TYPE left; + Node KEY_VALUE_GENERIC_TYPE right; + + Node(KEY_TYPE key, VALUE_TYPE value, Node KEY_VALUE_GENERIC_TYPE parent) { + this.key = key; + this.value = value; + this.parent = parent; + } + + Node KEY_VALUE_GENERIC_TYPE copy() { + Node KEY_VALUE_GENERIC_TYPE entry = new NodeKV_BRACES(key, value, null); + entry.state = state; + if(left != null) { + Node KEY_VALUE_GENERIC_TYPE newLeft = left.copy(); + entry.left = newLeft; + newLeft.parent = entry; + } + if(right != null) { + Node KEY_VALUE_GENERIC_TYPE newRight = right.copy(); + entry.right = newRight; + newRight.parent = entry; + } + return entry; + } + + public BasicEntry KEY_VALUE_GENERIC_TYPE export() { + return new BasicEntryKV_BRACES(key, value); + } + + @Override + public KEY_TYPE ENTRY_KEY() { + return key; + } + + @Override + public VALUE_TYPE ENTRY_VALUE() { + return value; + } + + @Override + public VALUE_TYPE setValue(VALUE_TYPE value) { + VALUE_TYPE oldValue = this.value; + this.value = value; + return oldValue; + } + +#if VALUE_PRIMITIVES + VALUE_TYPE addTo(VALUE_TYPE value) { + VALUE_TYPE oldValue = this.value; + this.value += value; + return oldValue; + } + + VALUE_TYPE subFrom(VALUE_TYPE value) { + VALUE_TYPE oldValue = this.value; + this.value -= value; + return oldValue; + } + +#endif + @Override + public boolean equals(Object obj) { + if(obj instanceof Map.Entry) { + if(obj instanceof MAP.Entry) { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)obj; +#if TYPE_OBJECT + if(entry.ENTRY_KEY() == null) return false; +#endif + return KEY_EQUALS(key, entry.ENTRY_KEY()) && VALUE_EQUALS(value, entry.ENTRY_VALUE()); + } + Map.Entry entry = (Map.Entry)obj; + Object otherKey = entry.getKey(); + if(otherKey == null) return false; + Object otherValue = entry.getValue(); +#if TYPE_OBJECT && VALUE_OBJECT + return KEY_EQUALS(key, otherKey) && VALUE_EQUALS(value, otherValue); +#else if TYPE_OBJECT + return otherValue instanceof CLASS_VALUE_TYPE && KEY_EQUALS(key, otherKey) && VALUE_EQUALS(value, CLASS_TO_VALUE(otherValue)); +#else if VALUE_OBJECT + return otherKey instanceof CLASS_TYPE && KEY_EQUALS(key, CLASS_TO_KEY(otherKey)) && VALUE_EQUALS(value, otherValue); +#else + return otherKey instanceof CLASS_TYPE && otherValue instanceof CLASS_VALUE_TYPE && KEY_EQUALS(key, CLASS_TO_KEY(otherKey)) && VALUE_EQUALS(value, CLASS_TO_VALUE(otherValue)); +#endif + } + return false; + } + + @Override + public int hashCode() { + return KEY_TO_HASH(key) ^ VALUE_TO_HASH(value); + } + + @Override + public String toString() { + return KEY_TO_STRING(key) + "=" + VALUE_TO_STRING(value); + } + + boolean isBlack() { + return (state & BLACK) != 0; + } + + void setBlack(boolean value) { + if(value) state |= BLACK; + else state &= ~BLACK; + } + + boolean needsSuccessor() { return left != null && right != null; } + + boolean replace(Node KEY_VALUE_GENERIC_TYPE entry) { + if(entry != null) entry.parent = parent; + if(parent != null) { + if(parent.left == this) parent.left = entry; + else parent.right = entry; + } + return parent == null; + } + + Node KEY_VALUE_GENERIC_TYPE next() { + if(right != null) { + Node KEY_VALUE_GENERIC_TYPE parent = right; + while(parent.left != null) parent = parent.left; + return parent; + } + Node KEY_VALUE_GENERIC_TYPE parent = this.parent; + Node KEY_VALUE_GENERIC_TYPE control = this; + while(parent != null && control == parent.right) { + control = parent; + parent = parent.parent; + } + return parent; + } + + Node KEY_VALUE_GENERIC_TYPE previous() { + if(left != null) { + Node KEY_VALUE_GENERIC_TYPE parent = left; + while(parent.right != null) parent = parent.right; + return parent; + } + Node KEY_VALUE_GENERIC_TYPE parent = this.parent; + Node KEY_VALUE_GENERIC_TYPE control = this; + while(parent != null && control == parent.left) { + control = parent; + parent = parent.parent; + } + return parent; + } + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/collections/templates/maps/interfaces/ConcurrentMap.template b/src/builder/resources/speiger/assets/collections/templates/maps/interfaces/ConcurrentMap.template index f38524c..bb8f0d4 100644 --- a/src/builder/resources/speiger/assets/collections/templates/maps/interfaces/ConcurrentMap.template +++ b/src/builder/resources/speiger/assets/collections/templates/maps/interfaces/ConcurrentMap.template @@ -1,95 +1,95 @@ -package speiger.src.collections.PACKAGE.maps.interfaces; - -import java.util.concurrent.ConcurrentMap; -import java.util.function.BiConsumer; -import java.util.function.BiFunction; -import java.util.function.Function; - -/** - * A type specific ConcurrentMap interface that reduces boxing/unboxing. - * Since the interface adds nothing new. It is there just for completion sake. - * @Type(T) - * @ValueType(V) - */ -public interface CONCURRENT_MAP KEY_VALUE_GENERIC_TYPE extends ConcurrentMap, MAP KEY_VALUE_GENERIC_TYPE -{ - @Override - @Primitive - public default CLASS_VALUE_TYPE compute(CLASS_TYPE key, BiFunction mappingFunction) { - return MAP.super.compute(key, mappingFunction); - } - - @Override - @Primitive - public default CLASS_VALUE_TYPE computeIfAbsent(CLASS_TYPE key, Function mappingFunction) { - return MAP.super.computeIfAbsent(key, mappingFunction); - } - - @Override - @Primitive - public default CLASS_VALUE_TYPE computeIfPresent(CLASS_TYPE key, BiFunction mappingFunction) { - return MAP.super.computeIfPresent(key, mappingFunction); - } - - @Override - @Primitive - public default void forEach(BiConsumer action) { - MAP.super.forEach(action); - } - - @Override - @Primitive - public default CLASS_VALUE_TYPE merge(CLASS_TYPE key, CLASS_VALUE_TYPE value, BiFunction mappingFunction) { - return MAP.super.merge(key, value, mappingFunction); - } - -#if TYPE_OBJECT && VALUE_OBJECT - @Override - public CLASS_VALUE_TYPE getOrDefault(Object key, CLASS_VALUE_TYPE defaultValue); - @Override - public CLASS_VALUE_TYPE putIfAbsent(CLASS_TYPE key, CLASS_VALUE_TYPE value); - @Override - public boolean remove(Object key, Object value); - @Override - public boolean replace(CLASS_TYPE key, CLASS_VALUE_TYPE oldValue, CLASS_VALUE_TYPE newValue); - @Override - public CLASS_VALUE_TYPE replace(CLASS_TYPE key, CLASS_VALUE_TYPE value); - -#else - @Primitive - @Override - public default CLASS_VALUE_TYPE getOrDefault(Object key, CLASS_VALUE_TYPE defaultValue) { - return MAP.super.getOrDefault(key, defaultValue); - } - - @Override - @Primitive - public default CLASS_VALUE_TYPE putIfAbsent(CLASS_TYPE key, CLASS_VALUE_TYPE value) { - return MAP.super.putIfAbsent(key, value); - } - - @Override - @Deprecated - public default boolean remove(Object key, Object value) { - return MAP.super.remove(key, value); - } - - @Override - @Deprecated - public default boolean replace(CLASS_TYPE key, CLASS_VALUE_TYPE oldValue, CLASS_VALUE_TYPE newValue) { - return MAP.super.replace(key, oldValue, newValue); - } - - @Override - @Deprecated - public default CLASS_VALUE_TYPE replace(CLASS_TYPE key, CLASS_VALUE_TYPE value) { - return MAP.super.replace(key, value); - } - -#endif - @Override - @Deprecated - public default void replaceAll(BiFunction mappingFunction) { - MAP.super.replaceAll(mappingFunction); - } +package speiger.src.collections.PACKAGE.maps.interfaces; + +import java.util.concurrent.ConcurrentMap; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Function; + +/** + * A type specific ConcurrentMap interface that reduces boxing/unboxing. + * Since the interface adds nothing new. It is there just for completion sake. + * @Type(T) + * @ValueType(V) + */ +public interface CONCURRENT_MAP KEY_VALUE_GENERIC_TYPE extends ConcurrentMap, MAP KEY_VALUE_GENERIC_TYPE +{ + @Override + @Primitive + public default CLASS_VALUE_TYPE compute(CLASS_TYPE key, BiFunction mappingFunction) { + return MAP.super.compute(key, mappingFunction); + } + + @Override + @Primitive + public default CLASS_VALUE_TYPE computeIfAbsent(CLASS_TYPE key, Function mappingFunction) { + return MAP.super.computeIfAbsent(key, mappingFunction); + } + + @Override + @Primitive + public default CLASS_VALUE_TYPE computeIfPresent(CLASS_TYPE key, BiFunction mappingFunction) { + return MAP.super.computeIfPresent(key, mappingFunction); + } + + @Override + @Primitive + public default void forEach(BiConsumer action) { + MAP.super.forEach(action); + } + + @Override + @Primitive + public default CLASS_VALUE_TYPE merge(CLASS_TYPE key, CLASS_VALUE_TYPE value, BiFunction mappingFunction) { + return MAP.super.merge(key, value, mappingFunction); + } + +#if TYPE_OBJECT && VALUE_OBJECT + @Override + public CLASS_VALUE_TYPE getOrDefault(Object key, CLASS_VALUE_TYPE defaultValue); + @Override + public CLASS_VALUE_TYPE putIfAbsent(CLASS_TYPE key, CLASS_VALUE_TYPE value); + @Override + public boolean remove(Object key, Object value); + @Override + public boolean replace(CLASS_TYPE key, CLASS_VALUE_TYPE oldValue, CLASS_VALUE_TYPE newValue); + @Override + public CLASS_VALUE_TYPE replace(CLASS_TYPE key, CLASS_VALUE_TYPE value); + +#else + @Primitive + @Override + public default CLASS_VALUE_TYPE getOrDefault(Object key, CLASS_VALUE_TYPE defaultValue) { + return MAP.super.getOrDefault(key, defaultValue); + } + + @Override + @Primitive + public default CLASS_VALUE_TYPE putIfAbsent(CLASS_TYPE key, CLASS_VALUE_TYPE value) { + return MAP.super.putIfAbsent(key, value); + } + + @Override + @Deprecated + public default boolean remove(Object key, Object value) { + return MAP.super.remove(key, value); + } + + @Override + @Deprecated + public default boolean replace(CLASS_TYPE key, CLASS_VALUE_TYPE oldValue, CLASS_VALUE_TYPE newValue) { + return MAP.super.replace(key, oldValue, newValue); + } + + @Override + @Deprecated + public default CLASS_VALUE_TYPE replace(CLASS_TYPE key, CLASS_VALUE_TYPE value) { + return MAP.super.replace(key, value); + } + +#endif + @Override + @Deprecated + public default void replaceAll(BiFunction mappingFunction) { + MAP.super.replaceAll(mappingFunction); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/collections/templates/queues/AbstractPriorityQueue.template b/src/builder/resources/speiger/assets/collections/templates/queues/AbstractPriorityQueue.template index 3667f7b..670710d 100644 --- a/src/builder/resources/speiger/assets/collections/templates/queues/AbstractPriorityQueue.template +++ b/src/builder/resources/speiger/assets/collections/templates/queues/AbstractPriorityQueue.template @@ -1,46 +1,46 @@ -package speiger.src.collections.PACKAGE.queues; - -#if TYPE_OBJECT -import java.util.Objects; -#endif -import java.util.StringJoiner; - -/** - * Helper class that implements all the essential methods for the PriorityQueues - * @Type(T) - */ -public abstract class ABSTRACT_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_QUEUE KEY_GENERIC_TYPE -{ - @Override - public boolean equals(Object obj) { - if(obj instanceof PRIORITY_QUEUE) { - PRIORITY_QUEUE KEY_GENERIC_TYPE queue = (PRIORITY_QUEUE KEY_GENERIC_TYPE)obj; - if(queue.size() != size()) return false; - for(int i = 0,m=size();i c) { - for(Iterator iter = c.iterator();iter.hasNext();) - enqueue(iter.next()); - } - -#endif - - /** - * Method to extract a element from the PriorityQueue - * @return a element from the Queue - * @throws java.util.NoSuchElementException if no element is present - */ - public KEY_TYPE dequeue(); - - /** - * Peeking function to see whats inside the queue. - * @param index of the element that is requested to be viewed. - * @return the element that is requested - */ - public KEY_TYPE peek(int index); - /** - * Shows the element that is to be returned next - * @return the first element in the Queue - */ - public default KEY_TYPE first() { return peek(0); } - - /** - * Removes the first found element in the queue - * @param e the element that should be removed - * @return if a searched element was removed - */ - public boolean removeFirst(KEY_TYPE e); - /** - * Removes the last found element in the queue - * @param e the element that should be removed - * @return if a searched element was removed - */ - public boolean removeLast(KEY_TYPE e); - - /** - * Allows to notify the Queue to be revalidate its data - */ - public void onChanged(); - - /** - * A Function that does a shallow clone of the PriorityQueue itself. - * This function is more optimized then a copy constructor since the PriorityQueue does not have to be unsorted/resorted. - * It can be compared to Cloneable but with less exception risk - * @return a Shallow Copy of the PriorityQueue - * @note Wrappers and view PriorityQueues will not support this feature - */ - public PRIORITY_QUEUE KEY_GENERIC_TYPE copy(); - - /** - * @return the sorter of the Queue, can be null - */ - public COMPARATOR KEY_SUPER_GENERIC_TYPE comparator(); - -#if TYPE_OBJECT - /** - * @return draining iterator of the PriorityQueue - */ - public ITERATOR KEY_GENERIC_TYPE iterator(); - -#endif -#if QUEUES_FEATURE - /** - * Creates a Wrapped PriorityQueue that is Synchronized - * @return a new PriorityQueue that is synchronized - * @see PRIORITY_QUEUES#synchronize - */ - public default PRIORITY_QUEUE KEY_GENERIC_TYPE synchronizeQueue() { return PRIORITY_QUEUES.synchronize(this); } - - /** - * Creates a Wrapped PriorityQueue that is Synchronized - * @param mutex is the controller of the synchronization block - * @return a new PriorityQueue Wrapper that is synchronized - * @see PRIORITY_QUEUES#synchronize - */ - public default PRIORITY_QUEUE KEY_GENERIC_TYPE synchronizeQueue(Object mutex) { return PRIORITY_QUEUES.synchronize(this, mutex); } - -#endif - /** - * A method to drop the contents of the Queue without clearing the queue - * @Type(E) - * @return the contents of the queue into a seperate array. - */ - public default GENERIC_SPECIAL_KEY_BRACES KEY_SPECIAL_TYPE[] TO_ARRAY() { return TO_ARRAY(NEW_SPECIAL_KEY_ARRAY(size())); } - /** - * A method to drop the contents of the Queue without clearing the queue - * @param input where the elements should be inserted to. If it does not fit then it creates a new appropiatly created array - * @Type(E) - * @return the contents of the queue into a seperate array. - * @note if the Type is generic then a Object Array is created instead of a Type Array - */ - public GENERIC_SPECIAL_KEY_BRACES KEY_SPECIAL_TYPE[] TO_ARRAY(KEY_SPECIAL_TYPE[] input); -#if TYPE_OBJECT - /** - * A Helper function that simplifies the process of creating a new Array. - * @param action the array creation function - * @return an array containing all of the elements in this collection - * @see Collection#toArray(Object[]) - */ - default E[] TO_ARRAY(IntFunction action) { - return TO_ARRAY(action.apply(size())); - } -#endif +package speiger.src.collections.PACKAGE.queues; + +#if TYPE_OBJECT +import java.util.Comparator; +import java.util.Collection; +import java.util.Iterator; +import java.util.function.IntFunction; +#else +import speiger.src.collections.PACKAGE.functions.COMPARATOR; +#endif +import speiger.src.collections.PACKAGE.collections.COLLECTION; +import speiger.src.collections.PACKAGE.collections.ITERABLE; +import speiger.src.collections.PACKAGE.collections.ITERATOR; +#if QUEUES_FEATURE +import speiger.src.collections.PACKAGE.utils.PRIORITY_QUEUES; +#endif + + +/** + * A Simple PriorityQueue (or Queue) interface that provides with the nessesary functions to interact with it, without cluttering with the Collection interface. + * @Type(T) + */ +public interface PRIORITY_QUEUE KEY_GENERIC_TYPE extends ITERABLE KEY_GENERIC_TYPE +{ + /** + * @return true if the PriorityQueue is empty + */ + public default boolean isEmpty() { return size() <= 0; } + /** + * @return the amount of elements that are stored in the PriorityQueue + */ + public int size(); + /** + * clears all elements within the PriorityQueue, + * this does not resize the backing arrays + */ + public void clear(); + + /** + * Method to insert a element into the PriorityQueue + * @param e the element that should be inserted + */ + public void enqueue(KEY_TYPE e); + + /** + * Method to mass insert elements into the PriorityQueue + * @param e the elements that should be inserted + */ + public default void enqueueAll(KEY_TYPE... e) { + enqueueAll(e, 0, e.length); + } + + /** + * Method to mass insert elements into the PriorityQueue + * @param e the elements that should be inserted + * @param length the amount of elements that should be inserted + */ + public default void enqueueAll(KEY_TYPE[] e, int length) { + enqueueAll(e, 0, length); + } + + /** + * Method to mass insert elements into the PriorityQueue + * @param e the elements that should be inserted + * @param offset the offset where in the array should be started + * @param length the amount of elements that should be inserted + */ + public default void enqueueAll(KEY_TYPE[] e, int offset, int length) { + for(int i = 0;i c) { + for(Iterator iter = c.iterator();iter.hasNext();) + enqueue(iter.next()); + } + +#endif + + /** + * Method to extract a element from the PriorityQueue + * @return a element from the Queue + * @throws java.util.NoSuchElementException if no element is present + */ + public KEY_TYPE dequeue(); + + /** + * Peeking function to see whats inside the queue. + * @param index of the element that is requested to be viewed. + * @return the element that is requested + */ + public KEY_TYPE peek(int index); + /** + * Shows the element that is to be returned next + * @return the first element in the Queue + */ + public default KEY_TYPE first() { return peek(0); } + + /** + * Removes the first found element in the queue + * @param e the element that should be removed + * @return if a searched element was removed + */ + public boolean removeFirst(KEY_TYPE e); + /** + * Removes the last found element in the queue + * @param e the element that should be removed + * @return if a searched element was removed + */ + public boolean removeLast(KEY_TYPE e); + + /** + * Allows to notify the Queue to be revalidate its data + */ + public void onChanged(); + + /** + * A Function that does a shallow clone of the PriorityQueue itself. + * This function is more optimized then a copy constructor since the PriorityQueue does not have to be unsorted/resorted. + * It can be compared to Cloneable but with less exception risk + * @return a Shallow Copy of the PriorityQueue + * @note Wrappers and view PriorityQueues will not support this feature + */ + public PRIORITY_QUEUE KEY_GENERIC_TYPE copy(); + + /** + * @return the sorter of the Queue, can be null + */ + public COMPARATOR KEY_SUPER_GENERIC_TYPE comparator(); + +#if TYPE_OBJECT + /** + * @return draining iterator of the PriorityQueue + */ + public ITERATOR KEY_GENERIC_TYPE iterator(); + +#endif +#if QUEUES_FEATURE + /** + * Creates a Wrapped PriorityQueue that is Synchronized + * @return a new PriorityQueue that is synchronized + * @see PRIORITY_QUEUES#synchronize + */ + public default PRIORITY_QUEUE KEY_GENERIC_TYPE synchronizeQueue() { return PRIORITY_QUEUES.synchronize(this); } + + /** + * Creates a Wrapped PriorityQueue that is Synchronized + * @param mutex is the controller of the synchronization block + * @return a new PriorityQueue Wrapper that is synchronized + * @see PRIORITY_QUEUES#synchronize + */ + public default PRIORITY_QUEUE KEY_GENERIC_TYPE synchronizeQueue(Object mutex) { return PRIORITY_QUEUES.synchronize(this, mutex); } + +#endif + /** + * A method to drop the contents of the Queue without clearing the queue + * @Type(E) + * @return the contents of the queue into a seperate array. + */ + public default GENERIC_SPECIAL_KEY_BRACES KEY_SPECIAL_TYPE[] TO_ARRAY() { return TO_ARRAY(NEW_SPECIAL_KEY_ARRAY(size())); } + /** + * A method to drop the contents of the Queue without clearing the queue + * @param input where the elements should be inserted to. If it does not fit then it creates a new appropiatly created array + * @Type(E) + * @return the contents of the queue into a seperate array. + * @note if the Type is generic then a Object Array is created instead of a Type Array + */ + public GENERIC_SPECIAL_KEY_BRACES KEY_SPECIAL_TYPE[] TO_ARRAY(KEY_SPECIAL_TYPE[] input); +#if TYPE_OBJECT + /** + * A Helper function that simplifies the process of creating a new Array. + * @param action the array creation function + * @param the returning arrayType + * @return an array containing all of the elements in this collection + * @see Collection#toArray(Object[]) + */ + default E[] TO_ARRAY(IntFunction action) { + return TO_ARRAY(action.apply(size())); + } +#endif } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/collections/templates/sets/AbstractSet.template b/src/builder/resources/speiger/assets/collections/templates/sets/AbstractSet.template index f404299..bc97fff 100644 --- a/src/builder/resources/speiger/assets/collections/templates/sets/AbstractSet.template +++ b/src/builder/resources/speiger/assets/collections/templates/sets/AbstractSet.template @@ -1,50 +1,50 @@ -package speiger.src.collections.PACKAGE.sets; - -#if TYPE_OBJECT -import java.util.Objects; -#endif -import java.util.Set; - -import speiger.src.collections.PACKAGE.collections.ABSTRACT_COLLECTION; -import speiger.src.collections.PACKAGE.collections.ITERATOR; - -/** - * Abstract Type Specific Set that reduces boxing/unboxing - * @Type(T) - */ -public abstract class ABSTRACT_SET KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION KEY_GENERIC_TYPE implements SET KEY_GENERIC_TYPE -{ -#if TYPE_OBJECT - @Override - public KEY_TYPE addOrGet(KEY_TYPE o) { throw new UnsupportedOperationException(); } - -#endif - @Override - public abstract ITERATOR KEY_GENERIC_TYPE iterator(); - @Override - public ABSTRACT_SET KEY_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); } - - @Override - public int hashCode() { - int hashCode = 0; - ITERATOR KEY_GENERIC_TYPE i = iterator(); - while(i.hasNext()) - hashCode += KEY_TO_HASH(i.NEXT()); - return hashCode; - } - - @Override - public boolean equals(Object o) { - if (o == this) - return true; - if (!(o instanceof Set)) - return false; - Set l = (Set)o; - if(l.size() != size()) return false; - try { - return containsAll(l); - } catch (ClassCastException | NullPointerException unused) { - return false; - } - } -} +package speiger.src.collections.PACKAGE.sets; + +#if TYPE_OBJECT +import java.util.Objects; +#endif +import java.util.Set; + +import speiger.src.collections.PACKAGE.collections.ABSTRACT_COLLECTION; +import speiger.src.collections.PACKAGE.collections.ITERATOR; + +/** + * Abstract Type Specific Set that reduces boxing/unboxing + * @Type(T) + */ +public abstract class ABSTRACT_SET KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION KEY_GENERIC_TYPE implements SET KEY_GENERIC_TYPE +{ +#if TYPE_OBJECT + @Override + public KEY_TYPE addOrGet(KEY_TYPE o) { throw new UnsupportedOperationException(); } + +#endif + @Override + public abstract ITERATOR KEY_GENERIC_TYPE iterator(); + @Override + public ABSTRACT_SET KEY_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); } + + @Override + public int hashCode() { + int hashCode = 0; + ITERATOR KEY_GENERIC_TYPE i = iterator(); + while(i.hasNext()) + hashCode += KEY_TO_HASH(i.NEXT()); + return hashCode; + } + + @Override + public boolean equals(Object o) { + if (o == this) + return true; + if (!(o instanceof Set)) + return false; + Set l = (Set)o; + if(l.size() != size()) return false; + try { + return containsAll(l); + } catch (ClassCastException | NullPointerException unused) { + return false; + } + } +} diff --git a/src/builder/resources/speiger/assets/collections/templates/utils/Arrays.template b/src/builder/resources/speiger/assets/collections/templates/utils/Arrays.template index 92ee749..a59ef3a 100644 --- a/src/builder/resources/speiger/assets/collections/templates/utils/Arrays.template +++ b/src/builder/resources/speiger/assets/collections/templates/utils/Arrays.template @@ -1,1656 +1,1656 @@ -package speiger.src.collections.PACKAGE.utils; - -import java.util.Arrays; -#if JAVA_VERSION>=17 -import java.util.random.RANDOM; -#else -import java.util.RANDOM; -#endif -import java.util.concurrent.RecursiveAction; -#if !TYPE_OBJECT - -import speiger.src.collections.PACKAGE.functions.COMPARATOR; -#else -import java.util.Comparator; -import java.util.function.IntFunction; - -#endif -import speiger.src.collections.PACKAGE.collections.ITERATOR; -import speiger.src.collections.PACKAGE.utils.ITERATORS; -import speiger.src.collections.PACKAGE.utils.COLLECTIONS; -import speiger.src.collections.utils.SanityChecks; - -/** - * A Helper class for Arrays - */ -public class ARRAYS -{ - /** Default Limit for Insertion/Selection Sort */ - public static final int BASE_THRESHOLD = 16; - /** Default Threshold for Multithreaded Sorting Algorythm options*/ - public static final int PARALLEL_THRESHOLD = 8192; - -#if !TYPE_OBJECT - /** Empty Array Reference used for Uninitialized Collections */ - public static final KEY_TYPE[] EMPTY_ARRAY = new KEY_TYPE[0]; - - /** - * A Helper function to convert a Primitive Array to a CLASS_TYPE Array. - * @param a the array that should be converted - * @return a CLASS_TYPE Array of the input array. - */ - public static CLASS_TYPE[] wrap(KEY_TYPE[] a) { - return wrap(a, 0, a.length); - } - - /** - * A Helper function to convert a Primitive Array to a CLASS_TYPE Array. - * @param a the array that should be converted - * @param length the maximum length that should be coverted - * @return a CLASS_TYPE Array of the input array. - */ - public static CLASS_TYPE[] wrap(KEY_TYPE[] a, int length) { - return wrap(a, 0, length); - } - - /** - * A Helper function to convert a Primitive Array to a CLASS_TYPE Array. - * @param a the array that should be converted - * @param offset the starting offset of the inputarray - * @param length the maximum length that should be coverted - * @return a CLASS_TYPE Array of the input array. - */ - public static CLASS_TYPE[] wrap(KEY_TYPE[] a, int offset, int length) { - SanityChecks.checkArrayCapacity(a.length, offset, length); - CLASS_TYPE[] result = new CLASS_TYPE[length]; - for(int i = offset;i clz, int length) { - if(clz == Object.class) return (KEY_TYPE[])new Object[length]; - return (KEY_TYPE[]) java.lang.reflect.Array.newInstance(clz, length); - } - -#endif - /** - * A Helper function that pours all elements of a iterator into a Array - * @param iter the elements that should be gathered. - * @ArrayType(T) - * @return array with all elements of the iterator - */ - public static GENERIC_KEY_BRACES KEY_TYPE[] pour(ITERATOR KEY_GENERIC_TYPE iter) { - return pour(iter, Integer.MAX_VALUE); - } - - /** - * A Helper function that pours all elements of a iterator into a Array - * @param iter the elements that should be gathered. - * @param max how many elements should be added - * @ArrayType(T) - * @return array with all requested elements of the iterator - */ - public static GENERIC_KEY_BRACES KEY_TYPE[] pour(ITERATOR KEY_GENERIC_TYPE iter, int max) { - COLLECTIONS.CollectionWrapper KEY_GENERIC_TYPE list = COLLECTIONS.wrapper(); - ITERATORS.pour(iter, list, max); - return list.TO_ARRAY(NEW_KEY_ARRAY(list.size())); - } - -#if TYPE_OBJECT - /** - * A Helper function that pours all elements of a iterator into a Array - * @param iter the elements that should be gathered. - * @ArrayType(T) - * @param action that is creating the Array to be poured into - * @return array with all elements of the iterator - */ - public static E[] pour(ITERATOR KEY_GENERIC_TYPE iter, IntFunction action) { - return pour(iter, Integer.MAX_VALUE, action); - } - - /** - * A Helper function that pours all elements of a iterator into a Array - * @param iter the elements that should be gathered. - * @param max how many elements should be added - * @param action that is creating the Array to be poured into - * @ArrayType(T) - * @return array with all requested elements of the iterator - */ - public static E[] pour(ITERATOR KEY_GENERIC_TYPE iter, int max, IntFunction action) { - COLLECTIONS.CollectionWrapper KEY_GENERIC_TYPE list = COLLECTIONS.wrapper(); - ITERATORS.pour(iter, list, max); - return list.TO_ARRAY(action.apply(list.size())); - } - -#endif - - /** - * Method to validate if the current value is the lowest value in the heap - * @param data the current heap. - * @param size the size of the heap - * @param index the index that should be validated - * @param comp the comparator to sort the heap. Can be null - * @ArrayType(T) - * @return the index the element was shifted to - */ - public static GENERIC_KEY_BRACES int shiftDown(KEY_TYPE[] data, int size, int index, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { - int half = size >>> 1; - KEY_TYPE value = data[index]; - if(comp != null) { - while(index < half) { - int child = (index << 1) + 1; - KEY_TYPE childValue = data[child]; - int right = child+1; - if(right < size && comp.compare(data[right], childValue) < 0) childValue = data[child = right]; - if(comp.compare(value, childValue) <= 0) break; - data[index] = childValue; - index = child; - } - } - else { - while(index < half) { - int child = (index << 1) + 1; - KEY_TYPE childValue = data[child]; - int right = child+1; - if(right < size && COMPAREABLE_TO_KEY(data[right], childValue) < 0) childValue = data[child = right]; - if(COMPAREABLE_TO_KEY(value, childValue) <= 0) break; - data[index] = childValue; - index = child; - } - } - data[index] = value; - return index; - } - - /** - * Method to sort a specific value into the heap. - * @param data the heap itself. - * @param index that should be heapified. - * @param comp the comparator to sort the heap. Can be null - * @ArrayType(T) - * @return the index the element was shifted to - */ - public static GENERIC_KEY_BRACES int shiftUp(KEY_TYPE[] data, int index, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { - KEY_TYPE value = data[index]; - if(comp != null) { - while(index > 0) { - int parent = (index - 1) >>> 1; - KEY_TYPE parentValue = data[parent]; - if(comp.compare(value, parentValue) >= 0) break; - data[index] = parentValue; - index = parent; - } - } - else { - while(index > 0) { - int parent = (index - 1) >>> 1; - KEY_TYPE parentValue = data[parent]; - if(COMPAREABLE_TO_KEY(value, parentValue) >= 0) break; - data[index] = parentValue; - index = parent; - } - } - data[index] = value; - return index; - } - - /** - * Helper function to create a Heap out of an array. - * @param data the array to heapify - * @param size the current size of elements within the array. - * @param comp the Comparator to sort the array. Can be null - * @ArrayType(T) - * @return the input array - */ - public static GENERIC_KEY_BRACES KEY_TYPE[] heapify(KEY_TYPE[] data, int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { - for(int i = (size >>> 1) - 1;i>=0;shiftDown(data, size, i--, comp)); - return data; - } - - /** - * Simple Shuffle method for Arrays. - * @param array the elements that should be shuffled - * @ArrayType(T) - * @note This uses the SanityChecks#getRandom - * @return the provided sorted array - */ - public static GENERIC_KEY_BRACES KEY_TYPE[] shuffle(KEY_TYPE[] array) { - return shuffle(array, SanityChecks.getRandom()); - } - - /** - * Simple Shuffle method for Arrays. - * @param array the elements that should be shuffled - * @param length the length of the array - * @ArrayType(T) - * @note This uses the SanityChecks#getRandom - * @return the provided sorted array - */ - public static GENERIC_KEY_BRACES KEY_TYPE[] shuffle(KEY_TYPE[] array, int length) { - return shuffle(array, 0, length, SanityChecks.getRandom()); - } - - /** - * Simple Shuffle method for Arrays. - * @param array the elements that should be shuffled - * @param offset the start array - * @param length the length of the array - * @ArrayType(T) - * @note This uses the SanityChecks#getRandom - * @return the provided sorted array - */ - public static GENERIC_KEY_BRACES KEY_TYPE[] shuffle(KEY_TYPE[] array, int offset, int length) { - return shuffle(array, offset, length, SanityChecks.getRandom()); - } - - /** - * Simple Shuffle method for Arrays. - * @param array the elements that should be shuffled - * @param random the Random Number Generator that should be used for the shuffling - * @ArrayType(T) - * @return the provided sorted array - */ - public static GENERIC_KEY_BRACES KEY_TYPE[] shuffle(KEY_TYPE[] array, RANDOM random) { - for(int i = array.length-1; i>=0;i--) { - int p = random.nextInt(i + 1); - KEY_TYPE t = array[i]; - array[i] = array[p]; - array[p] = t; - } - return array; - } - - /** - * Simple Shuffle method for Arrays. - * @param array the elements that should be shuffled - * @param length the length of the array - * @param random the Random Number Generator that should be used for the shuffling - * @ArrayType(T) - * @return the provided sorted array - */ - public static GENERIC_KEY_BRACES KEY_TYPE[] shuffle(KEY_TYPE[] array, int length, RANDOM random) { - return shuffle(array, 0, length, random); - } - - /** - * Simple Shuffle method for Arrays. - * @param array the elements that should be shuffled - * @param offset the start array - * @param length the length of the array - * @param random the Random Number Generator that should be used for the shuffling - * @ArrayType(T) - * @return the provided sorted array - */ - public static GENERIC_KEY_BRACES KEY_TYPE[] shuffle(KEY_TYPE[] array, int offset, int length, RANDOM random) { - for(int i = length-1; i>=0;i--) { - int p = offset + random.nextInt(i + 1); - KEY_TYPE t = array[offset+i]; - array[offset+i] = array[p]; - array[p] = t; - } - return array; - } - - /** - * Simple Array Reversal method - * @param array the Array that should flip - * @ArrayType(T) - * @return the provided array - */ - public static GENERIC_KEY_BRACES KEY_TYPE[] reverse(KEY_TYPE[] array) { - return reverse(array, 0, array.length); - } - - /** - * Simple Array Reversal method - * @param array the Array that should flip - * @param length the length of the array - * @ArrayType(T) - * @return the provided array - */ - public static GENERIC_KEY_BRACES KEY_TYPE[] reverse(KEY_TYPE[] array, int length) { - return reverse(array, 0, length); - } - - /** - * Simple Array Reversal method - * @param array the Array that should flip - * @param length the length of the array - * @param offset the start of the array - * @ArrayType(T) - * @return the provided array - */ - public static GENERIC_KEY_BRACES KEY_TYPE[] reverse(KEY_TYPE[] array, int offset, int length) { - for (int i = offset, mid = offset + length >> 1, j = offset + length - 1; i < mid; i++, j--) { - KEY_TYPE temp = array[i]; - array[i] = array[j]; - array[j] = temp; - } - return array; - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator, - * potentially dynamically choosing an appropriate algorithm given the type and size of the array. - * Stable sort referres to Mergesort or Insertionsort - * @param array the array that needs to be sorted - * @ArrayType(T) - * @param comp the Comparator that decides the sorting order - * @return input array. - */ - public static GENERIC_KEY_BRACES KEY_TYPE[] stableSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) { - stableSort(array, 0, array.length, comp); - return array; - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator, - * potentially dynamically choosing an appropriate algorithm given the type and size of the array. - * Stable sort referres to Mergesort or Insertionsort - * @param array the array that needs to be sorted - * @param length the maxmium size of the array to be sorted - * @param comp the Comparator that decides the sorting order - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void stableSort(KEY_TYPE[] array, int length, COMPARATOR KEY_GENERIC_TYPE comp) { - stableSort(array, 0, length, comp); - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator, - * potentially dynamically choosing an appropriate algorithm given the type and size of the array. - * Stable sort referres to Mergesort or Insertionsort - * @param array the array that needs to be sorted - * @param from where the array should be sorted from - * @param to where the array should be sorted to - * @param comp the Comparator that decides the sorting order - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void stableSort(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) { - mergeSort(array, null, from, to, comp); - } - - /** - * Sorts an array according to the natural ascending order, - * potentially dynamically choosing an appropriate algorithm given the type and size of the array. - * Stable sort referres to Mergesort or Insertionsort - * @param array the array that needs to be sorted - * @ArrayType(T) - * @return input array - */ - public static GENERIC_KEY_BRACES KEY_TYPE[] stableSort(KEY_TYPE[] array) { - stableSort(array, 0, array.length); - return array; - } - - /** - * Sorts an array according to the natural ascending order, - * potentially dynamically choosing an appropriate algorithm given the type and size of the array. - * Stable sort referres to Mergesort or Insertionsort - * @param array the array that needs to be sorted - * @param length the maxmium size of the array to be sorted - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void stableSort(KEY_TYPE[] array, int length) { - stableSort(array, 0, length); - } - - /** - * Sorts an array according to the natural ascending order, - * potentially dynamically choosing an appropriate algorithm given the type and size of the array. - * Stable sort referres to Mergesort or Insertionsort - * @param array the array that needs to be sorted - * @param from where the array should be sorted from - * @param to where the array should be sorted to - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void stableSort(KEY_TYPE[] array, int from, int to) { - mergeSort(array, null, from, to); - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator, - * potentially dynamically choosing an appropriate algorithm given the type and size of the array. - * Unstable sort referres to QuickSort or SelectionSort - * @param array the array that needs to be sorted - * @param comp the Comparator that decides the sorting order - * @ArrayType(T) - * @return input array - */ - public static GENERIC_KEY_BRACES KEY_TYPE[] unstableSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) { - unstableSort(array, 0, array.length, comp); - return array; - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator, - * potentially dynamically choosing an appropriate algorithm given the type and size of the array. - * Unstable sort referres to QuickSort or SelectionSort - * @param array the array that needs to be sorted - * @param length the maxmium size of the array to be sorted - * @param comp the Comparator that decides the sorting order - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void unstableSort(KEY_TYPE[] array, int length, COMPARATOR KEY_GENERIC_TYPE comp) { - unstableSort(array, 0, length, comp); - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator, - * potentially dynamically choosing an appropriate algorithm given the type and size of the array. - * Unstable sort referres to QuickSort or SelectionSort - * @param array the array that needs to be sorted - * @param from where the array should be sorted from - * @param to where the array should be sorted to - * @param comp the Comparator that decides the sorting order - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void unstableSort(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) { - quickSort(array, from, to, comp); - } - - /** - * Sorts an array according to the natural ascending order, - * potentially dynamically choosing an appropriate algorithm given the type and size of the array. - * Unstable sort referres to QuickSort or SelectionSort - * @param array the array that needs to be sorted - * @ArrayType(T) - * @return input array - */ - public static GENERIC_KEY_BRACES KEY_TYPE[] unstableSort(KEY_TYPE[] array) { - unstableSort(array, 0, array.length); - return array; - } - - /** - * Sorts an array according to the natural ascending order, - * potentially dynamically choosing an appropriate algorithm given the type and size of the array. - * Unstable sort referres to QuickSort or SelectionSort - * @param array the array that needs to be sorted - * @param length the maxmium size of the array to be sorted - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void unstableSort(KEY_TYPE[] array, int length) { - unstableSort(array, 0, length); - } - - /** - * Sorts an array according to the natural ascending order, - * potentially dynamically choosing an appropriate algorithm given the type and size of the array. - * Unstable sort referres to QuickSort or SelectionSort - * @param array the array that needs to be sorted - * @param from where the array should be sorted from - * @param to where the array should be sorted to - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void unstableSort(KEY_TYPE[] array, int from, int to) { - quickSort(array, from, to); - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator using Insertion Sort, - * @param array the array that needs to be sorted - * @param comp the Comparator that decides the sorting order - * @ArrayType(T) - * @return input array - */ - public static GENERIC_KEY_BRACES KEY_TYPE[] insertionSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) { - insertionSort(array, 0, array.length, comp); - return array; - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator using Insertion Sort, - * @param array the array that needs to be sorted - * @param length the maxmium size of the array to be sorted - * @param comp the Comparator that decides the sorting order - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void insertionSort(KEY_TYPE[] array, int length, COMPARATOR KEY_GENERIC_TYPE comp) { - insertionSort(array, 0, length, comp); - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator using Insertion Sort, - * @param array the array that needs to be sorted - * @param from where the array should be sorted from - * @param to where the array should be sorted to - * @param comp the Comparator that decides the sorting order - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void insertionSort(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) { - for (int i = from+1;i= from && comp.compare(current, array[j]) < 0) { - array[j+1] = array[j--]; - } - array[j+1] = current; - } - } - - /** - * Sorts an array according to the natural ascending order using InsertionSort, - * @param array the array that needs to be sorted - * @ArrayType(T) - * @return input array - */ - public static GENERIC_KEY_BRACES KEY_TYPE[] insertionSort(KEY_TYPE[] array) { - insertionSort(array, 0, array.length); - return array; - } - - /** - * Sorts an array according to the natural ascending order using InsertionSort, - * @param array the array that needs to be sorted - * @param length the maxmium size of the array to be sorted - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void insertionSort(KEY_TYPE[] array, int length) { - insertionSort(array, 0, length); - } - - /** - * Sorts an array according to the natural ascending order using InsertionSort, - * @param array the array that needs to be sorted - * @param from where the array should be sorted from - * @param to where the array should be sorted to - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void insertionSort(KEY_TYPE[] array, int from, int to) { - for (int i = from+1;i= from && COMPAREABLE_TO_KEY(current, array[j]) < 0) { - array[j+1] = array[j--]; - } - array[j+1] = current; - } - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator using Selection Sort, - * @param array the array that needs to be sorted - * @param comp the Comparator that decides the sorting order - * @ArrayType(T) - * @return input array - */ - public static GENERIC_KEY_BRACES KEY_TYPE[] selectionSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) { - selectionSort(array, 0, array.length, comp); - return array; - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator using Selection Sort, - * @param array the array that needs to be sorted - * @param length the maxmium size of the array to be sorted - * @param comp the Comparator that decides the sorting order - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void selectionSort(KEY_TYPE[] array, int length, COMPARATOR KEY_GENERIC_TYPE comp) { - selectionSort(array, 0, length, comp); - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator using Selection Sort, - * @param array the array that needs to be sorted - * @param from where the array should be sorted from - * @param to where the array should be sorted to - * @param comp the Comparator that decides the sorting order - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void selectionSort(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) { - for (int i = from; i < to; i++) { - KEY_TYPE min = array[i]; - int minId = i; - for(int j = i+1; j < to; j++) { - if(comp.compare(array[j], min) < 0) { - min = array[j]; - minId = j; - } - } - KEY_TYPE temp = array[i]; - array[i] = min; - array[minId] = temp; - } - } - - /** - * Sorts an array according to the natural ascending order using Selection Sort, - * @param array the array that needs to be sorted - * @ArrayType(T) - * @return input array - */ - public static GENERIC_KEY_BRACES KEY_TYPE[] selectionSort(KEY_TYPE[] array) { - selectionSort(array, 0, array.length); - return array; - } - - /** - * Sorts an array according to the natural ascending order using Selection Sort, - * @param array the array that needs to be sorted - * @param length the maxmium size of the array to be sorted - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void selectionSort(KEY_TYPE[] array, int length) { - selectionSort(array, 0, length); - } - - /** - * Sorts an array according to the natural ascending order using Selection Sort, - * @param array the array that needs to be sorted - * @param from where the array should be sorted from - * @param to where the array should be sorted to - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void selectionSort(KEY_TYPE[] array, int from, int to) { - for (int i = from; i < to; i++) { - KEY_TYPE min = array[i]; - int minId = i; - for(int j = i+1; j < to; j++) { - if(COMPAREABLE_TO_KEY(array[j], min) < 0) { - min = array[j]; - minId = j; - } - } - KEY_TYPE temp = array[i]; - array[i] = min; - array[minId] = temp; - } - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator using Merge Sort, - * This implementation was copied from FastUtil with a couple custom optimizations - * @param array the array that needs to be sorted - * @param comp the Comparator that decides the sorting order - * @ArrayType(T) - * @return input array - */ - public static GENERIC_KEY_BRACES KEY_TYPE[] mergeSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) { - mergeSort(array, null, 0, array.length, comp); - return array; - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator using Merge Sort, - * This implementation was copied from FastUtil with a couple custom optimizations - * @param array the array that needs to be sorted - * @param length the maxmium size of the array to be sorted - * @param comp the Comparator that decides the sorting order - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void mergeSort(KEY_TYPE[] array, int length, COMPARATOR KEY_GENERIC_TYPE comp) { - mergeSort(array, null, 0, length, comp); - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator using Merge Sort, - * This implementation was copied from FastUtil with a couple custom optimizations - * @param array the array that needs to be sorted - * @param supp the auxillary array that is used to simplify the sorting - * @param from where the array should be sorted from - * @param to where the array should be sorted to - * @param comp the Comparator that decides the sorting order - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void mergeSort(KEY_TYPE[] array, KEY_TYPE[] supp, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) { - if(to - from < BASE_THRESHOLD) { - insertionSort(array, from, to, comp); - return; - } - if(supp == null) supp = Arrays.copyOf(array, to); - int mid = (from + to) >>> 1; - mergeSort(supp, array, from, mid, comp); - mergeSort(supp, array, mid, to, comp); - if(comp.compare(supp[mid - 1], supp[mid]) <= 0) - { - System.arraycopy(supp, from, array, from, to - from); - return; - } - for(int p = from, q = mid;from < to;from++) { - if(q >= to || p < mid && comp.compare(supp[p], supp[q]) < 0) array[from] = supp[p++]; - else array[from] = supp[q++]; - } - } - - /** - * Sorts an array according to the natural ascending order using Merge Sort, - * This implementation was copied from FastUtil with a couple custom optimizations - * @param array the array that needs to be sorted - * @ArrayType(T) - * @return input array - */ - public static GENERIC_KEY_BRACES KEY_TYPE[] mergeSort(KEY_TYPE[] array) { - mergeSort(array, null, 0, array.length); - return array; - } - - /** - * Sorts an array according to the natural ascending order using Merge Sort, - * This implementation was copied from FastUtil with a couple custom optimizations - * @param array the array that needs to be sorted - * @param length the maxmium size of the array to be sorted - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void mergeSort(KEY_TYPE[] array, int length) { - mergeSort(array, null, 0, length); - } - - /** - * Sorts an array according to the natural ascending order using Merge Sort, - * This implementation was copied from FastUtil with a couple custom optimizations - * @param array the array that needs to be sorted - * @param supp the auxillary array that is used to simplify the sorting - * @param from where the array should be sorted from - * @param to where the array should be sorted to - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void mergeSort(KEY_TYPE[] array, KEY_TYPE[] supp, int from, int to) { - if(to - from < BASE_THRESHOLD) { - insertionSort(array, from, to); - return; - } - if(supp == null) supp = Arrays.copyOf(array, to); - int mid = (from + to) >>> 1; - mergeSort(supp, array, from, mid); - mergeSort(supp, array, mid, to); - if(COMPAREABLE_TO_KEY(supp[mid - 1], supp[mid]) <= 0) - { - System.arraycopy(supp, from, array, from, to - from); - return; - } - for(int p = from, q = mid;from < to;from++) { - if(q >= to || p < mid && COMPAREABLE_TO_KEY(supp[p], supp[q]) < 0) array[from] = supp[p++]; - else array[from] = supp[q++]; - } - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator using a Parallel Merge Sort, - * This implementation was copied from FastUtil with a couple custom optimizations - * @param array the array that needs to be sorted - * @param comp the Comparator that decides the sorting order - * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void parallelMergeSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) { - parallelMergeSort(array, null, 0, array.length, comp); - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator using Parallel Merge Sort, - * This implementation was copied from FastUtil with a couple custom optimizations - * @param array the array that needs to be sorted - * @param length the maxmium size of the array to be sorted - * @param comp the Comparator that decides the sorting order - * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void parallelMergeSort(KEY_TYPE[] array, int length, COMPARATOR KEY_GENERIC_TYPE comp) { - parallelMergeSort(array, null, 0, length, comp); - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator using Parallel Merge Sort, - * This implementation was copied from FastUtil with a couple custom optimizations - * @param array the array that needs to be sorted - * @param supp the auxillary array that is used to simplify the sorting - * @param from where the array should be sorted from - * @param to where the array should be sorted to - * @param comp the Comparator that decides the sorting order - * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void parallelMergeSort(KEY_TYPE[] array, KEY_TYPE[] supp, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) { - if(SanityChecks.canParallelTask() && to - from >= PARALLEL_THRESHOLD) { - SanityChecks.invokeTask(new MergeSortActionCompBRACES(array, supp, from, to, comp)); - return; - } - mergeSort(array, supp, from, to, comp); - } - - /** - * Sorts an array according to the natural ascending order using Parallel Merge Sort, - * This implementation was copied from FastUtil with a couple custom optimizations - * @param array the array that needs to be sorted - * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void parallelMergeSort(KEY_TYPE[] array) { - parallelMergeSort(array, null, 0, array.length); - } - - /** - * Sorts an array according to the natural ascending order using Parallel Merge Sort, - * This implementation was copied from FastUtil with a couple custom optimizations - * @param array the array that needs to be sorted - * @param length the maxmium size of the array to be sorted - * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void parallelMergeSort(KEY_TYPE[] array, int length) { - parallelMergeSort(array, null, 0, length); - } - - /** - * Sorts an array according to the natural ascending order using Parallel Merge Sort, - * This implementation was copied from FastUtil with a couple custom optimizations - * @param array the array that needs to be sorted - * @param supp the auxillary array that is used to simplify the sorting - * @param from where the array should be sorted from - * @param to where the array should be sorted to - * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void parallelMergeSort(KEY_TYPE[] array, KEY_TYPE[] supp, int from, int to) { - if(SanityChecks.canParallelTask() && to - from >= PARALLEL_THRESHOLD) { - SanityChecks.invokeTask(new MergeSortActionBRACES(array, supp, from, to)); - return; - } - mergeSort(array, supp, from, to); - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator using Memory Free Merge Sort, - * This implementation is inspired by FastUtil original merge sort, but without the need to allocate a copy of the original Array. It is in Very Unsorted Instances 50% slower then Mergesort, otherwise it as fast. - * @param array the array that needs to be sorted - * @param comp the Comparator that decides the sorting order - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void memFreeMergeSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) { - memFreeMergeSort(array, 0, array.length, comp); - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator using Memory Free Merge Sort, - * This implementation is inspired by FastUtil original merge sort, but without the need to allocate a copy of the original Array. It is in Very Unsorted Instances 50% slower then Mergesort, otherwise it as fast. - * @param array the array that needs to be sorted - * @param length the maxmium size of the array to be sorted - * @param comp the Comparator that decides the sorting order - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void memFreeMergeSort(KEY_TYPE[] array, int length, COMPARATOR KEY_GENERIC_TYPE comp) { - memFreeMergeSort(array, 0, length, comp); - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator using Memory Free Merge Sort, - * This implementation is inspired by FastUtil original merge sort, but without the need to allocate a copy of the original Array. It is in Very Unsorted Instances 50% slower then Mergesort, otherwise it as fast. - * @param array the array that needs to be sorted - * @param from where the array should be sorted from - * @param to where the array should be sorted to - * @param comp the Comparator that decides the sorting order - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void memFreeMergeSort(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) { - if(to - from < BASE_THRESHOLD) { - insertionSort(array, from, to, comp); - return; - } - int mid = (from + to) >>> 1; - memFreeMergeSort(array, from, mid, comp); - memFreeMergeSort(array, mid, to, comp); - if(comp.compare(array[mid - 1], array[mid]) <= 0) - return; - for(int i = from, j = mid, compare;i < j && j < to;) { - if((compare = comp.compare(array[i], array[j])) < 0) - i++; - else if(compare == 0) swap(array, ++i, j); - else { - int k = j; - for(;k < to - 1 && comp.compare(array[i], array[k + 1]) > 0;k++); - if(j == k) { - swap(array, i++, j); - continue; - } - else if(j + 1 == k) { - KEY_TYPE value = array[j]; - System.arraycopy(array, i, array, i+1, j - i); - array[i] = value; - i++; - j++; - continue; - } - KEY_TYPE[] data = NEW_KEY_ARRAY(k - j); - System.arraycopy(array, j, data, 0, data.length); - System.arraycopy(array, i, array, i+data.length, j - i); - System.arraycopy(data, 0, array, i, data.length); - i+=data.length; - j+=data.length; - } - } - } - - /** - * Sorts an array according to the natural ascending order using Memory Free Merge Sort, - * This implementation is inspired by FastUtil original merge sort, but without the need to allocate a copy of the original Array. - * It is depending on the size and the unsorted level of the input array slower or almost as fast as normal merge sort. Depending on the test size i can be 0.5x slower (5000 elements) or 4x slower (50000 elements) under the assumtion that the array is in its worst case scenario. - * It does stack allocate tiny amounts of data for shifting around elements. - * @author Speiger - * @param array the array that needs to be sorted - * @ArrayType(T) - * @return input array - */ - public static GENERIC_KEY_BRACES KEY_TYPE[] memFreeMergeSort(KEY_TYPE[] array) { - memFreeMergeSort(array, 0, array.length); - return array; - } - - /** - * Sorts an array according to the natural ascending order using Memory Free Merge Sort, - * This implementation is inspired by FastUtil original merge sort, but without the need to allocate a copy of the original Array. - * It is depending on the size and the unsorted level of the input array slower or almost as fast as normal merge sort. Depending on the test size i can be 0.5x slower (5000 elements) or 4x slower (50000 elements) under the assumtion that the array is in its worst case scenario. - * It does stack allocate tiny amounts of data for shifting around elements. - * @author Speiger - * @param array the array that needs to be sorted - * @param length the maxmium size of the array to be sorted - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void memFreeMergeSort(KEY_TYPE[] array, int length) { - memFreeMergeSort(array, 0, length); - } - - /** - * Sorts an array according to the natural ascending order using Memory Free Merge Sort, - * This implementation is inspired by FastUtil original merge sort, but without the need to allocate a copy of the original Array. - * It is depending on the size and the unsorted level of the input array slower or almost as fast as normal merge sort. Depending on the test size i can be 0.5x slower (5000 elements) or 4x slower (50000 elements) under the assumtion that the array is in its worst case scenario. - * It does stack allocate tiny amounts of data for shifting around elements. - * @author Speiger - * @param array the array that needs to be sorted - * @param from where the array should be sorted from - * @param to where the array should be sorted to - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void memFreeMergeSort(KEY_TYPE[] array, int from, int to) { - if(to - from < BASE_THRESHOLD) { - insertionSort(array, from, to); - return; - } - int mid = (from + to) >>> 1; - memFreeMergeSort(array, from, mid); - memFreeMergeSort(array, mid, to); - if(COMPAREABLE_TO_KEY(array[mid - 1], array[mid]) <= 0) - return; - for(int i = from, j = mid, comp;i < j && j < to;) { - if((comp = COMPAREABLE_TO_KEY(array[i], array[j])) < 0) - i++; - else if(comp == 0) swap(array, ++i, j); - else { - int k = j; - for(;k < to - 1 && COMPAREABLE_TO_KEY(array[i], array[k + 1]) > 0;k++); - if(j == k) { - swap(array, i++, j); - continue; - } - else if(j + 1 == k) { - KEY_TYPE value = array[j]; - System.arraycopy(array, i, array, i+1, j - i); - array[i] = value; - i++; - j++; - continue; - } - KEY_TYPE[] data = NEW_KEY_ARRAY(k - j); - System.arraycopy(array, j, data, 0, data.length); - System.arraycopy(array, i, array, i+data.length, j - i); - System.arraycopy(data, 0, array, i, data.length); - i+=data.length; - j+=data.length; - } - } - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator using Parallel Memory Free Merge Sort, - * This implementation is inspired by FastUtil original merge sort, but without the need to allocate a copy of the original Array. - * It is depending on the size and the unsorted level of the input array slower or almost as fast as normal merge sort. Depending on the test size i can be 0.5x slower (5000 elements) or 4x slower (50000 elements) under the assumtion that the array is in its worst case scenario. - * It does stack allocate tiny amounts of data for shifting around elements. - * @author Speiger - * @param array the array that needs to be sorted - * @param comp the Comparator that decides the sorting order - * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void parallelMemFreeMergeSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) { - parallelMemFreeMergeSort(array, 0, array.length, comp); - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator using Parallel Memory Free Merge Sort, - * This implementation is inspired by FastUtil original merge sort, but without the need to allocate a copy of the original Array. - * It is depending on the size and the unsorted level of the input array slower or almost as fast as normal merge sort. Depending on the test size i can be 0.5x slower (5000 elements) or 4x slower (50000 elements) under the assumtion that the array is in its worst case scenario. - * It does stack allocate tiny amounts of data for shifting around elements. - * @author Speiger - * @param array the array that needs to be sorted - * @param length the maxmium size of the array to be sorted - * @param comp the Comparator that decides the sorting order - * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void parallelMemFreeMergeSort(KEY_TYPE[] array, int length, COMPARATOR KEY_GENERIC_TYPE comp) { - parallelMemFreeMergeSort(array, 0, length, comp); - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator using Parallel Memory Free Merge Sort, - * This implementation is inspired by FastUtil original merge sort, but without the need to allocate a copy of the original Array. - * It is depending on the size and the unsorted level of the input array slower or almost as fast as normal merge sort. Depending on the test size i can be 0.5x slower (5000 elements) or 4x slower (50000 elements) under the assumtion that the array is in its worst case scenario. - * It does stack allocate tiny amounts of data for shifting around elements. - * @author Speiger - * @param array the array that needs to be sorted - * @param from where the array should be sorted from - * @param to where the array should be sorted to - * @param comp the Comparator that decides the sorting order - * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void parallelMemFreeMergeSort(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) { - if(SanityChecks.canParallelTask() && to - from >= PARALLEL_THRESHOLD) { - SanityChecks.invokeTask(new MemFreeMergeSortActionCompBRACES(array, from, to, comp)); - return; - } - memFreeMergeSort(array, from, to, comp); - } - - /** - * Sorts an array according to the natural ascending order using Parallel Memory Free Merge Sort, - * This implementation is inspired by FastUtil original merge sort, but without the need to allocate a copy of the original Array. - * It is depending on the size and the unsorted level of the input array slower or almost as fast as normal merge sort. Depending on the test size i can be 0.5x slower (5000 elements) or 4x slower (50000 elements) under the assumtion that the array is in its worst case scenario. - * It does stack allocate tiny amounts of data for shifting around elements. - * @author Speiger - * @param array the array that needs to be sorted - * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void parallelMemFreeMergeSort(KEY_TYPE[] array) { - parallelMemFreeMergeSort(array, 0, array.length); - } - - /** - * Sorts an array according to the natural ascending order using Parallel Memory Free Merge Sort, - * This implementation is inspired by FastUtil original merge sort, but without the need to allocate a copy of the original Array. - * It is depending on the size and the unsorted level of the input array slower or almost as fast as normal merge sort. Depending on the test size i can be 0.5x slower (5000 elements) or 4x slower (50000 elements) under the assumtion that the array is in its worst case scenario. - * It does stack allocate tiny amounts of data for shifting around elements. - * @author Speiger - * @param array the array that needs to be sorted - * @param length the maxmium size of the array to be sorted - * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void parallelMemFreeMergeSort(KEY_TYPE[] array, int length) { - parallelMemFreeMergeSort(array, 0, length); - } - - /** - * Sorts an array according to the natural ascending order using Parallel Memory Free Merge Sort, - * This implementation is inspired by FastUtil original merge sort, but without the need to allocate a copy of the original Array. - * It is depending on the size and the unsorted level of the input array slower or almost as fast as normal merge sort. Depending on the test size i can be 0.5x slower (5000 elements) or 4x slower (50000 elements) under the assumtion that the array is in its worst case scenario. - * It does stack allocate tiny amounts of data for shifting around elements. - * @author Speiger - * @param array the array that needs to be sorted - * @param from where the array should be sorted from - * @param to where the array should be sorted to - * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void parallelMemFreeMergeSort(KEY_TYPE[] array, int from, int to) { - if(SanityChecks.canParallelTask() && to - from >= PARALLEL_THRESHOLD) { - SanityChecks.invokeTask(new MemFreeMergeSortActionBRACES(array, from, to)); - return; - } - memFreeMergeSort(array, from, to); - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator using Quick Sort, - * This implementation is a custom of FastUtil quicksort but with a different code structure, - * and that sorting Algorithm is based on the tuned quicksort adapted from Jon L. Bentley and M. DouglasMcIlroy, "Engineering a Sort Function", Software: Practice and Experience, 23(11), pages1249−1265, 1993. - * @param array the array that needs to be sorted - * @param comp the Comparator that decides the sorting order - * @ArrayType(T) - * @return input array - */ - public static GENERIC_KEY_BRACES KEY_TYPE[] quickSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) { - quickSort(array, 0, array.length, comp); - return array; - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator using Quick Sort, - * This implementation is a custom of FastUtil quicksort but with a different code structure, - * and that sorting Algorithm is based on the tuned quicksort adapted from Jon L. Bentley and M. DouglasMcIlroy, "Engineering a Sort Function", Software: Practice and Experience, 23(11), pages1249−1265, 1993. - * @param array the array that needs to be sorted - * @param length the maxmium size of the array to be sorted - * @param comp the Comparator that decides the sorting order - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void quickSort(KEY_TYPE[] array, int length, COMPARATOR KEY_GENERIC_TYPE comp) { - quickSort(array, 0, length, comp); - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator using Quick Sort, - * This implementation is a custom of FastUtil quicksort but with a different code structure, - * and that sorting Algorithm is based on the tuned quicksort adapted from Jon L. Bentley and M. DouglasMcIlroy, "Engineering a Sort Function", Software: Practice and Experience, 23(11), pages1249−1265, 1993. - * @param array the array that needs to be sorted - * @param from where the array should be sorted from - * @param to where the array should be sorted to - * @param comp the Comparator that decides the sorting order - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void quickSort(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) { - int length = to - from; - if(length <= 0) return; - if(length < BASE_THRESHOLD) { - selectionSort(array, from, to, comp); - return; - } - KEY_TYPE pivot = array[length > 128 ? subMedium(array, from, from + (length / 2), to - 1, length / 8, comp) : medium(array, from, from + (length / 2), to - 1, comp)]; - int a = from, b = a, c = to - 1, d = c; - for(int compare;;swap(array, b++, c--)) { - for(;b<=c && (compare = comp.compare(array[b], pivot)) <= 0;b++) { - if(compare == 0) swap(array, a++, b); - } - for(;c>=b && (compare = comp.compare(array[c], pivot)) >= 0;c--) { - if(compare == 0) swap(array, c, d--); - } - if(b>c) break; - } - swap(array, from, b, Math.min(a - from, b - a)); - swap(array, b, to, Math.min(d - c, to - d - 1)); - if((length = b - a) > 1) quickSort(array, from, from + length, comp); - if((length = d - c) > 1) quickSort(array, to - length, to, comp); - } - - /** - * Sorts an array according to the natural ascending order using Quick Sort, - * This implementation is a custom of FastUtil quicksort but with a different code structure, - * and that sorting Algorithm is based on the tuned quicksort adapted from Jon L. Bentley and M. DouglasMcIlroy, "Engineering a Sort Function", Software: Practice and Experience, 23(11), pages1249−1265, 1993. - * @param array the array that needs to be sorted - * @ArrayType(T) - * @return input array - */ - public static GENERIC_KEY_BRACES KEY_TYPE[] quickSort(KEY_TYPE[] array) { - quickSort(array, 0, array.length); - return array; - } - - /** - * Sorts an array according to the natural ascending order using Quick Sort, - * This implementation is a custom of FastUtil quicksort but with a different code structure, - * and that sorting Algorithm is based on the tuned quicksort adapted from Jon L. Bentley and M. DouglasMcIlroy, "Engineering a Sort Function", Software: Practice and Experience, 23(11), pages1249−1265, 1993. - * @param array the array that needs to be sorted - * @param length the maxmium size of the array to be sorted - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void quickSort(KEY_TYPE[] array, int length) { - quickSort(array, 0, length); - } - - /** - * Sorts an array according to the natural ascending order using Quick Sort, - * This implementation is a custom of FastUtil quicksort but with a different code structure, - * and that sorting Algorithm is based on the tuned quicksort adapted from Jon L. Bentley and M. DouglasMcIlroy, "Engineering a Sort Function", Software: Practice and Experience, 23(11), pages1249−1265, 1993. - * @param array the array that needs to be sorted - * @param from where the array should be sorted from - * @param to where the array should be sorted to - * @ArrayType(T) - */ - public static GENERIC_KEY_BRACES void quickSort(KEY_TYPE[] array, int from, int to) { - int length = to - from; - if(length <= 0) return; - if(length < BASE_THRESHOLD) { - selectionSort(array, from, to); - return; - } - KEY_TYPE pivot = array[length > 128 ? subMedium(array, from, from + (length / 2), to - 1, length / 8) : medium(array, from, from + (length / 2), to - 1)]; - int a = from, b = a, c = to - 1, d = c; - for(int comp = 0;;swap(array, b++, c--)) { - for(;b<=c && (comp = COMPAREABLE_TO_KEY(array[b], pivot)) <= 0;b++) { - if(comp == 0) swap(array, a++, b); - } - for(;c>=b && (comp = COMPAREABLE_TO_KEY(array[c], pivot)) >= 0;c--) { - if(comp == 0) swap(array, c, d--); - } - if(b>c) break; - } - swap(array, from, b, Math.min(a - from, b - a)); - swap(array, b, to, Math.min(d - c, to - d - 1)); - if((length = b - a) > 1) quickSort(array, from, from + length); - if((length = d - c) > 1) quickSort(array, to - length, to); - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator using Parallel Quick Sort, - * This implementation is a custom of FastUtil quicksort but with a different code structure, - * and that sorting Algorithm is based on the tuned quicksort adapted from Jon L. Bentley and M. DouglasMcIlroy, "Engineering a Sort Function", Software: Practice and Experience, 23(11), pages1249−1265, 1993. - * @param array the array that needs to be sorted - * @param comp the Comparator that decides the sorting order - * @ArrayType(T) - * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed - */ - public static GENERIC_KEY_BRACES void parallelQuickSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) { - parallelQuickSort(array, 0, array.length, comp); - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator using Parallel Quick Sort, - * This implementation is a custom of FastUtil quicksort but with a different code structure, - * and that sorting Algorithm is based on the tuned quicksort adapted from Jon L. Bentley and M. DouglasMcIlroy, "Engineering a Sort Function", Software: Practice and Experience, 23(11), pages1249−1265, 1993. - * @param array the array that needs to be sorted - * @param length the maxmium size of the array to be sorted - * @param comp the Comparator that decides the sorting order - * @ArrayType(T) - * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed - */ - public static GENERIC_KEY_BRACES void parallelQuickSort(KEY_TYPE[] array, int length, COMPARATOR KEY_GENERIC_TYPE comp) { - parallelQuickSort(array, 0, length, comp); - } - - /** - * Sorts the specified range of elements according to the order induced by the specified comparator using Parallel Quick Sort, - * This implementation is a custom of FastUtil quicksort but with a different code structure, - * and that sorting Algorithm is based on the tuned quicksort adapted from Jon L. Bentley and M. DouglasMcIlroy, "Engineering a Sort Function", Software: Practice and Experience, 23(11), pages1249−1265, 1993. - * @param array the array that needs to be sorted - * @param from where the array should be sorted from - * @param to where the array should be sorted to - * @param comp the Comparator that decides the sorting order - * @ArrayType(T) - * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed - */ - public static GENERIC_KEY_BRACES void parallelQuickSort(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) { - if(SanityChecks.canParallelTask() && to - from >= PARALLEL_THRESHOLD) { - SanityChecks.invokeTask(new QuickSortActionCompBRACES(array, from, to, comp)); - return; - } - quickSort(array, from, to, comp); - } - - /** - * Sorts an array according to the natural ascending order using Parallel Quick Sort, - * This implementation is a custom of FastUtil quicksort but with a different code structure, - * and that sorting Algorithm is based on the tuned quicksort adapted from Jon L. Bentley and M. DouglasMcIlroy, "Engineering a Sort Function", Software: Practice and Experience, 23(11), pages1249−1265, 1993. - * @param array the array that needs to be sorted - * @ArrayType(T) - * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed - */ - public static GENERIC_KEY_BRACES void parallelQuickSort(KEY_TYPE[] array) { - parallelQuickSort(array, 0, array.length); - } - - /** - * Sorts an array according to the natural ascending order using Parallel Quick Sort, - * This implementation is a custom of FastUtil quicksort but with a different code structure, - * and that sorting Algorithm is based on the tuned quicksort adapted from Jon L. Bentley and M. DouglasMcIlroy, "Engineering a Sort Function", Software: Practice and Experience, 23(11), pages1249−1265, 1993. - * @param array the array that needs to be sorted - * @param length the maxmium size of the array to be sorted - * @ArrayType(T) - * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed - */ - public static GENERIC_KEY_BRACES void parallelQuickSort(KEY_TYPE[] array, int length) { - parallelQuickSort(array, 0, length); - } - - /** - * Sorts an array according to the natural ascending order using Parallel Quick Sort, - * This implementation is a custom of FastUtil quicksort but with a different code structure, - * and that sorting Algorithm is based on the tuned quicksort adapted from Jon L. Bentley and M. DouglasMcIlroy, "Engineering a Sort Function", Software: Practice and Experience, 23(11), pages1249−1265, 1993. - * @param array the array that needs to be sorted - * @param from where the array should be sorted from - * @param to where the array should be sorted to - * @ArrayType(T) - * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed - */ - public static GENERIC_KEY_BRACES void parallelQuickSort(KEY_TYPE[] array, int from, int to) { - if(SanityChecks.canParallelTask() && to - from >= PARALLEL_THRESHOLD) { - SanityChecks.invokeTask(new QuickSortActionBRACES(array, from, to)); - return; - } - quickSort(array, from, to); - } - - static GENERIC_KEY_BRACES void swap(KEY_TYPE[] a, int from, int to) { - KEY_TYPE t = a[from]; - a[from] = a[to]; - a[to] = t; - } - - static GENERIC_KEY_BRACES void swap(KEY_TYPE[] a, int from, int to, int length) { - to -= length; - for(int i = 0;i 0 ? b : comp.compare(data[a], data[c]) > 0 ? c : a); - } - - static GENERIC_KEY_BRACES int subMedium(KEY_TYPE[] data, int a, int b, int c, int length) { - return medium(data, medium(data, a, a + length, a + (length * 2)), medium(data, b - length, b, b + length), medium(data, c - (length * 2), c - length, c)); - } - - static GENERIC_KEY_BRACES int medium(KEY_TYPE[] data, int a, int b, int c) { - return COMPAREABLE_TO_KEY(data[a], data[b]) < 0 ? (COMPAREABLE_TO_KEY(data[b], data[c]) < 0 ? b : COMPAREABLE_TO_KEY(data[a], data[c]) < 0 ? c : a) : (COMPAREABLE_TO_KEY(data[b], data[c]) > 0 ? b : COMPAREABLE_TO_KEY(data[a], data[c]) > 0 ? c : a); - } - - static class QuickSortAction KEY_GENERIC_TYPE extends RecursiveAction { - private static final long serialVersionUID = 0L; - KEY_TYPE[] array; - int from; - int to; - - QuickSortAction(KEY_TYPE[] array, int from, int to) - { - this.array = array; - this.from = from; - this.to = to; - } - - @Override - protected void compute() - { - int length = to - from; - if(length <= 0) return; - if(length < BASE_THRESHOLD) { - selectionSort(array, from, to); - return; - } - KEY_TYPE pivot = array[length > 128 ? subMedium(array, from, from + (length / 2), to - 1, length / 8) : medium(array, from, from + (length / 2), to - 1)]; - int a = from, b = a, c = to - 1, d = c; - for(int comp = 0;;swap(array, b++, c--)) { - for(;b<=c && (comp = COMPAREABLE_TO_KEY(array[b], pivot)) <= 0;b++) { - if(comp == 0) swap(array, a++, b); - } - for(;c>=b && (comp = COMPAREABLE_TO_KEY(array[c], pivot)) >= 0;c--) { - if(comp == 0) swap(array, c, d--); - } - if(b>c) break; - } - swap(array, from, b, Math.min(a - from, b - a)); - swap(array, b, to, Math.min(d - c, to - d - 1)); - if(b - a > 1 && d - c > 1) invokeAll(new QuickSortActionBRACES(array, from, from + (b - a)), new QuickSortActionBRACES(array, to - (d - c), to)); - else if(b - a > 1) new QuickSortActionBRACES(array, from, from + (b - a)).invoke(); - else if(d - c > 1) new QuickSortActionBRACES(array, to - (d - c), to).invoke(); - } - } - - static class QuickSortActionComp KEY_GENERIC_TYPE extends RecursiveAction { - private static final long serialVersionUID = 0L; - KEY_TYPE[] array; - int from; - int to; - COMPARATOR KEY_GENERIC_TYPE comp; - - QuickSortActionComp(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) - { - this.array = array; - this.from = from; - this.to = to; - this.comp = comp; - } - - @Override - protected void compute() - { - int length = to - from; - if(length <= 0) return; - if(length < BASE_THRESHOLD) { - selectionSort(array, from, to, comp); - return; - } - KEY_TYPE pivot = array[length > 128 ? subMedium(array, from, from + (length / 2), to - 1, length / 8, comp) : medium(array, from, from + (length / 2), to - 1, comp)]; - int a = from, b = a, c = to - 1, d = c; - for(int compare;;swap(array, b++, c--)) { - for(;b<=c && (compare = comp.compare(array[b], pivot)) <= 0;b++) { - if(compare == 0) swap(array, a++, b); - } - for(;c>=b && (compare = comp.compare(array[c], pivot)) >= 0;c--) { - if(compare == 0) swap(array, c, d--); - } - if(b>c) break; - } - swap(array, from, b, Math.min(a - from, b - a)); - swap(array, b, to, Math.min(d - c, to - d - 1)); - if(b - a > 1 && d - c > 1) invokeAll(new QuickSortActionCompBRACES(array, from, from + (b - a), comp), new QuickSortActionCompBRACES(array, to - (d - c), to, comp)); - else if(b - a > 1) new QuickSortActionCompBRACES(array, from, from + (b - a), comp).invoke(); - else if(d - c > 1) new QuickSortActionCompBRACES(array, to - (d - c), to, comp).invoke(); - } - } - - static class MergeSortAction KEY_GENERIC_TYPE extends RecursiveAction { - private static final long serialVersionUID = 0L; - KEY_TYPE[] array; - KEY_TYPE[] supp; - int from; - int to; - - MergeSortAction(KEY_TYPE[] array, KEY_TYPE[] supp, int from, int to) - { - this.array = array; - this.supp = supp; - this.from = from; - this.to = to; - } - - @Override - protected void compute() - { - if(to - from < BASE_THRESHOLD) { - insertionSort(array, from, to); - return; - } - if(supp == null) supp = Arrays.copyOf(array, to); - int mid = (from + to) >>> 1; - invokeAll(new MergeSortActionBRACES(supp, array, from, mid), new MergeSortActionBRACES(supp, array, mid, to)); - if(COMPAREABLE_TO_KEY(supp[mid - 1], supp[mid]) <= 0) - { - System.arraycopy(supp, from, array, from, to - from); - return; - } - for(int p = from, q = mid;from < to;from++) { - if(q >= to || p < mid && COMPAREABLE_TO_KEY(supp[p], supp[q]) < 0) array[from] = supp[p++]; - else array[from] = supp[q++]; - } - } - } - - static class MergeSortActionComp KEY_GENERIC_TYPE extends RecursiveAction { - private static final long serialVersionUID = 0L; - KEY_TYPE[] array; - KEY_TYPE[] supp; - int from; - int to; - COMPARATOR KEY_GENERIC_TYPE comp; - - MergeSortActionComp(KEY_TYPE[] array, KEY_TYPE[] supp, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) - { - this.array = array; - this.supp = supp; - this.from = from; - this.to = to; - this.comp = comp; - } - - @Override - protected void compute() - { - if(to - from < BASE_THRESHOLD) { - insertionSort(array, from, to, comp); - return; - } - if(supp == null) supp = Arrays.copyOf(array, to); - int mid = (from + to) >>> 1; - invokeAll(new MergeSortActionCompBRACES(supp, array, from, mid, comp), new MergeSortActionCompBRACES(supp, array, mid, to, comp)); - if(comp.compare(supp[mid - 1], supp[mid]) <= 0) - { - System.arraycopy(supp, from, array, from, to - from); - return; - } - for(int p = from, q = mid;from < to;from++) { - if(q >= to || p < mid && comp.compare(supp[p], supp[q]) < 0) array[from] = supp[p++]; - else array[from] = supp[q++]; - } - } - } - - static class MemFreeMergeSortAction KEY_GENERIC_TYPE extends RecursiveAction { - private static final long serialVersionUID = 0L; - KEY_TYPE[] array; - int from; - int to; - - MemFreeMergeSortAction(KEY_TYPE[] array, int from, int to) - { - this.array = array; - this.from = from; - this.to = to; - } - - @Override - protected void compute() - { - if(to - from < BASE_THRESHOLD) { - insertionSort(array, from, to); - return; - } - int mid = (from + to) >>> 1; - invokeAll(new MemFreeMergeSortActionBRACES(array, from, mid), new MemFreeMergeSortActionBRACES(array, mid, to)); - if(COMPAREABLE_TO_KEY(array[mid - 1], array[mid]) <= 0) - return; - for(int i = from, j = mid, comp;i < j && j < to;) { - if((comp = COMPAREABLE_TO_KEY(array[i], array[j])) < 0) - i++; - else if(comp == 0) swap(array, ++i, j); - else { - int k = j; - for(;k < to - 1 && COMPAREABLE_TO_KEY(array[i], array[k + 1]) > 0;k++); - if(j == k) { - swap(array, i++, j); - continue; - } - else if(j + 1 == k) { - KEY_TYPE value = array[j]; - System.arraycopy(array, i, array, i+1, j - i); - array[i] = value; - i++; - j++; - continue; - } - KEY_TYPE[] data = NEW_KEY_ARRAY(k - j); - System.arraycopy(array, j, data, 0, data.length); - System.arraycopy(array, i, array, i+data.length, j - i); - System.arraycopy(data, 0, array, i, data.length); - i+=data.length; - j+=data.length; - } - } - } - } - - static class MemFreeMergeSortActionComp KEY_GENERIC_TYPE extends RecursiveAction { - private static final long serialVersionUID = 0L; - KEY_TYPE[] array; - int from; - int to; - COMPARATOR KEY_GENERIC_TYPE comp; - - MemFreeMergeSortActionComp(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) - { - this.array = array; - this.from = from; - this.to = to; - this.comp = comp; - } - - @Override - protected void compute() - { - if(to - from < BASE_THRESHOLD) { - insertionSort(array, from, to, comp); - return; - } - int mid = (from + to) >>> 1; - invokeAll(new MemFreeMergeSortActionCompBRACES(array, from, mid, comp), new MemFreeMergeSortActionCompBRACES(array, mid, to, comp)); - - if(comp.compare(array[mid - 1], array[mid]) <= 0) - return; - for(int i = from, j = mid, compare;i < j && j < to;) { - if((compare = comp.compare(array[i], array[j])) < 0) - i++; - else if(compare == 0) swap(array, ++i, j); - else { - int k = j; - for(;k < to - 1 && comp.compare(array[i], array[k + 1]) > 0;k++); - if(j == k) { - swap(array, i++, j); - continue; - } - else if(j + 1 == k) { - KEY_TYPE value = array[j]; - System.arraycopy(array, i, array, i+1, j - i); - array[i] = value; - i++; - j++; - continue; - } - KEY_TYPE[] data = NEW_KEY_ARRAY(k - j); - System.arraycopy(array, j, data, 0, data.length); - System.arraycopy(array, i, array, i+data.length, j - i); - System.arraycopy(data, 0, array, i, data.length); - i+=data.length; - j+=data.length; - } - } - } - } +package speiger.src.collections.PACKAGE.utils; + +import java.util.Arrays; +#if JAVA_VERSION>=17 +import java.util.random.RANDOM; +#else +import java.util.RANDOM; +#endif +import java.util.concurrent.RecursiveAction; +#if !TYPE_OBJECT + +import speiger.src.collections.PACKAGE.functions.COMPARATOR; +#else +import java.util.Comparator; +import java.util.function.IntFunction; + +#endif +import speiger.src.collections.PACKAGE.collections.ITERATOR; +import speiger.src.collections.utils.SanityChecks; + +/** + * A Helper class for Arrays + */ +public class ARRAYS +{ + /** Default Limit for Insertion/Selection Sort */ + public static final int BASE_THRESHOLD = 16; + /** Default Threshold for Multithreaded Sorting Algorythm options*/ + public static final int PARALLEL_THRESHOLD = 8192; + +#if !TYPE_OBJECT + /** Empty Array Reference used for Uninitialized Collections */ + public static final KEY_TYPE[] EMPTY_ARRAY = new KEY_TYPE[0]; + + /** + * A Helper function to convert a Primitive Array to a CLASS_TYPE Array. + * @param a the array that should be converted + * @return a CLASS_TYPE Array of the input array. + */ + public static CLASS_TYPE[] wrap(KEY_TYPE[] a) { + return wrap(a, 0, a.length); + } + + /** + * A Helper function to convert a Primitive Array to a CLASS_TYPE Array. + * @param a the array that should be converted + * @param length the maximum length that should be coverted + * @return a CLASS_TYPE Array of the input array. + */ + public static CLASS_TYPE[] wrap(KEY_TYPE[] a, int length) { + return wrap(a, 0, length); + } + + /** + * A Helper function to convert a Primitive Array to a CLASS_TYPE Array. + * @param a the array that should be converted + * @param offset the starting offset of the inputarray + * @param length the maximum length that should be coverted + * @return a CLASS_TYPE Array of the input array. + */ + public static CLASS_TYPE[] wrap(KEY_TYPE[] a, int offset, int length) { + SanityChecks.checkArrayCapacity(a.length, offset, length); + CLASS_TYPE[] result = new CLASS_TYPE[length]; + for(int i = offset;i clz, int length) { + if(clz == Object.class) return (KEY_TYPE[])new Object[length]; + return (KEY_TYPE[]) java.lang.reflect.Array.newInstance(clz, length); + } + +#endif + /** + * A Helper function that pours all elements of a iterator into a Array + * @param iter the elements that should be gathered. + * @ArrayType(T) + * @return array with all elements of the iterator + */ + public static GENERIC_KEY_BRACES KEY_TYPE[] pour(ITERATOR KEY_GENERIC_TYPE iter) { + return pour(iter, Integer.MAX_VALUE); + } + + /** + * A Helper function that pours all elements of a iterator into a Array + * @param iter the elements that should be gathered. + * @param max how many elements should be added + * @ArrayType(T) + * @return array with all requested elements of the iterator + */ + public static GENERIC_KEY_BRACES KEY_TYPE[] pour(ITERATOR KEY_GENERIC_TYPE iter, int max) { + COLLECTIONS.CollectionWrapper KEY_GENERIC_TYPE list = COLLECTIONS.wrapper(); + ITERATORS.pour(iter, list, max); + return list.TO_ARRAY(NEW_KEY_ARRAY(list.size())); + } + +#if TYPE_OBJECT + /** + * A Helper function that pours all elements of a iterator into a Array + * @param iter the elements that should be gathered. + * @ArrayType(T) + * @ArrayType(E) + * @param action that is creating the Array to be poured into + * @return array with all elements of the iterator + */ + public static E[] pour(ITERATOR KEY_GENERIC_TYPE iter, IntFunction action) { + return pour(iter, Integer.MAX_VALUE, action); + } + + /** + * A Helper function that pours all elements of a iterator into a Array + * @param iter the elements that should be gathered. + * @param max how many elements should be added + * @param action that is creating the Array to be poured into + * @ArrayType(T) + * @ArrayType(E) + * @return array with all requested elements of the iterator + */ + public static E[] pour(ITERATOR KEY_GENERIC_TYPE iter, int max, IntFunction action) { + COLLECTIONS.CollectionWrapper KEY_GENERIC_TYPE list = COLLECTIONS.wrapper(); + ITERATORS.pour(iter, list, max); + return list.TO_ARRAY(action.apply(list.size())); + } + +#endif + + /** + * Method to validate if the current value is the lowest value in the heap + * @param data the current heap. + * @param size the size of the heap + * @param index the index that should be validated + * @param comp the comparator to sort the heap. Can be null + * @ArrayType(T) + * @return the index the element was shifted to + */ + public static GENERIC_KEY_BRACES int shiftDown(KEY_TYPE[] data, int size, int index, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { + int half = size >>> 1; + KEY_TYPE value = data[index]; + if(comp != null) { + while(index < half) { + int child = (index << 1) + 1; + KEY_TYPE childValue = data[child]; + int right = child+1; + if(right < size && comp.compare(data[right], childValue) < 0) childValue = data[child = right]; + if(comp.compare(value, childValue) <= 0) break; + data[index] = childValue; + index = child; + } + } + else { + while(index < half) { + int child = (index << 1) + 1; + KEY_TYPE childValue = data[child]; + int right = child+1; + if(right < size && COMPAREABLE_TO_KEY(data[right], childValue) < 0) childValue = data[child = right]; + if(COMPAREABLE_TO_KEY(value, childValue) <= 0) break; + data[index] = childValue; + index = child; + } + } + data[index] = value; + return index; + } + + /** + * Method to sort a specific value into the heap. + * @param data the heap itself. + * @param index that should be heapified. + * @param comp the comparator to sort the heap. Can be null + * @ArrayType(T) + * @return the index the element was shifted to + */ + public static GENERIC_KEY_BRACES int shiftUp(KEY_TYPE[] data, int index, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { + KEY_TYPE value = data[index]; + if(comp != null) { + while(index > 0) { + int parent = (index - 1) >>> 1; + KEY_TYPE parentValue = data[parent]; + if(comp.compare(value, parentValue) >= 0) break; + data[index] = parentValue; + index = parent; + } + } + else { + while(index > 0) { + int parent = (index - 1) >>> 1; + KEY_TYPE parentValue = data[parent]; + if(COMPAREABLE_TO_KEY(value, parentValue) >= 0) break; + data[index] = parentValue; + index = parent; + } + } + data[index] = value; + return index; + } + + /** + * Helper function to create a Heap out of an array. + * @param data the array to heapify + * @param size the current size of elements within the array. + * @param comp the Comparator to sort the array. Can be null + * @ArrayType(T) + * @return the input array + */ + public static GENERIC_KEY_BRACES KEY_TYPE[] heapify(KEY_TYPE[] data, int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { + for(int i = (size >>> 1) - 1;i>=0;shiftDown(data, size, i--, comp)); + return data; + } + + /** + * Simple Shuffle method for Arrays. + * @param array the elements that should be shuffled + * @ArrayType(T) + * @note This uses the SanityChecks#getRandom + * @return the provided sorted array + */ + public static GENERIC_KEY_BRACES KEY_TYPE[] shuffle(KEY_TYPE[] array) { + return shuffle(array, SanityChecks.getRandom()); + } + + /** + * Simple Shuffle method for Arrays. + * @param array the elements that should be shuffled + * @param length the length of the array + * @ArrayType(T) + * @note This uses the SanityChecks#getRandom + * @return the provided sorted array + */ + public static GENERIC_KEY_BRACES KEY_TYPE[] shuffle(KEY_TYPE[] array, int length) { + return shuffle(array, 0, length, SanityChecks.getRandom()); + } + + /** + * Simple Shuffle method for Arrays. + * @param array the elements that should be shuffled + * @param offset the start array + * @param length the length of the array + * @ArrayType(T) + * @note This uses the SanityChecks#getRandom + * @return the provided sorted array + */ + public static GENERIC_KEY_BRACES KEY_TYPE[] shuffle(KEY_TYPE[] array, int offset, int length) { + return shuffle(array, offset, length, SanityChecks.getRandom()); + } + + /** + * Simple Shuffle method for Arrays. + * @param array the elements that should be shuffled + * @param random the Random Number Generator that should be used for the shuffling + * @ArrayType(T) + * @return the provided sorted array + */ + public static GENERIC_KEY_BRACES KEY_TYPE[] shuffle(KEY_TYPE[] array, RANDOM random) { + for(int i = array.length-1; i>=0;i--) { + int p = random.nextInt(i + 1); + KEY_TYPE t = array[i]; + array[i] = array[p]; + array[p] = t; + } + return array; + } + + /** + * Simple Shuffle method for Arrays. + * @param array the elements that should be shuffled + * @param length the length of the array + * @param random the Random Number Generator that should be used for the shuffling + * @ArrayType(T) + * @return the provided sorted array + */ + public static GENERIC_KEY_BRACES KEY_TYPE[] shuffle(KEY_TYPE[] array, int length, RANDOM random) { + return shuffle(array, 0, length, random); + } + + /** + * Simple Shuffle method for Arrays. + * @param array the elements that should be shuffled + * @param offset the start array + * @param length the length of the array + * @param random the Random Number Generator that should be used for the shuffling + * @ArrayType(T) + * @return the provided sorted array + */ + public static GENERIC_KEY_BRACES KEY_TYPE[] shuffle(KEY_TYPE[] array, int offset, int length, RANDOM random) { + for(int i = length-1; i>=0;i--) { + int p = offset + random.nextInt(i + 1); + KEY_TYPE t = array[offset+i]; + array[offset+i] = array[p]; + array[p] = t; + } + return array; + } + + /** + * Simple Array Reversal method + * @param array the Array that should flip + * @ArrayType(T) + * @return the provided array + */ + public static GENERIC_KEY_BRACES KEY_TYPE[] reverse(KEY_TYPE[] array) { + return reverse(array, 0, array.length); + } + + /** + * Simple Array Reversal method + * @param array the Array that should flip + * @param length the length of the array + * @ArrayType(T) + * @return the provided array + */ + public static GENERIC_KEY_BRACES KEY_TYPE[] reverse(KEY_TYPE[] array, int length) { + return reverse(array, 0, length); + } + + /** + * Simple Array Reversal method + * @param array the Array that should flip + * @param length the length of the array + * @param offset the start of the array + * @ArrayType(T) + * @return the provided array + */ + public static GENERIC_KEY_BRACES KEY_TYPE[] reverse(KEY_TYPE[] array, int offset, int length) { + for (int i = offset, mid = offset + length >> 1, j = offset + length - 1; i < mid; i++, j--) { + KEY_TYPE temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + return array; + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator, + * potentially dynamically choosing an appropriate algorithm given the type and size of the array. + * Stable sort referres to Mergesort or Insertionsort + * @param array the array that needs to be sorted + * @ArrayType(T) + * @param comp the Comparator that decides the sorting order + * @return input array. + */ + public static GENERIC_KEY_BRACES KEY_TYPE[] stableSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) { + stableSort(array, 0, array.length, comp); + return array; + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator, + * potentially dynamically choosing an appropriate algorithm given the type and size of the array. + * Stable sort referres to Mergesort or Insertionsort + * @param array the array that needs to be sorted + * @param length the maxmium size of the array to be sorted + * @param comp the Comparator that decides the sorting order + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void stableSort(KEY_TYPE[] array, int length, COMPARATOR KEY_GENERIC_TYPE comp) { + stableSort(array, 0, length, comp); + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator, + * potentially dynamically choosing an appropriate algorithm given the type and size of the array. + * Stable sort referres to Mergesort or Insertionsort + * @param array the array that needs to be sorted + * @param from where the array should be sorted from + * @param to where the array should be sorted to + * @param comp the Comparator that decides the sorting order + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void stableSort(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) { + mergeSort(array, null, from, to, comp); + } + + /** + * Sorts an array according to the natural ascending order, + * potentially dynamically choosing an appropriate algorithm given the type and size of the array. + * Stable sort referres to Mergesort or Insertionsort + * @param array the array that needs to be sorted + * @ArrayType(T) + * @return input array + */ + public static GENERIC_KEY_BRACES KEY_TYPE[] stableSort(KEY_TYPE[] array) { + stableSort(array, 0, array.length); + return array; + } + + /** + * Sorts an array according to the natural ascending order, + * potentially dynamically choosing an appropriate algorithm given the type and size of the array. + * Stable sort referres to Mergesort or Insertionsort + * @param array the array that needs to be sorted + * @param length the maxmium size of the array to be sorted + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void stableSort(KEY_TYPE[] array, int length) { + stableSort(array, 0, length); + } + + /** + * Sorts an array according to the natural ascending order, + * potentially dynamically choosing an appropriate algorithm given the type and size of the array. + * Stable sort referres to Mergesort or Insertionsort + * @param array the array that needs to be sorted + * @param from where the array should be sorted from + * @param to where the array should be sorted to + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void stableSort(KEY_TYPE[] array, int from, int to) { + mergeSort(array, null, from, to); + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator, + * potentially dynamically choosing an appropriate algorithm given the type and size of the array. + * Unstable sort referres to QuickSort or SelectionSort + * @param array the array that needs to be sorted + * @param comp the Comparator that decides the sorting order + * @ArrayType(T) + * @return input array + */ + public static GENERIC_KEY_BRACES KEY_TYPE[] unstableSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) { + unstableSort(array, 0, array.length, comp); + return array; + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator, + * potentially dynamically choosing an appropriate algorithm given the type and size of the array. + * Unstable sort referres to QuickSort or SelectionSort + * @param array the array that needs to be sorted + * @param length the maxmium size of the array to be sorted + * @param comp the Comparator that decides the sorting order + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void unstableSort(KEY_TYPE[] array, int length, COMPARATOR KEY_GENERIC_TYPE comp) { + unstableSort(array, 0, length, comp); + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator, + * potentially dynamically choosing an appropriate algorithm given the type and size of the array. + * Unstable sort referres to QuickSort or SelectionSort + * @param array the array that needs to be sorted + * @param from where the array should be sorted from + * @param to where the array should be sorted to + * @param comp the Comparator that decides the sorting order + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void unstableSort(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) { + quickSort(array, from, to, comp); + } + + /** + * Sorts an array according to the natural ascending order, + * potentially dynamically choosing an appropriate algorithm given the type and size of the array. + * Unstable sort referres to QuickSort or SelectionSort + * @param array the array that needs to be sorted + * @ArrayType(T) + * @return input array + */ + public static GENERIC_KEY_BRACES KEY_TYPE[] unstableSort(KEY_TYPE[] array) { + unstableSort(array, 0, array.length); + return array; + } + + /** + * Sorts an array according to the natural ascending order, + * potentially dynamically choosing an appropriate algorithm given the type and size of the array. + * Unstable sort referres to QuickSort or SelectionSort + * @param array the array that needs to be sorted + * @param length the maxmium size of the array to be sorted + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void unstableSort(KEY_TYPE[] array, int length) { + unstableSort(array, 0, length); + } + + /** + * Sorts an array according to the natural ascending order, + * potentially dynamically choosing an appropriate algorithm given the type and size of the array. + * Unstable sort referres to QuickSort or SelectionSort + * @param array the array that needs to be sorted + * @param from where the array should be sorted from + * @param to where the array should be sorted to + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void unstableSort(KEY_TYPE[] array, int from, int to) { + quickSort(array, from, to); + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator using Insertion Sort, + * @param array the array that needs to be sorted + * @param comp the Comparator that decides the sorting order + * @ArrayType(T) + * @return input array + */ + public static GENERIC_KEY_BRACES KEY_TYPE[] insertionSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) { + insertionSort(array, 0, array.length, comp); + return array; + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator using Insertion Sort, + * @param array the array that needs to be sorted + * @param length the maxmium size of the array to be sorted + * @param comp the Comparator that decides the sorting order + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void insertionSort(KEY_TYPE[] array, int length, COMPARATOR KEY_GENERIC_TYPE comp) { + insertionSort(array, 0, length, comp); + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator using Insertion Sort, + * @param array the array that needs to be sorted + * @param from where the array should be sorted from + * @param to where the array should be sorted to + * @param comp the Comparator that decides the sorting order + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void insertionSort(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) { + for (int i = from+1;i= from && comp.compare(current, array[j]) < 0) { + array[j+1] = array[j--]; + } + array[j+1] = current; + } + } + + /** + * Sorts an array according to the natural ascending order using InsertionSort, + * @param array the array that needs to be sorted + * @ArrayType(T) + * @return input array + */ + public static GENERIC_KEY_BRACES KEY_TYPE[] insertionSort(KEY_TYPE[] array) { + insertionSort(array, 0, array.length); + return array; + } + + /** + * Sorts an array according to the natural ascending order using InsertionSort, + * @param array the array that needs to be sorted + * @param length the maxmium size of the array to be sorted + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void insertionSort(KEY_TYPE[] array, int length) { + insertionSort(array, 0, length); + } + + /** + * Sorts an array according to the natural ascending order using InsertionSort, + * @param array the array that needs to be sorted + * @param from where the array should be sorted from + * @param to where the array should be sorted to + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void insertionSort(KEY_TYPE[] array, int from, int to) { + for (int i = from+1;i= from && COMPAREABLE_TO_KEY(current, array[j]) < 0) { + array[j+1] = array[j--]; + } + array[j+1] = current; + } + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator using Selection Sort, + * @param array the array that needs to be sorted + * @param comp the Comparator that decides the sorting order + * @ArrayType(T) + * @return input array + */ + public static GENERIC_KEY_BRACES KEY_TYPE[] selectionSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) { + selectionSort(array, 0, array.length, comp); + return array; + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator using Selection Sort, + * @param array the array that needs to be sorted + * @param length the maxmium size of the array to be sorted + * @param comp the Comparator that decides the sorting order + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void selectionSort(KEY_TYPE[] array, int length, COMPARATOR KEY_GENERIC_TYPE comp) { + selectionSort(array, 0, length, comp); + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator using Selection Sort, + * @param array the array that needs to be sorted + * @param from where the array should be sorted from + * @param to where the array should be sorted to + * @param comp the Comparator that decides the sorting order + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void selectionSort(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) { + for (int i = from; i < to; i++) { + KEY_TYPE min = array[i]; + int minId = i; + for(int j = i+1; j < to; j++) { + if(comp.compare(array[j], min) < 0) { + min = array[j]; + minId = j; + } + } + KEY_TYPE temp = array[i]; + array[i] = min; + array[minId] = temp; + } + } + + /** + * Sorts an array according to the natural ascending order using Selection Sort, + * @param array the array that needs to be sorted + * @ArrayType(T) + * @return input array + */ + public static GENERIC_KEY_BRACES KEY_TYPE[] selectionSort(KEY_TYPE[] array) { + selectionSort(array, 0, array.length); + return array; + } + + /** + * Sorts an array according to the natural ascending order using Selection Sort, + * @param array the array that needs to be sorted + * @param length the maxmium size of the array to be sorted + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void selectionSort(KEY_TYPE[] array, int length) { + selectionSort(array, 0, length); + } + + /** + * Sorts an array according to the natural ascending order using Selection Sort, + * @param array the array that needs to be sorted + * @param from where the array should be sorted from + * @param to where the array should be sorted to + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void selectionSort(KEY_TYPE[] array, int from, int to) { + for (int i = from; i < to; i++) { + KEY_TYPE min = array[i]; + int minId = i; + for(int j = i+1; j < to; j++) { + if(COMPAREABLE_TO_KEY(array[j], min) < 0) { + min = array[j]; + minId = j; + } + } + KEY_TYPE temp = array[i]; + array[i] = min; + array[minId] = temp; + } + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator using Merge Sort, + * This implementation was copied from FastUtil with a couple custom optimizations + * @param array the array that needs to be sorted + * @param comp the Comparator that decides the sorting order + * @ArrayType(T) + * @return input array + */ + public static GENERIC_KEY_BRACES KEY_TYPE[] mergeSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) { + mergeSort(array, null, 0, array.length, comp); + return array; + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator using Merge Sort, + * This implementation was copied from FastUtil with a couple custom optimizations + * @param array the array that needs to be sorted + * @param length the maxmium size of the array to be sorted + * @param comp the Comparator that decides the sorting order + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void mergeSort(KEY_TYPE[] array, int length, COMPARATOR KEY_GENERIC_TYPE comp) { + mergeSort(array, null, 0, length, comp); + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator using Merge Sort, + * This implementation was copied from FastUtil with a couple custom optimizations + * @param array the array that needs to be sorted + * @param supp the auxillary array that is used to simplify the sorting + * @param from where the array should be sorted from + * @param to where the array should be sorted to + * @param comp the Comparator that decides the sorting order + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void mergeSort(KEY_TYPE[] array, KEY_TYPE[] supp, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) { + if(to - from < BASE_THRESHOLD) { + insertionSort(array, from, to, comp); + return; + } + if(supp == null) supp = Arrays.copyOf(array, to); + int mid = (from + to) >>> 1; + mergeSort(supp, array, from, mid, comp); + mergeSort(supp, array, mid, to, comp); + if(comp.compare(supp[mid - 1], supp[mid]) <= 0) + { + System.arraycopy(supp, from, array, from, to - from); + return; + } + for(int p = from, q = mid;from < to;from++) { + if(q >= to || p < mid && comp.compare(supp[p], supp[q]) < 0) array[from] = supp[p++]; + else array[from] = supp[q++]; + } + } + + /** + * Sorts an array according to the natural ascending order using Merge Sort, + * This implementation was copied from FastUtil with a couple custom optimizations + * @param array the array that needs to be sorted + * @ArrayType(T) + * @return input array + */ + public static GENERIC_KEY_BRACES KEY_TYPE[] mergeSort(KEY_TYPE[] array) { + mergeSort(array, null, 0, array.length); + return array; + } + + /** + * Sorts an array according to the natural ascending order using Merge Sort, + * This implementation was copied from FastUtil with a couple custom optimizations + * @param array the array that needs to be sorted + * @param length the maxmium size of the array to be sorted + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void mergeSort(KEY_TYPE[] array, int length) { + mergeSort(array, null, 0, length); + } + + /** + * Sorts an array according to the natural ascending order using Merge Sort, + * This implementation was copied from FastUtil with a couple custom optimizations + * @param array the array that needs to be sorted + * @param supp the auxillary array that is used to simplify the sorting + * @param from where the array should be sorted from + * @param to where the array should be sorted to + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void mergeSort(KEY_TYPE[] array, KEY_TYPE[] supp, int from, int to) { + if(to - from < BASE_THRESHOLD) { + insertionSort(array, from, to); + return; + } + if(supp == null) supp = Arrays.copyOf(array, to); + int mid = (from + to) >>> 1; + mergeSort(supp, array, from, mid); + mergeSort(supp, array, mid, to); + if(COMPAREABLE_TO_KEY(supp[mid - 1], supp[mid]) <= 0) + { + System.arraycopy(supp, from, array, from, to - from); + return; + } + for(int p = from, q = mid;from < to;from++) { + if(q >= to || p < mid && COMPAREABLE_TO_KEY(supp[p], supp[q]) < 0) array[from] = supp[p++]; + else array[from] = supp[q++]; + } + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator using a Parallel Merge Sort, + * This implementation was copied from FastUtil with a couple custom optimizations + * @param array the array that needs to be sorted + * @param comp the Comparator that decides the sorting order + * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void parallelMergeSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) { + parallelMergeSort(array, null, 0, array.length, comp); + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator using Parallel Merge Sort, + * This implementation was copied from FastUtil with a couple custom optimizations + * @param array the array that needs to be sorted + * @param length the maxmium size of the array to be sorted + * @param comp the Comparator that decides the sorting order + * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void parallelMergeSort(KEY_TYPE[] array, int length, COMPARATOR KEY_GENERIC_TYPE comp) { + parallelMergeSort(array, null, 0, length, comp); + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator using Parallel Merge Sort, + * This implementation was copied from FastUtil with a couple custom optimizations + * @param array the array that needs to be sorted + * @param supp the auxillary array that is used to simplify the sorting + * @param from where the array should be sorted from + * @param to where the array should be sorted to + * @param comp the Comparator that decides the sorting order + * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void parallelMergeSort(KEY_TYPE[] array, KEY_TYPE[] supp, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) { + if(SanityChecks.canParallelTask() && to - from >= PARALLEL_THRESHOLD) { + SanityChecks.invokeTask(new MergeSortActionCompBRACES(array, supp, from, to, comp)); + return; + } + mergeSort(array, supp, from, to, comp); + } + + /** + * Sorts an array according to the natural ascending order using Parallel Merge Sort, + * This implementation was copied from FastUtil with a couple custom optimizations + * @param array the array that needs to be sorted + * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void parallelMergeSort(KEY_TYPE[] array) { + parallelMergeSort(array, null, 0, array.length); + } + + /** + * Sorts an array according to the natural ascending order using Parallel Merge Sort, + * This implementation was copied from FastUtil with a couple custom optimizations + * @param array the array that needs to be sorted + * @param length the maxmium size of the array to be sorted + * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void parallelMergeSort(KEY_TYPE[] array, int length) { + parallelMergeSort(array, null, 0, length); + } + + /** + * Sorts an array according to the natural ascending order using Parallel Merge Sort, + * This implementation was copied from FastUtil with a couple custom optimizations + * @param array the array that needs to be sorted + * @param supp the auxillary array that is used to simplify the sorting + * @param from where the array should be sorted from + * @param to where the array should be sorted to + * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void parallelMergeSort(KEY_TYPE[] array, KEY_TYPE[] supp, int from, int to) { + if(SanityChecks.canParallelTask() && to - from >= PARALLEL_THRESHOLD) { + SanityChecks.invokeTask(new MergeSortActionBRACES(array, supp, from, to)); + return; + } + mergeSort(array, supp, from, to); + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator using Memory Free Merge Sort, + * This implementation is inspired by FastUtil original merge sort, but without the need to allocate a copy of the original Array. It is in Very Unsorted Instances 50% slower then Mergesort, otherwise it as fast. + * @param array the array that needs to be sorted + * @param comp the Comparator that decides the sorting order + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void memFreeMergeSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) { + memFreeMergeSort(array, 0, array.length, comp); + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator using Memory Free Merge Sort, + * This implementation is inspired by FastUtil original merge sort, but without the need to allocate a copy of the original Array. It is in Very Unsorted Instances 50% slower then Mergesort, otherwise it as fast. + * @param array the array that needs to be sorted + * @param length the maxmium size of the array to be sorted + * @param comp the Comparator that decides the sorting order + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void memFreeMergeSort(KEY_TYPE[] array, int length, COMPARATOR KEY_GENERIC_TYPE comp) { + memFreeMergeSort(array, 0, length, comp); + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator using Memory Free Merge Sort, + * This implementation is inspired by FastUtil original merge sort, but without the need to allocate a copy of the original Array. It is in Very Unsorted Instances 50% slower then Mergesort, otherwise it as fast. + * @param array the array that needs to be sorted + * @param from where the array should be sorted from + * @param to where the array should be sorted to + * @param comp the Comparator that decides the sorting order + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void memFreeMergeSort(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) { + if(to - from < BASE_THRESHOLD) { + insertionSort(array, from, to, comp); + return; + } + int mid = (from + to) >>> 1; + memFreeMergeSort(array, from, mid, comp); + memFreeMergeSort(array, mid, to, comp); + if(comp.compare(array[mid - 1], array[mid]) <= 0) + return; + for(int i = from, j = mid, compare;i < j && j < to;) { + if((compare = comp.compare(array[i], array[j])) < 0) + i++; + else if(compare == 0) swap(array, ++i, j); + else { + int k = j; + for(;k < to - 1 && comp.compare(array[i], array[k + 1]) > 0;k++); + if(j == k) { + swap(array, i++, j); + continue; + } + else if(j + 1 == k) { + KEY_TYPE value = array[j]; + System.arraycopy(array, i, array, i+1, j - i); + array[i] = value; + i++; + j++; + continue; + } + KEY_TYPE[] data = NEW_KEY_ARRAY(k - j); + System.arraycopy(array, j, data, 0, data.length); + System.arraycopy(array, i, array, i+data.length, j - i); + System.arraycopy(data, 0, array, i, data.length); + i+=data.length; + j+=data.length; + } + } + } + + /** + * Sorts an array according to the natural ascending order using Memory Free Merge Sort, + * This implementation is inspired by FastUtil original merge sort, but without the need to allocate a copy of the original Array. + * It is depending on the size and the unsorted level of the input array slower or almost as fast as normal merge sort. Depending on the test size i can be 0.5x slower (5000 elements) or 4x slower (50000 elements) under the assumtion that the array is in its worst case scenario. + * It does stack allocate tiny amounts of data for shifting around elements. + * @author Speiger + * @param array the array that needs to be sorted + * @ArrayType(T) + * @return input array + */ + public static GENERIC_KEY_BRACES KEY_TYPE[] memFreeMergeSort(KEY_TYPE[] array) { + memFreeMergeSort(array, 0, array.length); + return array; + } + + /** + * Sorts an array according to the natural ascending order using Memory Free Merge Sort, + * This implementation is inspired by FastUtil original merge sort, but without the need to allocate a copy of the original Array. + * It is depending on the size and the unsorted level of the input array slower or almost as fast as normal merge sort. Depending on the test size i can be 0.5x slower (5000 elements) or 4x slower (50000 elements) under the assumtion that the array is in its worst case scenario. + * It does stack allocate tiny amounts of data for shifting around elements. + * @author Speiger + * @param array the array that needs to be sorted + * @param length the maxmium size of the array to be sorted + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void memFreeMergeSort(KEY_TYPE[] array, int length) { + memFreeMergeSort(array, 0, length); + } + + /** + * Sorts an array according to the natural ascending order using Memory Free Merge Sort, + * This implementation is inspired by FastUtil original merge sort, but without the need to allocate a copy of the original Array. + * It is depending on the size and the unsorted level of the input array slower or almost as fast as normal merge sort. Depending on the test size i can be 0.5x slower (5000 elements) or 4x slower (50000 elements) under the assumtion that the array is in its worst case scenario. + * It does stack allocate tiny amounts of data for shifting around elements. + * @author Speiger + * @param array the array that needs to be sorted + * @param from where the array should be sorted from + * @param to where the array should be sorted to + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void memFreeMergeSort(KEY_TYPE[] array, int from, int to) { + if(to - from < BASE_THRESHOLD) { + insertionSort(array, from, to); + return; + } + int mid = (from + to) >>> 1; + memFreeMergeSort(array, from, mid); + memFreeMergeSort(array, mid, to); + if(COMPAREABLE_TO_KEY(array[mid - 1], array[mid]) <= 0) + return; + for(int i = from, j = mid, comp;i < j && j < to;) { + if((comp = COMPAREABLE_TO_KEY(array[i], array[j])) < 0) + i++; + else if(comp == 0) swap(array, ++i, j); + else { + int k = j; + for(;k < to - 1 && COMPAREABLE_TO_KEY(array[i], array[k + 1]) > 0;k++); + if(j == k) { + swap(array, i++, j); + continue; + } + else if(j + 1 == k) { + KEY_TYPE value = array[j]; + System.arraycopy(array, i, array, i+1, j - i); + array[i] = value; + i++; + j++; + continue; + } + KEY_TYPE[] data = NEW_KEY_ARRAY(k - j); + System.arraycopy(array, j, data, 0, data.length); + System.arraycopy(array, i, array, i+data.length, j - i); + System.arraycopy(data, 0, array, i, data.length); + i+=data.length; + j+=data.length; + } + } + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator using Parallel Memory Free Merge Sort, + * This implementation is inspired by FastUtil original merge sort, but without the need to allocate a copy of the original Array. + * It is depending on the size and the unsorted level of the input array slower or almost as fast as normal merge sort. Depending on the test size i can be 0.5x slower (5000 elements) or 4x slower (50000 elements) under the assumtion that the array is in its worst case scenario. + * It does stack allocate tiny amounts of data for shifting around elements. + * @author Speiger + * @param array the array that needs to be sorted + * @param comp the Comparator that decides the sorting order + * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void parallelMemFreeMergeSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) { + parallelMemFreeMergeSort(array, 0, array.length, comp); + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator using Parallel Memory Free Merge Sort, + * This implementation is inspired by FastUtil original merge sort, but without the need to allocate a copy of the original Array. + * It is depending on the size and the unsorted level of the input array slower or almost as fast as normal merge sort. Depending on the test size i can be 0.5x slower (5000 elements) or 4x slower (50000 elements) under the assumtion that the array is in its worst case scenario. + * It does stack allocate tiny amounts of data for shifting around elements. + * @author Speiger + * @param array the array that needs to be sorted + * @param length the maxmium size of the array to be sorted + * @param comp the Comparator that decides the sorting order + * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void parallelMemFreeMergeSort(KEY_TYPE[] array, int length, COMPARATOR KEY_GENERIC_TYPE comp) { + parallelMemFreeMergeSort(array, 0, length, comp); + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator using Parallel Memory Free Merge Sort, + * This implementation is inspired by FastUtil original merge sort, but without the need to allocate a copy of the original Array. + * It is depending on the size and the unsorted level of the input array slower or almost as fast as normal merge sort. Depending on the test size i can be 0.5x slower (5000 elements) or 4x slower (50000 elements) under the assumtion that the array is in its worst case scenario. + * It does stack allocate tiny amounts of data for shifting around elements. + * @author Speiger + * @param array the array that needs to be sorted + * @param from where the array should be sorted from + * @param to where the array should be sorted to + * @param comp the Comparator that decides the sorting order + * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void parallelMemFreeMergeSort(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) { + if(SanityChecks.canParallelTask() && to - from >= PARALLEL_THRESHOLD) { + SanityChecks.invokeTask(new MemFreeMergeSortActionCompBRACES(array, from, to, comp)); + return; + } + memFreeMergeSort(array, from, to, comp); + } + + /** + * Sorts an array according to the natural ascending order using Parallel Memory Free Merge Sort, + * This implementation is inspired by FastUtil original merge sort, but without the need to allocate a copy of the original Array. + * It is depending on the size and the unsorted level of the input array slower or almost as fast as normal merge sort. Depending on the test size i can be 0.5x slower (5000 elements) or 4x slower (50000 elements) under the assumtion that the array is in its worst case scenario. + * It does stack allocate tiny amounts of data for shifting around elements. + * @author Speiger + * @param array the array that needs to be sorted + * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void parallelMemFreeMergeSort(KEY_TYPE[] array) { + parallelMemFreeMergeSort(array, 0, array.length); + } + + /** + * Sorts an array according to the natural ascending order using Parallel Memory Free Merge Sort, + * This implementation is inspired by FastUtil original merge sort, but without the need to allocate a copy of the original Array. + * It is depending on the size and the unsorted level of the input array slower or almost as fast as normal merge sort. Depending on the test size i can be 0.5x slower (5000 elements) or 4x slower (50000 elements) under the assumtion that the array is in its worst case scenario. + * It does stack allocate tiny amounts of data for shifting around elements. + * @author Speiger + * @param array the array that needs to be sorted + * @param length the maxmium size of the array to be sorted + * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void parallelMemFreeMergeSort(KEY_TYPE[] array, int length) { + parallelMemFreeMergeSort(array, 0, length); + } + + /** + * Sorts an array according to the natural ascending order using Parallel Memory Free Merge Sort, + * This implementation is inspired by FastUtil original merge sort, but without the need to allocate a copy of the original Array. + * It is depending on the size and the unsorted level of the input array slower or almost as fast as normal merge sort. Depending on the test size i can be 0.5x slower (5000 elements) or 4x slower (50000 elements) under the assumtion that the array is in its worst case scenario. + * It does stack allocate tiny amounts of data for shifting around elements. + * @author Speiger + * @param array the array that needs to be sorted + * @param from where the array should be sorted from + * @param to where the array should be sorted to + * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void parallelMemFreeMergeSort(KEY_TYPE[] array, int from, int to) { + if(SanityChecks.canParallelTask() && to - from >= PARALLEL_THRESHOLD) { + SanityChecks.invokeTask(new MemFreeMergeSortActionBRACES(array, from, to)); + return; + } + memFreeMergeSort(array, from, to); + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator using Quick Sort, + * This implementation is a custom of FastUtil quicksort but with a different code structure, + * and that sorting Algorithm is based on the tuned quicksort adapted from Jon L. Bentley and M. DouglasMcIlroy, "Engineering a Sort Function", Software: Practice and Experience, 23(11), pages1249−1265, 1993. + * @param array the array that needs to be sorted + * @param comp the Comparator that decides the sorting order + * @ArrayType(T) + * @return input array + */ + public static GENERIC_KEY_BRACES KEY_TYPE[] quickSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) { + quickSort(array, 0, array.length, comp); + return array; + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator using Quick Sort, + * This implementation is a custom of FastUtil quicksort but with a different code structure, + * and that sorting Algorithm is based on the tuned quicksort adapted from Jon L. Bentley and M. DouglasMcIlroy, "Engineering a Sort Function", Software: Practice and Experience, 23(11), pages1249−1265, 1993. + * @param array the array that needs to be sorted + * @param length the maxmium size of the array to be sorted + * @param comp the Comparator that decides the sorting order + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void quickSort(KEY_TYPE[] array, int length, COMPARATOR KEY_GENERIC_TYPE comp) { + quickSort(array, 0, length, comp); + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator using Quick Sort, + * This implementation is a custom of FastUtil quicksort but with a different code structure, + * and that sorting Algorithm is based on the tuned quicksort adapted from Jon L. Bentley and M. DouglasMcIlroy, "Engineering a Sort Function", Software: Practice and Experience, 23(11), pages1249−1265, 1993. + * @param array the array that needs to be sorted + * @param from where the array should be sorted from + * @param to where the array should be sorted to + * @param comp the Comparator that decides the sorting order + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void quickSort(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) { + int length = to - from; + if(length <= 0) return; + if(length < BASE_THRESHOLD) { + selectionSort(array, from, to, comp); + return; + } + KEY_TYPE pivot = array[length > 128 ? subMedium(array, from, from + (length / 2), to - 1, length / 8, comp) : medium(array, from, from + (length / 2), to - 1, comp)]; + int a = from, b = a, c = to - 1, d = c; + for(int compare;;swap(array, b++, c--)) { + for(;b<=c && (compare = comp.compare(array[b], pivot)) <= 0;b++) { + if(compare == 0) swap(array, a++, b); + } + for(;c>=b && (compare = comp.compare(array[c], pivot)) >= 0;c--) { + if(compare == 0) swap(array, c, d--); + } + if(b>c) break; + } + swap(array, from, b, Math.min(a - from, b - a)); + swap(array, b, to, Math.min(d - c, to - d - 1)); + if((length = b - a) > 1) quickSort(array, from, from + length, comp); + if((length = d - c) > 1) quickSort(array, to - length, to, comp); + } + + /** + * Sorts an array according to the natural ascending order using Quick Sort, + * This implementation is a custom of FastUtil quicksort but with a different code structure, + * and that sorting Algorithm is based on the tuned quicksort adapted from Jon L. Bentley and M. DouglasMcIlroy, "Engineering a Sort Function", Software: Practice and Experience, 23(11), pages1249−1265, 1993. + * @param array the array that needs to be sorted + * @ArrayType(T) + * @return input array + */ + public static GENERIC_KEY_BRACES KEY_TYPE[] quickSort(KEY_TYPE[] array) { + quickSort(array, 0, array.length); + return array; + } + + /** + * Sorts an array according to the natural ascending order using Quick Sort, + * This implementation is a custom of FastUtil quicksort but with a different code structure, + * and that sorting Algorithm is based on the tuned quicksort adapted from Jon L. Bentley and M. DouglasMcIlroy, "Engineering a Sort Function", Software: Practice and Experience, 23(11), pages1249−1265, 1993. + * @param array the array that needs to be sorted + * @param length the maxmium size of the array to be sorted + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void quickSort(KEY_TYPE[] array, int length) { + quickSort(array, 0, length); + } + + /** + * Sorts an array according to the natural ascending order using Quick Sort, + * This implementation is a custom of FastUtil quicksort but with a different code structure, + * and that sorting Algorithm is based on the tuned quicksort adapted from Jon L. Bentley and M. DouglasMcIlroy, "Engineering a Sort Function", Software: Practice and Experience, 23(11), pages1249−1265, 1993. + * @param array the array that needs to be sorted + * @param from where the array should be sorted from + * @param to where the array should be sorted to + * @ArrayType(T) + */ + public static GENERIC_KEY_BRACES void quickSort(KEY_TYPE[] array, int from, int to) { + int length = to - from; + if(length <= 0) return; + if(length < BASE_THRESHOLD) { + selectionSort(array, from, to); + return; + } + KEY_TYPE pivot = array[length > 128 ? subMedium(array, from, from + (length / 2), to - 1, length / 8) : medium(array, from, from + (length / 2), to - 1)]; + int a = from, b = a, c = to - 1, d = c; + for(int comp = 0;;swap(array, b++, c--)) { + for(;b<=c && (comp = COMPAREABLE_TO_KEY(array[b], pivot)) <= 0;b++) { + if(comp == 0) swap(array, a++, b); + } + for(;c>=b && (comp = COMPAREABLE_TO_KEY(array[c], pivot)) >= 0;c--) { + if(comp == 0) swap(array, c, d--); + } + if(b>c) break; + } + swap(array, from, b, Math.min(a - from, b - a)); + swap(array, b, to, Math.min(d - c, to - d - 1)); + if((length = b - a) > 1) quickSort(array, from, from + length); + if((length = d - c) > 1) quickSort(array, to - length, to); + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator using Parallel Quick Sort, + * This implementation is a custom of FastUtil quicksort but with a different code structure, + * and that sorting Algorithm is based on the tuned quicksort adapted from Jon L. Bentley and M. DouglasMcIlroy, "Engineering a Sort Function", Software: Practice and Experience, 23(11), pages1249−1265, 1993. + * @param array the array that needs to be sorted + * @param comp the Comparator that decides the sorting order + * @ArrayType(T) + * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed + */ + public static GENERIC_KEY_BRACES void parallelQuickSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) { + parallelQuickSort(array, 0, array.length, comp); + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator using Parallel Quick Sort, + * This implementation is a custom of FastUtil quicksort but with a different code structure, + * and that sorting Algorithm is based on the tuned quicksort adapted from Jon L. Bentley and M. DouglasMcIlroy, "Engineering a Sort Function", Software: Practice and Experience, 23(11), pages1249−1265, 1993. + * @param array the array that needs to be sorted + * @param length the maxmium size of the array to be sorted + * @param comp the Comparator that decides the sorting order + * @ArrayType(T) + * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed + */ + public static GENERIC_KEY_BRACES void parallelQuickSort(KEY_TYPE[] array, int length, COMPARATOR KEY_GENERIC_TYPE comp) { + parallelQuickSort(array, 0, length, comp); + } + + /** + * Sorts the specified range of elements according to the order induced by the specified comparator using Parallel Quick Sort, + * This implementation is a custom of FastUtil quicksort but with a different code structure, + * and that sorting Algorithm is based on the tuned quicksort adapted from Jon L. Bentley and M. DouglasMcIlroy, "Engineering a Sort Function", Software: Practice and Experience, 23(11), pages1249−1265, 1993. + * @param array the array that needs to be sorted + * @param from where the array should be sorted from + * @param to where the array should be sorted to + * @param comp the Comparator that decides the sorting order + * @ArrayType(T) + * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed + */ + public static GENERIC_KEY_BRACES void parallelQuickSort(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) { + if(SanityChecks.canParallelTask() && to - from >= PARALLEL_THRESHOLD) { + SanityChecks.invokeTask(new QuickSortActionCompBRACES(array, from, to, comp)); + return; + } + quickSort(array, from, to, comp); + } + + /** + * Sorts an array according to the natural ascending order using Parallel Quick Sort, + * This implementation is a custom of FastUtil quicksort but with a different code structure, + * and that sorting Algorithm is based on the tuned quicksort adapted from Jon L. Bentley and M. DouglasMcIlroy, "Engineering a Sort Function", Software: Practice and Experience, 23(11), pages1249−1265, 1993. + * @param array the array that needs to be sorted + * @ArrayType(T) + * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed + */ + public static GENERIC_KEY_BRACES void parallelQuickSort(KEY_TYPE[] array) { + parallelQuickSort(array, 0, array.length); + } + + /** + * Sorts an array according to the natural ascending order using Parallel Quick Sort, + * This implementation is a custom of FastUtil quicksort but with a different code structure, + * and that sorting Algorithm is based on the tuned quicksort adapted from Jon L. Bentley and M. DouglasMcIlroy, "Engineering a Sort Function", Software: Practice and Experience, 23(11), pages1249−1265, 1993. + * @param array the array that needs to be sorted + * @param length the maxmium size of the array to be sorted + * @ArrayType(T) + * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed + */ + public static GENERIC_KEY_BRACES void parallelQuickSort(KEY_TYPE[] array, int length) { + parallelQuickSort(array, 0, length); + } + + /** + * Sorts an array according to the natural ascending order using Parallel Quick Sort, + * This implementation is a custom of FastUtil quicksort but with a different code structure, + * and that sorting Algorithm is based on the tuned quicksort adapted from Jon L. Bentley and M. DouglasMcIlroy, "Engineering a Sort Function", Software: Practice and Experience, 23(11), pages1249−1265, 1993. + * @param array the array that needs to be sorted + * @param from where the array should be sorted from + * @param to where the array should be sorted to + * @ArrayType(T) + * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed + */ + public static GENERIC_KEY_BRACES void parallelQuickSort(KEY_TYPE[] array, int from, int to) { + if(SanityChecks.canParallelTask() && to - from >= PARALLEL_THRESHOLD) { + SanityChecks.invokeTask(new QuickSortActionBRACES(array, from, to)); + return; + } + quickSort(array, from, to); + } + + static GENERIC_KEY_BRACES void swap(KEY_TYPE[] a, int from, int to) { + KEY_TYPE t = a[from]; + a[from] = a[to]; + a[to] = t; + } + + static GENERIC_KEY_BRACES void swap(KEY_TYPE[] a, int from, int to, int length) { + to -= length; + for(int i = 0;i 0 ? b : comp.compare(data[a], data[c]) > 0 ? c : a); + } + + static GENERIC_KEY_BRACES int subMedium(KEY_TYPE[] data, int a, int b, int c, int length) { + return medium(data, medium(data, a, a + length, a + (length * 2)), medium(data, b - length, b, b + length), medium(data, c - (length * 2), c - length, c)); + } + + static GENERIC_KEY_BRACES int medium(KEY_TYPE[] data, int a, int b, int c) { + return COMPAREABLE_TO_KEY(data[a], data[b]) < 0 ? (COMPAREABLE_TO_KEY(data[b], data[c]) < 0 ? b : COMPAREABLE_TO_KEY(data[a], data[c]) < 0 ? c : a) : (COMPAREABLE_TO_KEY(data[b], data[c]) > 0 ? b : COMPAREABLE_TO_KEY(data[a], data[c]) > 0 ? c : a); + } + + static class QuickSortAction KEY_GENERIC_TYPE extends RecursiveAction { + private static final long serialVersionUID = 0L; + KEY_TYPE[] array; + int from; + int to; + + QuickSortAction(KEY_TYPE[] array, int from, int to) + { + this.array = array; + this.from = from; + this.to = to; + } + + @Override + protected void compute() + { + int length = to - from; + if(length <= 0) return; + if(length < BASE_THRESHOLD) { + selectionSort(array, from, to); + return; + } + KEY_TYPE pivot = array[length > 128 ? subMedium(array, from, from + (length / 2), to - 1, length / 8) : medium(array, from, from + (length / 2), to - 1)]; + int a = from, b = a, c = to - 1, d = c; + for(int comp = 0;;swap(array, b++, c--)) { + for(;b<=c && (comp = COMPAREABLE_TO_KEY(array[b], pivot)) <= 0;b++) { + if(comp == 0) swap(array, a++, b); + } + for(;c>=b && (comp = COMPAREABLE_TO_KEY(array[c], pivot)) >= 0;c--) { + if(comp == 0) swap(array, c, d--); + } + if(b>c) break; + } + swap(array, from, b, Math.min(a - from, b - a)); + swap(array, b, to, Math.min(d - c, to - d - 1)); + if(b - a > 1 && d - c > 1) invokeAll(new QuickSortActionBRACES(array, from, from + (b - a)), new QuickSortActionBRACES(array, to - (d - c), to)); + else if(b - a > 1) new QuickSortActionBRACES(array, from, from + (b - a)).invoke(); + else if(d - c > 1) new QuickSortActionBRACES(array, to - (d - c), to).invoke(); + } + } + + static class QuickSortActionComp KEY_GENERIC_TYPE extends RecursiveAction { + private static final long serialVersionUID = 0L; + KEY_TYPE[] array; + int from; + int to; + COMPARATOR KEY_GENERIC_TYPE comp; + + QuickSortActionComp(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) + { + this.array = array; + this.from = from; + this.to = to; + this.comp = comp; + } + + @Override + protected void compute() + { + int length = to - from; + if(length <= 0) return; + if(length < BASE_THRESHOLD) { + selectionSort(array, from, to, comp); + return; + } + KEY_TYPE pivot = array[length > 128 ? subMedium(array, from, from + (length / 2), to - 1, length / 8, comp) : medium(array, from, from + (length / 2), to - 1, comp)]; + int a = from, b = a, c = to - 1, d = c; + for(int compare;;swap(array, b++, c--)) { + for(;b<=c && (compare = comp.compare(array[b], pivot)) <= 0;b++) { + if(compare == 0) swap(array, a++, b); + } + for(;c>=b && (compare = comp.compare(array[c], pivot)) >= 0;c--) { + if(compare == 0) swap(array, c, d--); + } + if(b>c) break; + } + swap(array, from, b, Math.min(a - from, b - a)); + swap(array, b, to, Math.min(d - c, to - d - 1)); + if(b - a > 1 && d - c > 1) invokeAll(new QuickSortActionCompBRACES(array, from, from + (b - a), comp), new QuickSortActionCompBRACES(array, to - (d - c), to, comp)); + else if(b - a > 1) new QuickSortActionCompBRACES(array, from, from + (b - a), comp).invoke(); + else if(d - c > 1) new QuickSortActionCompBRACES(array, to - (d - c), to, comp).invoke(); + } + } + + static class MergeSortAction KEY_GENERIC_TYPE extends RecursiveAction { + private static final long serialVersionUID = 0L; + KEY_TYPE[] array; + KEY_TYPE[] supp; + int from; + int to; + + MergeSortAction(KEY_TYPE[] array, KEY_TYPE[] supp, int from, int to) + { + this.array = array; + this.supp = supp; + this.from = from; + this.to = to; + } + + @Override + protected void compute() + { + if(to - from < BASE_THRESHOLD) { + insertionSort(array, from, to); + return; + } + if(supp == null) supp = Arrays.copyOf(array, to); + int mid = (from + to) >>> 1; + invokeAll(new MergeSortActionBRACES(supp, array, from, mid), new MergeSortActionBRACES(supp, array, mid, to)); + if(COMPAREABLE_TO_KEY(supp[mid - 1], supp[mid]) <= 0) + { + System.arraycopy(supp, from, array, from, to - from); + return; + } + for(int p = from, q = mid;from < to;from++) { + if(q >= to || p < mid && COMPAREABLE_TO_KEY(supp[p], supp[q]) < 0) array[from] = supp[p++]; + else array[from] = supp[q++]; + } + } + } + + static class MergeSortActionComp KEY_GENERIC_TYPE extends RecursiveAction { + private static final long serialVersionUID = 0L; + KEY_TYPE[] array; + KEY_TYPE[] supp; + int from; + int to; + COMPARATOR KEY_GENERIC_TYPE comp; + + MergeSortActionComp(KEY_TYPE[] array, KEY_TYPE[] supp, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) + { + this.array = array; + this.supp = supp; + this.from = from; + this.to = to; + this.comp = comp; + } + + @Override + protected void compute() + { + if(to - from < BASE_THRESHOLD) { + insertionSort(array, from, to, comp); + return; + } + if(supp == null) supp = Arrays.copyOf(array, to); + int mid = (from + to) >>> 1; + invokeAll(new MergeSortActionCompBRACES(supp, array, from, mid, comp), new MergeSortActionCompBRACES(supp, array, mid, to, comp)); + if(comp.compare(supp[mid - 1], supp[mid]) <= 0) + { + System.arraycopy(supp, from, array, from, to - from); + return; + } + for(int p = from, q = mid;from < to;from++) { + if(q >= to || p < mid && comp.compare(supp[p], supp[q]) < 0) array[from] = supp[p++]; + else array[from] = supp[q++]; + } + } + } + + static class MemFreeMergeSortAction KEY_GENERIC_TYPE extends RecursiveAction { + private static final long serialVersionUID = 0L; + KEY_TYPE[] array; + int from; + int to; + + MemFreeMergeSortAction(KEY_TYPE[] array, int from, int to) + { + this.array = array; + this.from = from; + this.to = to; + } + + @Override + protected void compute() + { + if(to - from < BASE_THRESHOLD) { + insertionSort(array, from, to); + return; + } + int mid = (from + to) >>> 1; + invokeAll(new MemFreeMergeSortActionBRACES(array, from, mid), new MemFreeMergeSortActionBRACES(array, mid, to)); + if(COMPAREABLE_TO_KEY(array[mid - 1], array[mid]) <= 0) + return; + for(int i = from, j = mid, comp;i < j && j < to;) { + if((comp = COMPAREABLE_TO_KEY(array[i], array[j])) < 0) + i++; + else if(comp == 0) swap(array, ++i, j); + else { + int k = j; + for(;k < to - 1 && COMPAREABLE_TO_KEY(array[i], array[k + 1]) > 0;k++); + if(j == k) { + swap(array, i++, j); + continue; + } + else if(j + 1 == k) { + KEY_TYPE value = array[j]; + System.arraycopy(array, i, array, i+1, j - i); + array[i] = value; + i++; + j++; + continue; + } + KEY_TYPE[] data = NEW_KEY_ARRAY(k - j); + System.arraycopy(array, j, data, 0, data.length); + System.arraycopy(array, i, array, i+data.length, j - i); + System.arraycopy(data, 0, array, i, data.length); + i+=data.length; + j+=data.length; + } + } + } + } + + static class MemFreeMergeSortActionComp KEY_GENERIC_TYPE extends RecursiveAction { + private static final long serialVersionUID = 0L; + KEY_TYPE[] array; + int from; + int to; + COMPARATOR KEY_GENERIC_TYPE comp; + + MemFreeMergeSortActionComp(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) + { + this.array = array; + this.from = from; + this.to = to; + this.comp = comp; + } + + @Override + protected void compute() + { + if(to - from < BASE_THRESHOLD) { + insertionSort(array, from, to, comp); + return; + } + int mid = (from + to) >>> 1; + invokeAll(new MemFreeMergeSortActionCompBRACES(array, from, mid, comp), new MemFreeMergeSortActionCompBRACES(array, mid, to, comp)); + + if(comp.compare(array[mid - 1], array[mid]) <= 0) + return; + for(int i = from, j = mid, compare;i < j && j < to;) { + if((compare = comp.compare(array[i], array[j])) < 0) + i++; + else if(compare == 0) swap(array, ++i, j); + else { + int k = j; + for(;k < to - 1 && comp.compare(array[i], array[k + 1]) > 0;k++); + if(j == k) { + swap(array, i++, j); + continue; + } + else if(j + 1 == k) { + KEY_TYPE value = array[j]; + System.arraycopy(array, i, array, i+1, j - i); + array[i] = value; + i++; + j++; + continue; + } + KEY_TYPE[] data = NEW_KEY_ARRAY(k - j); + System.arraycopy(array, j, data, 0, data.length); + System.arraycopy(array, i, array, i+data.length, j - i); + System.arraycopy(data, 0, array, i, data.length); + i+=data.length; + j+=data.length; + } + } + } + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/collections/templates/utils/Collections.template b/src/builder/resources/speiger/assets/collections/templates/utils/Collections.template index 5d26d23..f8a98a4 100644 --- a/src/builder/resources/speiger/assets/collections/templates/utils/Collections.template +++ b/src/builder/resources/speiger/assets/collections/templates/utils/Collections.template @@ -1,1038 +1,1037 @@ -package speiger.src.collections.PACKAGE.utils; - -import java.util.Arrays; -import java.util.Collection; -#if !TYPE_BOOLEAN -import java.util.ConcurrentModificationException; -#endif -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.Objects; -#if TYPE_OBJECT -import java.util.Comparator; -import java.util.function.BiFunction; -#endif -import java.util.function.Predicate; -#if JDK_FUNCTION && !TYPE_OBJECT -import java.util.function.PREDICATE; -#endif -#if PRIMITIVES && !JDK_FUNCTION -import java.util.function.JAVA_PREDICATE; -#endif -import java.util.function.Consumer; - -import speiger.src.collections.PACKAGE.collections.ABSTRACT_COLLECTION; -import speiger.src.collections.PACKAGE.collections.COLLECTION; -import speiger.src.collections.PACKAGE.collections.ITERATOR; -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.functions.COMPARATOR; -#endif -import speiger.src.collections.objects.utils.ObjectArrays; -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.functions.CONSUMER; -import speiger.src.collections.PACKAGE.utils.ARRAYS; -#endif -#if !JDK_FUNCTION -import speiger.src.collections.PACKAGE.functions.function.PREDICATE; -#endif -import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; -import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER; -import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; -#if !TYPE_BOOLEAN -import speiger.src.collections.utils.HashUtil; -#endif -import speiger.src.collections.utils.ITrimmable; -import speiger.src.collections.utils.SanityChecks; - -/** - * A Helper class for Collections - */ -public class COLLECTIONS -{ - /** - * Empty Collection Reference - */ - public static final COLLECTION NO_GENERIC_TYPE EMPTY = new EmptyCollectionBRACES(); - - /** - * Returns a Immutable EmptyCollection instance that is automatically casted. - * @Type(T) - * @return an empty collection - */ - public static GENERIC_KEY_BRACES COLLECTION KEY_GENERIC_TYPE empty() { -#if TYPE_OBJECT - return (COLLECTION)EMPTY; -#else - return EMPTY; -#endif - } - - /** - * Returns a Immutable Collection instance based on the instance given. - * @param c that should be made immutable/unmodifiable - * @Type(T) - * @return a unmodifiable collection wrapper. If the Collection already a unmodifiable wrapper then it just returns itself. - */ - public static GENERIC_KEY_BRACES COLLECTION KEY_GENERIC_TYPE unmodifiable(COLLECTION KEY_GENERIC_TYPE c) { - return c instanceof UnmodifiableCollection ? c : new UnmodifiableCollectionBRACES(c); - } - - /** - * Returns a synchronized Collection instance based on the instance given. - * @param c that should be synchronized - * @Type(T) - * @return a synchronized collection wrapper. If the Collection already a synchronized wrapper then it just returns itself. - */ - public static GENERIC_KEY_BRACES COLLECTION KEY_GENERIC_TYPE synchronize(COLLECTION KEY_GENERIC_TYPE c) { - return c instanceof SynchronizedCollection ? c : new SynchronizedCollectionBRACES(c); - } - - /** - * Returns a synchronized Collection instance based on the instance given. - * @param c that should be synchronized - * @param mutex is the controller of the synchronization block. - * @Type(T) - * @return a synchronized collection wrapper. If the Collection already a synchronized wrapper then it just returns itself. - */ - public static GENERIC_KEY_BRACES COLLECTION KEY_GENERIC_TYPE synchronize(COLLECTION KEY_GENERIC_TYPE c, Object mutex) { - return c instanceof SynchronizedCollection ? c : new SynchronizedCollectionBRACES(c, mutex); - } - - /** - * Creates a Singleton Collection of a given element - * @param element the element that should be converted into a singleton collection - * @Type(T) - * @return a singletoncollection of the given element - */ - public static GENERIC_KEY_BRACES COLLECTION KEY_GENERIC_TYPE singleton(KEY_TYPE element) { - return new SingletonCollectionBRACES(element); - } - - protected static GENERIC_KEY_BRACES CollectionWrapper KEY_GENERIC_TYPE wrapper() { - return new CollectionWrapperBRACES(); - } - - protected static GENERIC_KEY_BRACES CollectionWrapper KEY_GENERIC_TYPE wrapper(int size) { - return new CollectionWrapperBRACES(size); - } - -#if !TYPE_BOOLEAN - protected static GENERIC_KEY_BRACES DistinctCollectionWrapper KEY_GENERIC_TYPE distinctWrapper() { - return new DistinctCollectionWrapperBRACES(); - } - - protected static GENERIC_KEY_BRACES DistinctCollectionWrapper KEY_GENERIC_TYPE distinctWrapper(int size) { - return new DistinctCollectionWrapperBRACES(size); - } - -#endif - protected static class CollectionWrapper KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION KEY_GENERIC_TYPE implements ITrimmable { - KEY_TYPE[] elements; - int size = 0; - - public CollectionWrapper() { - this(10); - } - - public CollectionWrapper(int size) { - if(size < 0) throw new IllegalStateException("Size has to be 0 or greater"); - elements = NEW_KEY_ARRAY(size); - } - - @Override - public boolean add(KEY_TYPE o) { - if(size >= elements.length) elements = Arrays.copyOf(elements, (int)Math.min((long)elements.length + (elements.length >> 1), SanityChecks.MAX_ARRAY_SIZE)); - elements[size++] = o; - return true; - } - - public KEY_TYPE GET_KEY(int index) { - if(index < 0 || index >= size) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); - return elements[index]; - } - -#if TYPE_OBJECT - @Override - public boolean remove(Object e) { - for(int i = 0;i= size) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); - size--; - if(index != size) System.arraycopy(elements, index+1, elements, index, size - index); - } - - @Override - public ITERATOR KEY_GENERIC_TYPE iterator() { - return new ITERATOR KEY_GENERIC_TYPE() { - int index = 0; - int lastReturned = -1; - - @Override - public boolean hasNext() { - return index < size; - } - - @Override - public KEY_TYPE NEXT() { - int i = index++; - return elements[(lastReturned = i)]; - } - - @Override - public void remove() { - if(lastReturned == -1) throw new IllegalStateException(); - removeIndex(lastReturned); - index = lastReturned; - lastReturned = -1; - } - }; - } - - @Override - public int size() { - return size; - } - - @Override - public void clear() { -#if TYPE_OBJECT - for(int i = 0;i c) { - if(c != null) ARRAYS.stableSort(elements, size, c); - else ARRAYS.stableSort(elements, size); - } - - public void unstableSort(Comparator c) { - if(c != null) ARRAYS.unstableSort(elements, size, c); - else ARRAYS.unstableSort(elements, size); - } - -#else - public void sort(COMPARATOR c) { - if(c != null) ARRAYS.stableSort(elements, size, c); - else ARRAYS.stableSort(elements, size); - } - - public void unstableSort(COMPARATOR c) { - if(c != null) ARRAYS.unstableSort(elements, size, c); - else ARRAYS.unstableSort(elements, size); - } - -#endif - @Override - public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { - Objects.requireNonNull(action); - for(int i = 0;i void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { - Objects.requireNonNull(action); - for(int i = 0;i size() || size() == elements.length) return false; - int value = Math.max(size, size()); - elements = value == 0 ? EMPTY_KEY_ARRAY : Arrays.copyOf(elements, value); - return true; - } - - @Override - public void clearAndTrim(int size) { - if(elements.length <= size) { - clear(); - return; - } - elements = size == 0 ? EMPTY_KEY_ARRAY : NEW_KEY_ARRAY(size); - this.size = size; - } - - @Override - @Primitive - public Object[] toArray() { - Object[] obj = new Object[size]; - for(int i = 0;i E[] toArray(E[] a) { - if(a == null) a = (E[])new Object[size]; - else if(a.length < size) a = (E[])ObjectArrays.newArray(a.getClass().getComponentType(), size); - #if TYPE_OBJECT - System.arraycopy(elements, 0, a, 0, size); - #else - for(int i = 0;i size) a[size] = null; - return a; - } - -#if !TYPE_OBJECT - @Override - public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) { - if(a.length < size) a = new KEY_TYPE[size]; - System.arraycopy(elements, 0, a, 0, size); - if (a.length > size) a[size] = EMPTY_KEY_VALUE; - return a; - } -#endif - } - -#if !TYPE_BOOLEAN - protected static class DistinctCollectionWrapper KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION KEY_GENERIC_TYPE { - KEY_TYPE[] keys; - boolean containsNull; - int minCapacity; - int nullIndex; - int maxFill; - int mask; - int size; - - public DistinctCollectionWrapper() { - this(HashUtil.DEFAULT_MIN_CAPACITY); - } - - public DistinctCollectionWrapper(int size) { - if(minCapacity < 0) throw new IllegalStateException("Minimum Capacity is negative. This is not allowed"); - minCapacity = nullIndex = HashUtil.arraySize(minCapacity, HashUtil.DEFAULT_LOAD_FACTOR); - mask = nullIndex - 1; - maxFill = Math.min((int)Math.ceil(nullIndex * HashUtil.DEFAULT_LOAD_FACTOR), nullIndex - 1); - keys = NEW_KEY_ARRAY(nullIndex + 1); - } - - @Override - public boolean add(KEY_TYPE o) { - if(KEY_EQUALS_NULL(o)) { - if(containsNull) return false; - containsNull = true; - } - else { - int pos = HashUtil.mix(KEY_TO_HASH(o)) & mask; - KEY_TYPE current = keys[pos]; - if(KEY_EQUALS_NOT_NULL(current)) { - if(KEY_EQUALS(current, o)) return false; - while(KEY_EQUALS_NOT_NULL((current = keys[pos = (++pos & mask)]))) - if(KEY_EQUALS(current, o)) return false; - } - keys[pos] = o; - } - if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, HashUtil.DEFAULT_LOAD_FACTOR)); - return true; - } - - @Override - public boolean contains(Object o) { -#if TYPE_OBJECT - if(o == null) return containsNull; -#else - if(o == null) return false; - if(o instanceof CLASS_TYPE && KEY_EQUALS(CLASS_TO_KEY(o), EMPTY_KEY_VALUE)) return containsNull; -#endif - int pos = HashUtil.mix(o.hashCode()) & mask; - KEY_TYPE current = keys[pos]; - if(KEY_EQUALS_NULL(current)) return false; - if(EQUALS_KEY_TYPE(current, o)) return true; - while(true) { - if(KEY_EQUALS_NULL((current = keys[pos = (++pos & mask)]))) return false; - else if(EQUALS_KEY_TYPE(current, o)) return true; - } - } - - @Override - public boolean remove(Object o) { -#if TYPE_OBJECT - if(o == null) return (containsNull ? removeNullIndex() : false); -#else - if(o == null) return false; - if(o instanceof CLASS_TYPE && KEY_EQUALS(CLASS_TO_KEY(o), EMPTY_KEY_VALUE)) return (containsNull ? removeNullIndex() : false); -#endif - int pos = HashUtil.mix(o.hashCode()) & mask; - KEY_TYPE current = keys[pos]; - if(KEY_EQUALS_NULL(current)) return false; - if(EQUALS_KEY_TYPE(current, o)) return removeIndex(pos); - while(true) { - if(KEY_EQUALS_NULL((current = keys[pos = (++pos & mask)]))) return false; - else if(EQUALS_KEY_TYPE(current, o)) return removeIndex(pos); - } - } - -#if !TYPE_OBJECT - @Override - public boolean contains(KEY_TYPE o) { - if(KEY_EQUALS_NULL(o)) return containsNull; - int pos = HashUtil.mix(KEY_TO_HASH(o)) & mask; - KEY_TYPE current = keys[pos]; - if(KEY_EQUALS_NULL(current)) return false; - if(KEY_EQUALS(current, o)) return true; - while(true) { - if(KEY_EQUALS_NULL((current = keys[pos = (++pos & mask)]))) return false; - else if(KEY_EQUALS(current, o)) return true; - } - } - - @Override - public boolean REMOVE_KEY(KEY_TYPE o) { - if(KEY_EQUALS_NULL(o)) return containsNull ? removeNullIndex() : false; - int pos = HashUtil.mix(KEY_TO_HASH(o)) & mask; - KEY_TYPE current = keys[pos]; - if(KEY_EQUALS_NULL(current)) return false; - if(KEY_EQUALS(current, o)) return removeIndex(pos); - while(true) { - if(KEY_EQUALS_NULL((current = keys[pos = (++pos & mask)]))) return false; - else if(KEY_EQUALS(current, o)) return removeIndex(pos); - } - } - -#endif - protected boolean removeIndex(int pos) { - if(pos == nullIndex) return containsNull ? removeNullIndex() : false; - keys[pos] = EMPTY_KEY_VALUE; - size--; - shiftKeys(pos); - if(nullIndex > minCapacity && size < maxFill / 4 && nullIndex > HashUtil.DEFAULT_MIN_CAPACITY) rehash(nullIndex / 2); - return true; - } - - protected boolean removeNullIndex() { - containsNull = false; - keys[nullIndex] = EMPTY_KEY_VALUE; - size--; - if(nullIndex > minCapacity && size < maxFill / 4 && nullIndex > HashUtil.DEFAULT_MIN_CAPACITY) rehash(nullIndex / 2); - return true; - } - - @Override - public ITERATOR KEY_GENERIC_TYPE iterator() { - return new SetIterator(); - } - - @Override - public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { - if(size() <= 0) return; - if(containsNull) action.accept(keys[nullIndex]); - for(int i = nullIndex-1;i>=0;i--) { - if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(keys[i]); - } - } - - @Override - public DistinctCollectionWrapper KEY_GENERIC_TYPE copy() { - DistinctCollectionWrapper KEY_GENERIC_TYPE set = new DistinctCollectionWrapperBRACES(0); - set.minCapacity = minCapacity; - set.mask = mask; - set.maxFill = maxFill; - set.nullIndex = nullIndex; - set.containsNull = containsNull; - set.size = size; - set.keys = Arrays.copyOf(keys, keys.length); - return set; - } - - protected void shiftKeys(int startPos) { - int slot, last; - KEY_TYPE current; - while(true) { - startPos = ((last = startPos) + 1) & mask; - while(true){ - if(KEY_EQUALS_NULL((current = keys[startPos]))) { - keys[last] = EMPTY_KEY_VALUE; - return; - } - slot = HashUtil.mix(KEY_TO_HASH(current)) & mask; - if(last <= startPos ? (last >= slot || slot > startPos) : (last >= slot && slot > startPos)) break; - startPos = ++startPos & mask; - } - keys[last] = current; - } - } - - protected void rehash(int newSize) { - int newMask = newSize - 1; - KEY_TYPE[] newKeys = NEW_KEY_ARRAY(newSize + 1); - for(int i = nullIndex, pos = 0, j = (size - (containsNull ? 1 : 0));j-- != 0;) { - while(true) { - if(--i < 0) throw new ConcurrentModificationException("Set was modified during rehash"); - if(KEY_EQUALS_NOT_NULL(keys[i])) break; - } - if(KEY_EQUALS_NOT_NULL(newKeys[pos = HashUtil.mix(KEY_TO_HASH(keys[i])) & newMask])) - while(KEY_EQUALS_NOT_NULL(newKeys[pos = (++pos & newMask)])); - newKeys[pos] = keys[i]; - } - nullIndex = newSize; - mask = newMask; - maxFill = Math.min((int)Math.ceil(nullIndex * HashUtil.DEFAULT_LOAD_FACTOR), nullIndex - 1); - keys = newKeys; - } - - @Override - public void clear() { - if(size == 0) return; - size = 0; - containsNull = false; - Arrays.fill(keys, EMPTY_KEY_VALUE); - } - - @Override - public int size() { - return size; - } - - private class SetIterator implements ITERATOR KEY_GENERIC_TYPE { - int pos = nullIndex; - int returnedPos = -1; - int lastReturned = -1; - int nextIndex = Integer.MIN_VALUE; - boolean returnNull = containsNull; - KEY_TYPE[] wrapped = null; - int wrappedIndex = 0; - - @Override - public boolean hasNext() { - if(nextIndex == Integer.MIN_VALUE) { - if(returnNull) { - returnNull = false; - nextIndex = nullIndex; - } - else - { - while(true) { - if(--pos < 0) { - if(wrapped == null || wrappedIndex <= -pos - 1) break; - nextIndex = -pos - 1; - break; - } - if(KEY_EQUALS_NOT_NULL(keys[pos])){ - nextIndex = pos; - break; - } - } - } - } - return nextIndex != Integer.MIN_VALUE; - } - - @Override - public KEY_TYPE NEXT() { - if(!hasNext()) throw new NoSuchElementException(); - returnedPos = pos; - if(nextIndex < 0){ - lastReturned = Integer.MAX_VALUE; - KEY_TYPE value = wrapped[nextIndex]; - nextIndex = Integer.MIN_VALUE; - return value; - } - KEY_TYPE value = keys[(lastReturned = nextIndex)]; - nextIndex = Integer.MIN_VALUE; - return value; - } - - @Override - public void remove() { - if(lastReturned == -1) throw new IllegalStateException(); - if(lastReturned == nullIndex) { - containsNull = false; - keys[nullIndex] = EMPTY_KEY_VALUE; - } - else if(returnedPos >= 0) shiftKeys(returnedPos); - else { -#if TYPE_OBJECT - DistinctCollectionWrapper.this.remove(wrapped[-returnedPos - 1]); -#else - DistinctCollectionWrapper.this.REMOVE_KEY(wrapped[-returnedPos - 1]); -#endif - lastReturned = -1; - return; - } - size--; - lastReturned = -1; - } - - private void shiftKeys(int startPos) { - int slot, last; - KEY_TYPE current; - while(true) { - startPos = ((last = startPos) + 1) & mask; - while(true){ - if(KEY_EQUALS_NULL((current = keys[startPos]))) { - keys[last] = EMPTY_KEY_VALUE; - return; - } - slot = HashUtil.mix(KEY_TO_HASH(current)) & mask; - if(last <= startPos ? (last >= slot || slot > startPos) : (last >= slot && slot > startPos)) break; - startPos = ++startPos & mask; - } - if(startPos < last) addWrapper(keys[startPos]); - keys[last] = current; - } - } - - private void addWrapper(KEY_TYPE value) { - if(wrapped == null) wrapped = NEW_KEY_ARRAY(2); - else if(wrappedIndex >= wrapped.length) { - KEY_TYPE[] newArray = NEW_KEY_ARRAY(wrapped.length * 2); - System.arraycopy(wrapped, 0, newArray, 0, wrapped.length); - wrapped = newArray; - } - wrapped[wrappedIndex++] = value; - } - } - } - -#endif - private static class SingletonCollection KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION KEY_GENERIC_TYPE - { - KEY_TYPE element; - - SingletonCollection(KEY_TYPE element) { - this.element = element; - } - -#if !TYPE_OBJECT - @Override - public boolean REMOVE_KEY(KEY_TYPE o) { throw new UnsupportedOperationException(); } -#endif - @Override - public boolean add(KEY_TYPE o) { throw new UnsupportedOperationException(); } - @Override - public ITERATOR KEY_GENERIC_TYPE iterator() - { - return new ITERATOR KEY_GENERIC_TYPE() { - boolean next = true; - @Override - public boolean hasNext() { return next; } - @Override - public KEY_TYPE NEXT() { - if(!hasNext()) throw new NoSuchElementException(); - next = false; - return element; - } - }; - } - - @Override - public boolean equals(Object o) { - if (o == this) - return true; - if (!(o instanceof Collection)) - return false; - Collection l = (Collection)o; - if(l.size() != size()) return false; - Iterator iter = l.iterator(); - if (iter.hasNext() && !Objects.equals(element, iter.next())) { - return false; - } - return !iter.hasNext(); - } - - @Override - public int hashCode() { - return KEY_TO_HASH(element); - } - - @Override - public int size() { return 1; } - - @Override - public SingletonCollection KEY_GENERIC_TYPE copy() { return new SingletonCollectionBRACES(element); } - } - - /** - * Synchronized Collection Wrapper for the synchronizedCollection function - * @Type(T) - */ - public static class SynchronizedCollection KEY_GENERIC_TYPE implements COLLECTION KEY_GENERIC_TYPE { - COLLECTION KEY_GENERIC_TYPE c; - protected Object mutex; - - SynchronizedCollection(COLLECTION KEY_GENERIC_TYPE c) { - this.c = c; - mutex = this; - } - - SynchronizedCollection(COLLECTION KEY_GENERIC_TYPE c, Object mutex) { - this.c = c; - this.mutex = mutex; - } - - @Override - public boolean add(KEY_TYPE o) { synchronized(mutex) { return c.add(o); } } - @Override - public boolean addAll(Collection c) { synchronized(mutex) { return this.c.addAll(c); } } - @Override - public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) { synchronized(mutex) { return this.c.addAll(c); } } - @Override - public boolean addAll(KEY_TYPE[] e, int offset, int length) { synchronized(mutex) { return c.addAll(e, offset, length); } } -#if !TYPE_OBJECT - @Override - public boolean contains(KEY_TYPE o) { synchronized(mutex) { return c.contains(o); } } -#else - @Override - public boolean contains(Object o) { synchronized(mutex) { return c.contains(o); } } -#endif - @Override - @Primitive - public boolean containsAll(Collection c) { synchronized(mutex) { return this.c.containsAll(c); } } - - @Override - @Primitive - public boolean containsAny(Collection c) { synchronized(mutex) { return this.c.containsAny(c); } } - - @Override - public boolean containsAll(COLLECTION KEY_GENERIC_TYPE c) { synchronized(mutex) { return this.c.containsAll(c); } } - - @Override - public boolean containsAny(COLLECTION KEY_GENERIC_TYPE c) { synchronized(mutex) { return this.c.containsAny(c); } } - - @Override - public int size() { synchronized(mutex) { return c.size(); } } - - @Override - public boolean isEmpty() { synchronized(mutex) { return c.isEmpty(); } } - - @Override - public ITERATOR KEY_GENERIC_TYPE iterator() { - return c.iterator(); - } - - @Override - public COLLECTION KEY_GENERIC_TYPE copy() { synchronized(mutex) { return c.copy(); } } - - @Override - @Primitive - public boolean remove(Object o) { synchronized(mutex) { return c.remove(o); } } - @Override - @Primitive - public boolean removeAll(Collection c) { synchronized(mutex) { return this.c.removeAll(c); } } - @Override - @Primitive - public boolean retainAll(Collection c) { synchronized(mutex) { return this.c.retainAll(c); } } -#if !TYPE_OBJECT - @Override - public boolean REMOVE_KEY(KEY_TYPE o) { synchronized(mutex) { return c.REMOVE_KEY(o); } } -#endif - @Override - public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) { synchronized(mutex) { return this.c.removeAll(c); } } - @Override - public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { synchronized(mutex) { return this.c.removeAll(c, r); } } - @Override - public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) { synchronized(mutex) { return this.c.retainAll(c); } } - @Override - public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { synchronized(mutex) { return this.c.retainAll(c, r); } } -#if PRIMITIVES - @Override - public boolean remIf(JAVA_PREDICATE filter){ synchronized(mutex) { return c.remIf(filter); } } -#endif - @Override - public void clear() { synchronized(mutex) { c.clear(); } } - @Override - public Object[] toArray() { synchronized(mutex) { return c.toArray(); } } -#if !TYPE_OBJECT - @Override - public T[] toArray(T[] a) { synchronized(mutex) { return c.toArray(a); } } - @Override - public KEY_TYPE[] TO_ARRAY() { synchronized(mutex) { return c.TO_ARRAY(); } } - @Override - public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) { synchronized(mutex) { return c.TO_ARRAY(a); } } - @Override - public void forEach(CONSUMER action) { synchronized(mutex) { c.forEach(action); } } - @Override - @Deprecated - public void forEach(Consumer action) { synchronized(mutex) { c.forEach(action); } } -#else - @Override - public E[] toArray(E[] a) { synchronized(mutex) { return c.toArray(a); } } - @Override - public void forEach(Consumer action) { synchronized(mutex) { c.forEach(action); } } -#endif - @Override - public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) { synchronized(mutex) { c.forEachIndexed(action); } } - @Override - public int hashCode() { synchronized(mutex) { return c.hashCode(); } } - @Override - public boolean equals(Object obj) { - if(obj == this) return true; - synchronized(mutex) { return c.equals(obj); } - } - @Override - public String toString() { synchronized(mutex) { return c.toString(); } } - @Override - public void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { synchronized(mutex) { c.forEach(input, action); } } - @Override - public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { synchronized(mutex) { return c.matchesAny(filter); } } - @Override - public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { synchronized(mutex) { return c.matchesNone(filter); } } - @Override - public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { synchronized(mutex) { return c.matchesAll(filter); } } -#if TYPE_OBJECT - public KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) { synchronized(mutex) { return c.reduce(identity, operator); } } -#else - @Override - public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { synchronized(mutex) { return c.reduce(identity, operator); } } -#endif - @Override - public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { synchronized(mutex) { return c.reduce(operator); } } - @Override - public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { synchronized(mutex) { return c.findFirst(filter); } } - @Override - public int count(PREDICATE KEY_GENERIC_TYPE filter) { synchronized(mutex) { return c.count(filter); } } - } - - /** - * Unmodifyable Collection Wrapper for the unmodifyableCollection method - * @Type(T) - */ - public static class UnmodifiableCollection KEY_GENERIC_TYPE implements COLLECTION KEY_GENERIC_TYPE { - COLLECTION KEY_GENERIC_TYPE c; - - UnmodifiableCollection(COLLECTION KEY_GENERIC_TYPE c) { - this.c = c; - } - - @Override - public boolean add(KEY_TYPE o) { throw new UnsupportedOperationException(); } - @Override - public boolean addAll(Collection c) { throw new UnsupportedOperationException(); } - @Override - public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } - @Override - public boolean addAll(KEY_TYPE[] e, int offset, int length) { throw new UnsupportedOperationException(); } -#if !TYPE_OBJECT - @Override - public boolean contains(KEY_TYPE o) { return c.contains(o); } -#else - @Override - public boolean contains(Object o) { return c.contains(o); } -#endif - @Override - public boolean containsAll(COLLECTION KEY_GENERIC_TYPE c) { return this.c.containsAll(c); } - @Override - public boolean containsAny(COLLECTION KEY_GENERIC_TYPE c) { return this.c.containsAny(c); } - @Override - @Primitive - public boolean containsAny(Collection c) { return this.c.containsAny(c); } - @Override - @Primitive - public boolean containsAll(Collection c) { return this.c.containsAll(c); } - @Override - public int size() { return c.size(); } - @Override - public boolean isEmpty() { return c.isEmpty(); } - @Override - public ITERATOR KEY_GENERIC_TYPE iterator() { return ITERATORS.unmodifiable(c.iterator()); } - @Override - public COLLECTION KEY_GENERIC_TYPE copy() { return c.copy(); } - @Override - @Deprecated - public boolean remove(Object o) { throw new UnsupportedOperationException(); } - @Override - @Primitive - public boolean removeAll(Collection c) { throw new UnsupportedOperationException(); } - @Override - @Primitive - public boolean retainAll(Collection c) { throw new UnsupportedOperationException(); } - @Override - @Primitive - public boolean removeIf(Predicate filter) { throw new UnsupportedOperationException(); } -#if !TYPE_OBJECT - @Override - public boolean REMOVE_KEY(KEY_TYPE o) { throw new UnsupportedOperationException(); } -#endif - @Override - public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } - @Override - public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { throw new UnsupportedOperationException(); } - @Override - public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } - @Override - public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { throw new UnsupportedOperationException(); } -#if PRIMITIVES - @Override - public boolean remIf(JAVA_PREDICATE filter){ throw new UnsupportedOperationException(); } -#endif - @Override - public void clear() { throw new UnsupportedOperationException(); } - @Override - public Object[] toArray() { return c.toArray(); } -#if !TYPE_OBJECT - @Override - public T[] toArray(T[] a) { return c.toArray(a); } - @Override - public KEY_TYPE[] TO_ARRAY() { return c.TO_ARRAY(); } - @Override - public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) { return c.TO_ARRAY(a); } - @Override - public void forEach(CONSUMER action) { c.forEach(action); } - @Override - @Deprecated - public void forEach(Consumer action) { c.forEach(action); } -#else - @Override - public E[] toArray(E[] a) { return c.toArray(a); } - @Override - public void forEach(Consumer action) { c.forEach(action); } -#endif - @Override - public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) { c.forEachIndexed(action); } - @Override - public int hashCode() { return c.hashCode(); } - @Override - public boolean equals(Object obj) { return obj == this || c.equals(obj); } - @Override - public String toString() { return c.toString(); } - @Override - public void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { c.forEach(input, action); } - @Override - public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { return c.matchesAny(filter); } - @Override - public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { return c.matchesNone(filter); } - @Override - public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { return c.matchesAll(filter); } -#if TYPE_OBJECT - public KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) { return c.reduce(identity, operator); } -#else - @Override - public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { return c.reduce(identity, operator); } -#endif - @Override - public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { return c.reduce(operator); } - @Override - public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { return c.findFirst(filter); } - @Override - public int count(PREDICATE KEY_GENERIC_TYPE filter) { return c.count(filter); } - } - - /** - * Empty Collection implementation for the empty collection function - * @Type(T) - */ - public static class EmptyCollection KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION KEY_GENERIC_TYPE { - @Override - public boolean add(KEY_TYPE o) { throw new UnsupportedOperationException(); } - - @Override - public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } - @Override - public boolean addAll(KEY_TYPE[] e, int offset, int length) { throw new UnsupportedOperationException(); } - -#if !TYPE_OBJECT - @Override - public boolean contains(KEY_TYPE o) { return false; } - @Override - public boolean containsAll(COLLECTION KEY_GENERIC_TYPE c) { return c.isEmpty(); } - @Override - public boolean containsAny(COLLECTION KEY_GENERIC_TYPE c) { return false; } -#else - @Override - public boolean contains(Object o) { return false; } -#endif - @Override - @Primitive - public boolean containsAny(Collection c) { return false; } - @Override - @Primitive - public boolean containsAll(Collection c) { return c.isEmpty(); } - @Override - public int hashCode() { return 0; } - - @Override - public boolean equals(Object o) { - if(o == this) return true; - if(!(o instanceof Collection)) return false; - return ((Collection)o).isEmpty(); - } - - @Override - @Deprecated - public boolean remove(Object o) { throw new UnsupportedOperationException(); } - @Override - @Primitive - public boolean removeAll(Collection c) { throw new UnsupportedOperationException(); } - @Override - @Primitive - public boolean retainAll(Collection c) { throw new UnsupportedOperationException(); } - @Override - @Primitive - public boolean removeIf(Predicate filter) { throw new UnsupportedOperationException(); } -#if !TYPE_OBJECT - @Override - public boolean REMOVE_KEY(KEY_TYPE o) { throw new UnsupportedOperationException(); } -#endif - @Override - public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } - @Override - public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } -#if PRIMITIVES - @Override - public boolean remIf(JAVA_PREDICATE filter){ throw new UnsupportedOperationException(); } -#endif - @Override - public Object[] toArray() { return ObjectArrays.EMPTY_ARRAY; } -#if !TYPE_OBJECT - @Override - public T[] toArray(T[] a) { - if(a != null && a.length > 0) - a[0] = null; - return a; - } - - @Override - public KEY_TYPE[] TO_ARRAY() { return ARRAYS.EMPTY_ARRAY; } - @Override - public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) { - if(a != null && a.length > 0) - a[0] = EMPTY_KEY_VALUE; - return a; - } - -#else - @Override - public E[] toArray(E[] a) { - if(a != null && a.length > 0) - a[0] = EMPTY_KEY_VALUE; - return a; - } -#endif - @Override - public ITERATOR KEY_GENERIC_TYPE iterator() { return ITERATORS.empty(); } - @Override - public void clear() {} - @Override - public int size() { return 0; } - @Override - public EmptyCollection KEY_GENERIC_TYPE copy() { return this; } - } +package speiger.src.collections.PACKAGE.utils; + +import java.util.Arrays; +import java.util.Collection; +#if !TYPE_BOOLEAN +import java.util.ConcurrentModificationException; +#endif +import java.util.Iterator; +import java.util.NoSuchElementException; +import java.util.Objects; +#if TYPE_OBJECT +import java.util.Comparator; +import java.util.function.BiFunction; +#endif +import java.util.function.Predicate; +#if JDK_FUNCTION && !TYPE_OBJECT +import java.util.function.PREDICATE; +#endif +#if PRIMITIVES && !JDK_FUNCTION +import java.util.function.JAVA_PREDICATE; +#endif +import java.util.function.Consumer; + +import speiger.src.collections.PACKAGE.collections.ABSTRACT_COLLECTION; +import speiger.src.collections.PACKAGE.collections.COLLECTION; +import speiger.src.collections.PACKAGE.collections.ITERATOR; +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.functions.COMPARATOR; +#endif +#if !TYPE_OBJECT +import speiger.src.collections.objects.utils.ObjectArrays; +import speiger.src.collections.PACKAGE.functions.CONSUMER; +#endif +#if !JDK_FUNCTION +import speiger.src.collections.PACKAGE.functions.function.PREDICATE; +#endif +import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; +import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER; +import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; +#if !TYPE_BOOLEAN +import speiger.src.collections.utils.HashUtil; +#endif +import speiger.src.collections.utils.ITrimmable; +import speiger.src.collections.utils.SanityChecks; + +/** + * A Helper class for Collections + */ +public class COLLECTIONS +{ + /** + * Empty Collection Reference + */ + public static final COLLECTION NO_GENERIC_TYPE EMPTY = new EmptyCollectionBRACES(); + + /** + * Returns a Immutable EmptyCollection instance that is automatically casted. + * @Type(T) + * @return an empty collection + */ + public static GENERIC_KEY_BRACES COLLECTION KEY_GENERIC_TYPE empty() { +#if TYPE_OBJECT + return (COLLECTION)EMPTY; +#else + return EMPTY; +#endif + } + + /** + * Returns a Immutable Collection instance based on the instance given. + * @param c that should be made immutable/unmodifiable + * @Type(T) + * @return a unmodifiable collection wrapper. If the Collection already a unmodifiable wrapper then it just returns itself. + */ + public static GENERIC_KEY_BRACES COLLECTION KEY_GENERIC_TYPE unmodifiable(COLLECTION KEY_GENERIC_TYPE c) { + return c instanceof UnmodifiableCollection ? c : new UnmodifiableCollectionBRACES(c); + } + + /** + * Returns a synchronized Collection instance based on the instance given. + * @param c that should be synchronized + * @Type(T) + * @return a synchronized collection wrapper. If the Collection already a synchronized wrapper then it just returns itself. + */ + public static GENERIC_KEY_BRACES COLLECTION KEY_GENERIC_TYPE synchronize(COLLECTION KEY_GENERIC_TYPE c) { + return c instanceof SynchronizedCollection ? c : new SynchronizedCollectionBRACES(c); + } + + /** + * Returns a synchronized Collection instance based on the instance given. + * @param c that should be synchronized + * @param mutex is the controller of the synchronization block. + * @Type(T) + * @return a synchronized collection wrapper. If the Collection already a synchronized wrapper then it just returns itself. + */ + public static GENERIC_KEY_BRACES COLLECTION KEY_GENERIC_TYPE synchronize(COLLECTION KEY_GENERIC_TYPE c, Object mutex) { + return c instanceof SynchronizedCollection ? c : new SynchronizedCollectionBRACES(c, mutex); + } + + /** + * Creates a Singleton Collection of a given element + * @param element the element that should be converted into a singleton collection + * @Type(T) + * @return a singletoncollection of the given element + */ + public static GENERIC_KEY_BRACES COLLECTION KEY_GENERIC_TYPE singleton(KEY_TYPE element) { + return new SingletonCollectionBRACES(element); + } + + protected static GENERIC_KEY_BRACES CollectionWrapper KEY_GENERIC_TYPE wrapper() { + return new CollectionWrapperBRACES(); + } + + protected static GENERIC_KEY_BRACES CollectionWrapper KEY_GENERIC_TYPE wrapper(int size) { + return new CollectionWrapperBRACES(size); + } + +#if !TYPE_BOOLEAN + protected static GENERIC_KEY_BRACES DistinctCollectionWrapper KEY_GENERIC_TYPE distinctWrapper() { + return new DistinctCollectionWrapperBRACES(); + } + + protected static GENERIC_KEY_BRACES DistinctCollectionWrapper KEY_GENERIC_TYPE distinctWrapper(int size) { + return new DistinctCollectionWrapperBRACES(size); + } + +#endif + protected static class CollectionWrapper KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION KEY_GENERIC_TYPE implements ITrimmable { + KEY_TYPE[] elements; + int size = 0; + + public CollectionWrapper() { + this(10); + } + + public CollectionWrapper(int size) { + if(size < 0) throw new IllegalStateException("Size has to be 0 or greater"); + elements = NEW_KEY_ARRAY(size); + } + + @Override + public boolean add(KEY_TYPE o) { + if(size >= elements.length) elements = Arrays.copyOf(elements, (int)Math.min((long)elements.length + (elements.length >> 1), SanityChecks.MAX_ARRAY_SIZE)); + elements[size++] = o; + return true; + } + + public KEY_TYPE GET_KEY(int index) { + if(index < 0 || index >= size) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); + return elements[index]; + } + +#if TYPE_OBJECT + @Override + public boolean remove(Object e) { + for(int i = 0;i= size) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); + size--; + if(index != size) System.arraycopy(elements, index+1, elements, index, size - index); + } + + @Override + public ITERATOR KEY_GENERIC_TYPE iterator() { + return new ITERATOR KEY_GENERIC_TYPE() { + int index = 0; + int lastReturned = -1; + + @Override + public boolean hasNext() { + return index < size; + } + + @Override + public KEY_TYPE NEXT() { + int i = index++; + return elements[(lastReturned = i)]; + } + + @Override + public void remove() { + if(lastReturned == -1) throw new IllegalStateException(); + removeIndex(lastReturned); + index = lastReturned; + lastReturned = -1; + } + }; + } + + @Override + public int size() { + return size; + } + + @Override + public void clear() { +#if TYPE_OBJECT + for(int i = 0;i c) { + if(c != null) ARRAYS.stableSort(elements, size, c); + else ARRAYS.stableSort(elements, size); + } + + public void unstableSort(Comparator c) { + if(c != null) ARRAYS.unstableSort(elements, size, c); + else ARRAYS.unstableSort(elements, size); + } + +#else + public void sort(COMPARATOR c) { + if(c != null) ARRAYS.stableSort(elements, size, c); + else ARRAYS.stableSort(elements, size); + } + + public void unstableSort(COMPARATOR c) { + if(c != null) ARRAYS.unstableSort(elements, size, c); + else ARRAYS.unstableSort(elements, size); + } + +#endif + @Override + public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { + Objects.requireNonNull(action); + for(int i = 0;i void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { + Objects.requireNonNull(action); + for(int i = 0;i size() || size() == elements.length) return false; + int value = Math.max(size, size()); + elements = value == 0 ? EMPTY_KEY_ARRAY : Arrays.copyOf(elements, value); + return true; + } + + @Override + public void clearAndTrim(int size) { + if(elements.length <= size) { + clear(); + return; + } + elements = size == 0 ? EMPTY_KEY_ARRAY : NEW_KEY_ARRAY(size); + this.size = size; + } + + @Override + @Primitive + public Object[] toArray() { + Object[] obj = new Object[size]; + for(int i = 0;i E[] toArray(E[] a) { + if(a == null) a = (E[])new Object[size]; + else if(a.length < size) a = (E[])ObjectArrays.newArray(a.getClass().getComponentType(), size); + #if TYPE_OBJECT + System.arraycopy(elements, 0, a, 0, size); + #else + for(int i = 0;i size) a[size] = null; + return a; + } + +#if !TYPE_OBJECT + @Override + public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) { + if(a.length < size) a = new KEY_TYPE[size]; + System.arraycopy(elements, 0, a, 0, size); + if (a.length > size) a[size] = EMPTY_KEY_VALUE; + return a; + } +#endif + } + +#if !TYPE_BOOLEAN + protected static class DistinctCollectionWrapper KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION KEY_GENERIC_TYPE { + KEY_TYPE[] keys; + boolean containsNull; + int minCapacity; + int nullIndex; + int maxFill; + int mask; + int size; + + public DistinctCollectionWrapper() { + this(HashUtil.DEFAULT_MIN_CAPACITY); + } + + public DistinctCollectionWrapper(int size) { + if(minCapacity < 0) throw new IllegalStateException("Minimum Capacity is negative. This is not allowed"); + minCapacity = nullIndex = HashUtil.arraySize(minCapacity, HashUtil.DEFAULT_LOAD_FACTOR); + mask = nullIndex - 1; + maxFill = Math.min((int)Math.ceil(nullIndex * HashUtil.DEFAULT_LOAD_FACTOR), nullIndex - 1); + keys = NEW_KEY_ARRAY(nullIndex + 1); + } + + @Override + public boolean add(KEY_TYPE o) { + if(KEY_EQUALS_NULL(o)) { + if(containsNull) return false; + containsNull = true; + } + else { + int pos = HashUtil.mix(KEY_TO_HASH(o)) & mask; + KEY_TYPE current = keys[pos]; + if(KEY_EQUALS_NOT_NULL(current)) { + if(KEY_EQUALS(current, o)) return false; + while(KEY_EQUALS_NOT_NULL((current = keys[pos = (++pos & mask)]))) + if(KEY_EQUALS(current, o)) return false; + } + keys[pos] = o; + } + if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, HashUtil.DEFAULT_LOAD_FACTOR)); + return true; + } + + @Override + public boolean contains(Object o) { +#if TYPE_OBJECT + if(o == null) return containsNull; +#else + if(o == null) return false; + if(o instanceof CLASS_TYPE && KEY_EQUALS(CLASS_TO_KEY(o), EMPTY_KEY_VALUE)) return containsNull; +#endif + int pos = HashUtil.mix(o.hashCode()) & mask; + KEY_TYPE current = keys[pos]; + if(KEY_EQUALS_NULL(current)) return false; + if(EQUALS_KEY_TYPE(current, o)) return true; + while(true) { + if(KEY_EQUALS_NULL((current = keys[pos = (++pos & mask)]))) return false; + else if(EQUALS_KEY_TYPE(current, o)) return true; + } + } + + @Override + public boolean remove(Object o) { +#if TYPE_OBJECT + if(o == null) return (containsNull ? removeNullIndex() : false); +#else + if(o == null) return false; + if(o instanceof CLASS_TYPE && KEY_EQUALS(CLASS_TO_KEY(o), EMPTY_KEY_VALUE)) return (containsNull ? removeNullIndex() : false); +#endif + int pos = HashUtil.mix(o.hashCode()) & mask; + KEY_TYPE current = keys[pos]; + if(KEY_EQUALS_NULL(current)) return false; + if(EQUALS_KEY_TYPE(current, o)) return removeIndex(pos); + while(true) { + if(KEY_EQUALS_NULL((current = keys[pos = (++pos & mask)]))) return false; + else if(EQUALS_KEY_TYPE(current, o)) return removeIndex(pos); + } + } + +#if !TYPE_OBJECT + @Override + public boolean contains(KEY_TYPE o) { + if(KEY_EQUALS_NULL(o)) return containsNull; + int pos = HashUtil.mix(KEY_TO_HASH(o)) & mask; + KEY_TYPE current = keys[pos]; + if(KEY_EQUALS_NULL(current)) return false; + if(KEY_EQUALS(current, o)) return true; + while(true) { + if(KEY_EQUALS_NULL((current = keys[pos = (++pos & mask)]))) return false; + else if(KEY_EQUALS(current, o)) return true; + } + } + + @Override + public boolean REMOVE_KEY(KEY_TYPE o) { + if(KEY_EQUALS_NULL(o)) return containsNull ? removeNullIndex() : false; + int pos = HashUtil.mix(KEY_TO_HASH(o)) & mask; + KEY_TYPE current = keys[pos]; + if(KEY_EQUALS_NULL(current)) return false; + if(KEY_EQUALS(current, o)) return removeIndex(pos); + while(true) { + if(KEY_EQUALS_NULL((current = keys[pos = (++pos & mask)]))) return false; + else if(KEY_EQUALS(current, o)) return removeIndex(pos); + } + } + +#endif + protected boolean removeIndex(int pos) { + if(pos == nullIndex) return containsNull ? removeNullIndex() : false; + keys[pos] = EMPTY_KEY_VALUE; + size--; + shiftKeys(pos); + if(nullIndex > minCapacity && size < maxFill / 4 && nullIndex > HashUtil.DEFAULT_MIN_CAPACITY) rehash(nullIndex / 2); + return true; + } + + protected boolean removeNullIndex() { + containsNull = false; + keys[nullIndex] = EMPTY_KEY_VALUE; + size--; + if(nullIndex > minCapacity && size < maxFill / 4 && nullIndex > HashUtil.DEFAULT_MIN_CAPACITY) rehash(nullIndex / 2); + return true; + } + + @Override + public ITERATOR KEY_GENERIC_TYPE iterator() { + return new SetIterator(); + } + + @Override + public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { + if(size() <= 0) return; + if(containsNull) action.accept(keys[nullIndex]); + for(int i = nullIndex-1;i>=0;i--) { + if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(keys[i]); + } + } + + @Override + public DistinctCollectionWrapper KEY_GENERIC_TYPE copy() { + DistinctCollectionWrapper KEY_GENERIC_TYPE set = new DistinctCollectionWrapperBRACES(0); + set.minCapacity = minCapacity; + set.mask = mask; + set.maxFill = maxFill; + set.nullIndex = nullIndex; + set.containsNull = containsNull; + set.size = size; + set.keys = Arrays.copyOf(keys, keys.length); + return set; + } + + protected void shiftKeys(int startPos) { + int slot, last; + KEY_TYPE current; + while(true) { + startPos = ((last = startPos) + 1) & mask; + while(true){ + if(KEY_EQUALS_NULL((current = keys[startPos]))) { + keys[last] = EMPTY_KEY_VALUE; + return; + } + slot = HashUtil.mix(KEY_TO_HASH(current)) & mask; + if(last <= startPos ? (last >= slot || slot > startPos) : (last >= slot && slot > startPos)) break; + startPos = ++startPos & mask; + } + keys[last] = current; + } + } + + protected void rehash(int newSize) { + int newMask = newSize - 1; + KEY_TYPE[] newKeys = NEW_KEY_ARRAY(newSize + 1); + for(int i = nullIndex, pos = 0, j = (size - (containsNull ? 1 : 0));j-- != 0;) { + while(true) { + if(--i < 0) throw new ConcurrentModificationException("Set was modified during rehash"); + if(KEY_EQUALS_NOT_NULL(keys[i])) break; + } + if(KEY_EQUALS_NOT_NULL(newKeys[pos = HashUtil.mix(KEY_TO_HASH(keys[i])) & newMask])) + while(KEY_EQUALS_NOT_NULL(newKeys[pos = (++pos & newMask)])); + newKeys[pos] = keys[i]; + } + nullIndex = newSize; + mask = newMask; + maxFill = Math.min((int)Math.ceil(nullIndex * HashUtil.DEFAULT_LOAD_FACTOR), nullIndex - 1); + keys = newKeys; + } + + @Override + public void clear() { + if(size == 0) return; + size = 0; + containsNull = false; + Arrays.fill(keys, EMPTY_KEY_VALUE); + } + + @Override + public int size() { + return size; + } + + private class SetIterator implements ITERATOR KEY_GENERIC_TYPE { + int pos = nullIndex; + int returnedPos = -1; + int lastReturned = -1; + int nextIndex = Integer.MIN_VALUE; + boolean returnNull = containsNull; + KEY_TYPE[] wrapped = null; + int wrappedIndex = 0; + + @Override + public boolean hasNext() { + if(nextIndex == Integer.MIN_VALUE) { + if(returnNull) { + returnNull = false; + nextIndex = nullIndex; + } + else + { + while(true) { + if(--pos < 0) { + if(wrapped == null || wrappedIndex <= -pos - 1) break; + nextIndex = -pos - 1; + break; + } + if(KEY_EQUALS_NOT_NULL(keys[pos])){ + nextIndex = pos; + break; + } + } + } + } + return nextIndex != Integer.MIN_VALUE; + } + + @Override + public KEY_TYPE NEXT() { + if(!hasNext()) throw new NoSuchElementException(); + returnedPos = pos; + if(nextIndex < 0){ + lastReturned = Integer.MAX_VALUE; + KEY_TYPE value = wrapped[nextIndex]; + nextIndex = Integer.MIN_VALUE; + return value; + } + KEY_TYPE value = keys[(lastReturned = nextIndex)]; + nextIndex = Integer.MIN_VALUE; + return value; + } + + @Override + public void remove() { + if(lastReturned == -1) throw new IllegalStateException(); + if(lastReturned == nullIndex) { + containsNull = false; + keys[nullIndex] = EMPTY_KEY_VALUE; + } + else if(returnedPos >= 0) shiftKeys(returnedPos); + else { +#if TYPE_OBJECT + DistinctCollectionWrapper.this.remove(wrapped[-returnedPos - 1]); +#else + DistinctCollectionWrapper.this.REMOVE_KEY(wrapped[-returnedPos - 1]); +#endif + lastReturned = -1; + return; + } + size--; + lastReturned = -1; + } + + private void shiftKeys(int startPos) { + int slot, last; + KEY_TYPE current; + while(true) { + startPos = ((last = startPos) + 1) & mask; + while(true){ + if(KEY_EQUALS_NULL((current = keys[startPos]))) { + keys[last] = EMPTY_KEY_VALUE; + return; + } + slot = HashUtil.mix(KEY_TO_HASH(current)) & mask; + if(last <= startPos ? (last >= slot || slot > startPos) : (last >= slot && slot > startPos)) break; + startPos = ++startPos & mask; + } + if(startPos < last) addWrapper(keys[startPos]); + keys[last] = current; + } + } + + private void addWrapper(KEY_TYPE value) { + if(wrapped == null) wrapped = NEW_KEY_ARRAY(2); + else if(wrappedIndex >= wrapped.length) { + KEY_TYPE[] newArray = NEW_KEY_ARRAY(wrapped.length * 2); + System.arraycopy(wrapped, 0, newArray, 0, wrapped.length); + wrapped = newArray; + } + wrapped[wrappedIndex++] = value; + } + } + } + +#endif + private static class SingletonCollection KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION KEY_GENERIC_TYPE + { + KEY_TYPE element; + + SingletonCollection(KEY_TYPE element) { + this.element = element; + } + +#if !TYPE_OBJECT + @Override + public boolean REMOVE_KEY(KEY_TYPE o) { throw new UnsupportedOperationException(); } +#endif + @Override + public boolean add(KEY_TYPE o) { throw new UnsupportedOperationException(); } + @Override + public ITERATOR KEY_GENERIC_TYPE iterator() + { + return new ITERATOR KEY_GENERIC_TYPE() { + boolean next = true; + @Override + public boolean hasNext() { return next; } + @Override + public KEY_TYPE NEXT() { + if(!hasNext()) throw new NoSuchElementException(); + next = false; + return element; + } + }; + } + + @Override + public boolean equals(Object o) { + if (o == this) + return true; + if (!(o instanceof Collection)) + return false; + Collection l = (Collection)o; + if(l.size() != size()) return false; + Iterator iter = l.iterator(); + if (iter.hasNext() && !Objects.equals(element, iter.next())) { + return false; + } + return !iter.hasNext(); + } + + @Override + public int hashCode() { + return KEY_TO_HASH(element); + } + + @Override + public int size() { return 1; } + + @Override + public SingletonCollection KEY_GENERIC_TYPE copy() { return new SingletonCollectionBRACES(element); } + } + + /** + * Synchronized Collection Wrapper for the synchronizedCollection function + * @Type(T) + */ + public static class SynchronizedCollection KEY_GENERIC_TYPE implements COLLECTION KEY_GENERIC_TYPE { + COLLECTION KEY_GENERIC_TYPE c; + protected Object mutex; + + SynchronizedCollection(COLLECTION KEY_GENERIC_TYPE c) { + this.c = c; + mutex = this; + } + + SynchronizedCollection(COLLECTION KEY_GENERIC_TYPE c, Object mutex) { + this.c = c; + this.mutex = mutex; + } + + @Override + public boolean add(KEY_TYPE o) { synchronized(mutex) { return c.add(o); } } + @Override + public boolean addAll(Collection c) { synchronized(mutex) { return this.c.addAll(c); } } + @Override + public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) { synchronized(mutex) { return this.c.addAll(c); } } + @Override + public boolean addAll(KEY_TYPE[] e, int offset, int length) { synchronized(mutex) { return c.addAll(e, offset, length); } } +#if !TYPE_OBJECT + @Override + public boolean contains(KEY_TYPE o) { synchronized(mutex) { return c.contains(o); } } +#else + @Override + public boolean contains(Object o) { synchronized(mutex) { return c.contains(o); } } +#endif + @Override + @Primitive + public boolean containsAll(Collection c) { synchronized(mutex) { return this.c.containsAll(c); } } + + @Override + @Primitive + public boolean containsAny(Collection c) { synchronized(mutex) { return this.c.containsAny(c); } } + + @Override + public boolean containsAll(COLLECTION KEY_GENERIC_TYPE c) { synchronized(mutex) { return this.c.containsAll(c); } } + + @Override + public boolean containsAny(COLLECTION KEY_GENERIC_TYPE c) { synchronized(mutex) { return this.c.containsAny(c); } } + + @Override + public int size() { synchronized(mutex) { return c.size(); } } + + @Override + public boolean isEmpty() { synchronized(mutex) { return c.isEmpty(); } } + + @Override + public ITERATOR KEY_GENERIC_TYPE iterator() { + return c.iterator(); + } + + @Override + public COLLECTION KEY_GENERIC_TYPE copy() { synchronized(mutex) { return c.copy(); } } + + @Override + @Primitive + public boolean remove(Object o) { synchronized(mutex) { return c.remove(o); } } + @Override + @Primitive + public boolean removeAll(Collection c) { synchronized(mutex) { return this.c.removeAll(c); } } + @Override + @Primitive + public boolean retainAll(Collection c) { synchronized(mutex) { return this.c.retainAll(c); } } +#if !TYPE_OBJECT + @Override + public boolean REMOVE_KEY(KEY_TYPE o) { synchronized(mutex) { return c.REMOVE_KEY(o); } } +#endif + @Override + public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) { synchronized(mutex) { return this.c.removeAll(c); } } + @Override + public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { synchronized(mutex) { return this.c.removeAll(c, r); } } + @Override + public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) { synchronized(mutex) { return this.c.retainAll(c); } } + @Override + public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { synchronized(mutex) { return this.c.retainAll(c, r); } } +#if PRIMITIVES + @Override + public boolean remIf(JAVA_PREDICATE filter){ synchronized(mutex) { return c.remIf(filter); } } +#endif + @Override + public void clear() { synchronized(mutex) { c.clear(); } } + @Override + public Object[] toArray() { synchronized(mutex) { return c.toArray(); } } +#if !TYPE_OBJECT + @Override + public T[] toArray(T[] a) { synchronized(mutex) { return c.toArray(a); } } + @Override + public KEY_TYPE[] TO_ARRAY() { synchronized(mutex) { return c.TO_ARRAY(); } } + @Override + public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) { synchronized(mutex) { return c.TO_ARRAY(a); } } + @Override + public void forEach(CONSUMER action) { synchronized(mutex) { c.forEach(action); } } + @Override + @Deprecated + public void forEach(Consumer action) { synchronized(mutex) { c.forEach(action); } } +#else + @Override + public E[] toArray(E[] a) { synchronized(mutex) { return c.toArray(a); } } + @Override + public void forEach(Consumer action) { synchronized(mutex) { c.forEach(action); } } +#endif + @Override + public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) { synchronized(mutex) { c.forEachIndexed(action); } } + @Override + public int hashCode() { synchronized(mutex) { return c.hashCode(); } } + @Override + public boolean equals(Object obj) { + if(obj == this) return true; + synchronized(mutex) { return c.equals(obj); } + } + @Override + public String toString() { synchronized(mutex) { return c.toString(); } } + @Override + public void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { synchronized(mutex) { c.forEach(input, action); } } + @Override + public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { synchronized(mutex) { return c.matchesAny(filter); } } + @Override + public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { synchronized(mutex) { return c.matchesNone(filter); } } + @Override + public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { synchronized(mutex) { return c.matchesAll(filter); } } +#if TYPE_OBJECT + public KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) { synchronized(mutex) { return c.reduce(identity, operator); } } +#else + @Override + public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { synchronized(mutex) { return c.reduce(identity, operator); } } +#endif + @Override + public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { synchronized(mutex) { return c.reduce(operator); } } + @Override + public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { synchronized(mutex) { return c.findFirst(filter); } } + @Override + public int count(PREDICATE KEY_GENERIC_TYPE filter) { synchronized(mutex) { return c.count(filter); } } + } + + /** + * Unmodifyable Collection Wrapper for the unmodifyableCollection method + * @Type(T) + */ + public static class UnmodifiableCollection KEY_GENERIC_TYPE implements COLLECTION KEY_GENERIC_TYPE { + COLLECTION KEY_GENERIC_TYPE c; + + UnmodifiableCollection(COLLECTION KEY_GENERIC_TYPE c) { + this.c = c; + } + + @Override + public boolean add(KEY_TYPE o) { throw new UnsupportedOperationException(); } + @Override + public boolean addAll(Collection c) { throw new UnsupportedOperationException(); } + @Override + public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } + @Override + public boolean addAll(KEY_TYPE[] e, int offset, int length) { throw new UnsupportedOperationException(); } +#if !TYPE_OBJECT + @Override + public boolean contains(KEY_TYPE o) { return c.contains(o); } +#else + @Override + public boolean contains(Object o) { return c.contains(o); } +#endif + @Override + public boolean containsAll(COLLECTION KEY_GENERIC_TYPE c) { return this.c.containsAll(c); } + @Override + public boolean containsAny(COLLECTION KEY_GENERIC_TYPE c) { return this.c.containsAny(c); } + @Override + @Primitive + public boolean containsAny(Collection c) { return this.c.containsAny(c); } + @Override + @Primitive + public boolean containsAll(Collection c) { return this.c.containsAll(c); } + @Override + public int size() { return c.size(); } + @Override + public boolean isEmpty() { return c.isEmpty(); } + @Override + public ITERATOR KEY_GENERIC_TYPE iterator() { return ITERATORS.unmodifiable(c.iterator()); } + @Override + public COLLECTION KEY_GENERIC_TYPE copy() { return c.copy(); } + @Override + @Deprecated + public boolean remove(Object o) { throw new UnsupportedOperationException(); } + @Override + @Primitive + public boolean removeAll(Collection c) { throw new UnsupportedOperationException(); } + @Override + @Primitive + public boolean retainAll(Collection c) { throw new UnsupportedOperationException(); } + @Override + @Primitive + public boolean removeIf(Predicate filter) { throw new UnsupportedOperationException(); } +#if !TYPE_OBJECT + @Override + public boolean REMOVE_KEY(KEY_TYPE o) { throw new UnsupportedOperationException(); } +#endif + @Override + public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } + @Override + public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { throw new UnsupportedOperationException(); } + @Override + public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } + @Override + public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { throw new UnsupportedOperationException(); } +#if PRIMITIVES + @Override + public boolean remIf(JAVA_PREDICATE filter){ throw new UnsupportedOperationException(); } +#endif + @Override + public void clear() { throw new UnsupportedOperationException(); } + @Override + public Object[] toArray() { return c.toArray(); } +#if !TYPE_OBJECT + @Override + public T[] toArray(T[] a) { return c.toArray(a); } + @Override + public KEY_TYPE[] TO_ARRAY() { return c.TO_ARRAY(); } + @Override + public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) { return c.TO_ARRAY(a); } + @Override + public void forEach(CONSUMER action) { c.forEach(action); } + @Override + @Deprecated + public void forEach(Consumer action) { c.forEach(action); } +#else + @Override + public E[] toArray(E[] a) { return c.toArray(a); } + @Override + public void forEach(Consumer action) { c.forEach(action); } +#endif + @Override + public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) { c.forEachIndexed(action); } + @Override + public int hashCode() { return c.hashCode(); } + @Override + public boolean equals(Object obj) { return obj == this || c.equals(obj); } + @Override + public String toString() { return c.toString(); } + @Override + public void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE action) { c.forEach(input, action); } + @Override + public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { return c.matchesAny(filter); } + @Override + public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { return c.matchesNone(filter); } + @Override + public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { return c.matchesAll(filter); } +#if TYPE_OBJECT + public KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction operator) { return c.reduce(identity, operator); } +#else + @Override + public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { return c.reduce(identity, operator); } +#endif + @Override + public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { return c.reduce(operator); } + @Override + public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { return c.findFirst(filter); } + @Override + public int count(PREDICATE KEY_GENERIC_TYPE filter) { return c.count(filter); } + } + + /** + * Empty Collection implementation for the empty collection function + * @Type(T) + */ + public static class EmptyCollection KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION KEY_GENERIC_TYPE { + @Override + public boolean add(KEY_TYPE o) { throw new UnsupportedOperationException(); } + + @Override + public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } + @Override + public boolean addAll(KEY_TYPE[] e, int offset, int length) { throw new UnsupportedOperationException(); } + +#if !TYPE_OBJECT + @Override + public boolean contains(KEY_TYPE o) { return false; } + @Override + public boolean containsAll(COLLECTION KEY_GENERIC_TYPE c) { return c.isEmpty(); } + @Override + public boolean containsAny(COLLECTION KEY_GENERIC_TYPE c) { return false; } +#else + @Override + public boolean contains(Object o) { return false; } +#endif + @Override + @Primitive + public boolean containsAny(Collection c) { return false; } + @Override + @Primitive + public boolean containsAll(Collection c) { return c.isEmpty(); } + @Override + public int hashCode() { return 0; } + + @Override + public boolean equals(Object o) { + if(o == this) return true; + if(!(o instanceof Collection)) return false; + return ((Collection)o).isEmpty(); + } + + @Override + @Deprecated + public boolean remove(Object o) { throw new UnsupportedOperationException(); } + @Override + @Primitive + public boolean removeAll(Collection c) { throw new UnsupportedOperationException(); } + @Override + @Primitive + public boolean retainAll(Collection c) { throw new UnsupportedOperationException(); } + @Override + @Primitive + public boolean removeIf(Predicate filter) { throw new UnsupportedOperationException(); } +#if !TYPE_OBJECT + @Override + public boolean REMOVE_KEY(KEY_TYPE o) { throw new UnsupportedOperationException(); } +#endif + @Override + public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } + @Override + public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } +#if PRIMITIVES + @Override + public boolean remIf(JAVA_PREDICATE filter){ throw new UnsupportedOperationException(); } +#endif + @Override + public Object[] toArray() { return ObjectArrays.EMPTY_ARRAY; } +#if !TYPE_OBJECT + @Override + public T[] toArray(T[] a) { + if(a != null && a.length > 0) + a[0] = null; + return a; + } + + @Override + public KEY_TYPE[] TO_ARRAY() { return ARRAYS.EMPTY_ARRAY; } + @Override + public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) { + if(a != null && a.length > 0) + a[0] = EMPTY_KEY_VALUE; + return a; + } + +#else + @Override + public E[] toArray(E[] a) { + if(a != null && a.length > 0) + a[0] = EMPTY_KEY_VALUE; + return a; + } +#endif + @Override + public ITERATOR KEY_GENERIC_TYPE iterator() { return ITERATORS.empty(); } + @Override + public void clear() {} + @Override + public int size() { return 0; } + @Override + public EmptyCollection KEY_GENERIC_TYPE copy() { return this; } + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/collections/templates/utils/Iterables.template b/src/builder/resources/speiger/assets/collections/templates/utils/Iterables.template index 84f4aee..54f4592 100644 --- a/src/builder/resources/speiger/assets/collections/templates/utils/Iterables.template +++ b/src/builder/resources/speiger/assets/collections/templates/utils/Iterables.template @@ -1,588 +1,588 @@ -package speiger.src.collections.PACKAGE.utils; - -import java.util.Objects; -#if TYPE_BOOLEAN -import java.util.concurrent.atomic.AtomicInteger; -#else if TYPE_OBJECT -import java.util.Comparator; -#endif -import java.util.concurrent.atomic.AtomicLong; -import java.util.function.Consumer; -#if JDK_FUNCTION -import java.util.function.PREDICATE; -#endif - -import speiger.src.collections.PACKAGE.collections.ITERABLE; -import speiger.src.collections.PACKAGE.collections.COLLECTION; -#if !TYPE_OBJECT -import speiger.src.collections.objects.collections.ObjectIterable; -import speiger.src.collections.objects.collections.ObjectIterator; -import speiger.src.collections.PACKAGE.functions.CONSUMER; -import speiger.src.collections.PACKAGE.functions.COMPARATOR; -#endif -import speiger.src.collections.PACKAGE.collections.ITERATOR; -import speiger.src.collections.PACKAGE.functions.function.TO_OBJECT_FUNCTION; -#if !JDK_FUNCTION -import speiger.src.collections.PACKAGE.functions.function.PREDICATE; -#endif -import speiger.src.collections.utils.ISizeProvider; - -/** - * A Helper class for Iterables - */ -public class ITERABLES -{ - /** - * A Helper function that maps a Java-Iterable into a new Type. - * @param iterable the iterable that should be mapped - * @param mapper the function that decides what the result turns into. - * @Type(T) - * @param The return type. - * @return a iterable that is mapped to a new result - */ - public static GENERIC_KEY_SPECIAL_BRACES ObjectIterable map(Iterable iterable, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { - return new MappedIterable<>(wrap(iterable), mapper); - } - - /** - * A Helper function that maps a Iterable into a new Type. - * @param iterable the iterable that should be mapped - * @param mapper the function that decides what the result turns into. - * @Type(T) - * @param The return type. - * @return a iterable that is mapped to a new result - */ - public static GENERIC_KEY_SPECIAL_BRACES ObjectIterable map(ITERABLE KEY_GENERIC_TYPE iterable, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { - return new MappedIterable<>(iterable, mapper); - } - - /** - * A Helper function that flatMaps a Java-Iterable into a new Type. - * @param iterable the iterable that should be flatMapped - * @param mapper the function that decides what the result turns into. - * @Type(T) - * @param The return type supplier. - * @param The return type. - * @return a iterable that is flatMapped to a new result - */ - public static GENERIC_KEY_SPECIAL_BRACES> ObjectIterable flatMap(Iterable iterable, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { - return new FlatMappedIterable<>(wrap(iterable), mapper); - } - - /** - * A Helper function that flatMaps a Iterable into a new Type. - * @param iterable the iterable that should be flatMapped - * @param mapper the function that decides what the result turns into. - * @Type(T) - * @param The return type supplier. - * @param The return type. - * @return a iterable that is flatMapped to a new result - */ - public static GENERIC_KEY_SPECIAL_BRACES> ObjectIterable flatMap(ITERABLE KEY_GENERIC_TYPE iterable, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { - return new FlatMappedIterable<>(iterable, mapper); - } - - /** - * A Helper function that flatMaps a Java-Iterable into a new Type. - * @param iterable the iterable that should be flatMapped - * @param mapper the function that decides what the result turns into. - * @Type(T) - * @param The return type. - * @return a iterable that is flatMapped to a new result - */ - public static GENERIC_KEY_SPECIAL_BRACES ObjectIterable arrayFlatMap(Iterable iterable, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { - return new FlatMappedArrayIterable<>(wrap(iterable), mapper); - } - - /** - * A Helper function that flatMaps a Iterable into a new Type. - * @param iterable the iterable that should be flatMapped - * @param mapper the function that decides what the result turns into. - * @Type(T) - * @param The return type. - * @return a iterable that is flatMapped to a new result - */ - public static GENERIC_KEY_SPECIAL_BRACES ObjectIterable arrayFlatMap(ITERABLE KEY_GENERIC_TYPE iterable, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { - return new FlatMappedArrayIterable<>(iterable, mapper); - } - - /** - * A Helper function that filters out all desired elements from a Java-Iterable - * @param iterable that should be filtered. - * @param filter the filter that decides that should be let through - * @Type(T) - * @return a filtered iterable - */ - public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE filter(Iterable iterable, PREDICATE KEY_GENERIC_TYPE filter) { - return new FilteredIterableBRACES(wrap(iterable), filter); - } - - /** - * A Helper function that filters out all desired elements - * @param iterable that should be filtered. - * @param filter the filter that decides that should be let through - * @Type(T) - * @return a filtered iterable - */ - public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE filter(ITERABLE KEY_GENERIC_TYPE iterable, PREDICATE KEY_GENERIC_TYPE filter) { - return new FilteredIterableBRACES(iterable, filter); - } - - /** - * A Helper function that filters out all duplicated elements. - * @param iterable that should be distinct - * @Type(T) - * @return a distinct iterable - */ - public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE distinct(ITERABLE KEY_GENERIC_TYPE iterable) { - return new DistinctIterableBRACES(iterable); - } - - /** - * A Helper function that filters out all duplicated elements from a Java Iterable. - * @param iterable that should be distinct - * @Type(T) - * @return a distinct iterable - */ - public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE distinct(Iterable iterable) { - return new DistinctIterableBRACES(wrap(iterable)); - } - - /** - * A Helper function that repeats the Iterable a specific amount of times - * @param iterable that should be repeated - * @param repeats the amount of times the iterable should be repeated - * @Type(T) - * @return a repeating iterable - */ - public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE repeat(ITERABLE KEY_GENERIC_TYPE iterable, int repeats) { - return new RepeatingIterableBRACES(iterable, repeats); - } - - /** - * A Helper function that repeats the Iterable a specific amount of times from a Java Iterable - * @param iterable that should be repeated - * @param repeats the amount of times the iterable should be repeated - * @Type(T) - * @return a repeating iterable - */ - public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE repeat(Iterable iterable, int repeats) { - return new RepeatingIterableBRACES(wrap(iterable), repeats); - } - - /** - * A Helper function that hard limits the Iterable to a specific size - * @param iterable that should be limited - * @param limit the amount of elements it should be limited to - * @Type(T) - * @return a limited iterable - */ - public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE limit(ITERABLE KEY_GENERIC_TYPE iterable, long limit) { - return new LimitedIterableBRACES(iterable, limit); - } - - /** - * A Helper function that hard limits the Iterable to a specific size from a Java Iterable - * @param iterable that should be limited - * @param limit the amount of elements it should be limited to - * @Type(T) - * @return a limited iterable - */ - public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE limit(Iterable iterable, long limit) { - return new LimitedIterableBRACES(wrap(iterable), limit); - } - - /** - * A Helper function that sorts the Iterable. - * This operation is heavily hurting performance because it rebuilds the entire iterator and then sorts it. - * @param iterable that should be sorted - * @param sorter that sorts the iterable. Can be null. - * @Type(T) - * @return a sorted iterable. - */ - public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE sorted(ITERABLE KEY_GENERIC_TYPE iterable, COMPARATOR KEY_GENERIC_TYPE sorter) { - return new SortedIterableBRACES(iterable, sorter); - } - - /** - * A Helper function that sorts the Iterable from a Java Iterable - * This operation is heavily hurting performance because it rebuilds the entire iterator and then sorts it. - * @param iterable that should be sorted - * @param sorter that sorts the iterable. Can be null. - * @Type(T) - * @return a sorted iterable. - */ - public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE sorted(Iterable iterable, COMPARATOR KEY_GENERIC_TYPE sorter) { - return new SortedIterableBRACES(wrap(iterable), sorter); - } - - /** - * A Helper function that allows to preview the result of a Iterable. - * @param iterable that should be peeked at - * @param action callback that receives the value before the iterable returns it - * @Type(T) - * @return a peeked iterable - */ - public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE peek(ITERABLE KEY_GENERIC_TYPE iterable, CONSUMER KEY_GENERIC_TYPE action) { - return new PeekIterableBRACES(iterable, action); - } - - /** - * A Helper function that allows to preview the result of a Iterable from a Java Iterable - * @param iterable that should be peeked at - * @param action callback that receives the value before the iterable returns it - * @Type(T) - * @return a peeked iterable - */ - public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE peek(Iterable iterable, CONSUMER KEY_GENERIC_TYPE action) { - return new PeekIterableBRACES(wrap(iterable), action); - } - - /** - * A Wrapper function that wraps a Java-Iterable into a Type Specific Iterable - * @param iterable that should be wrapped - * @Type(T) - * @return a type specific iterable - */ - public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE wrap(Iterable iterable) { - return new WrappedIterableBRACES(iterable); - } - - private static class WrappedIterable KEY_GENERIC_TYPE implements ITERABLE KEY_GENERIC_TYPE, ISizeProvider - { - Iterable iterable; - - public WrappedIterable(Iterable iterable) { - this.iterable = iterable; - } - - public ITERATOR KEY_GENERIC_TYPE iterator() { - return ITERATORS.wrap(iterable.iterator()); - } - - @Override - public int size() { - ISizeProvider prov = ISizeProvider.of(iterable); - return prov == null ? -1 : prov.size(); - } - -#if !TYPE_OBJECT - @Override - public void forEach(CONSUMER action) { - Objects.requireNonNull(action); - iterable.forEach(action); - } -#else - public void forEach(Consumer action) { - Objects.requireNonNull(action); - iterable.forEach(action); - } -#endif - } - - private static class MappedIterable KSS_GENERIC_TYPE implements ObjectIterable, ISizeProvider - { - ITERABLE KEY_SPECIAL_GENERIC_TYPE iterable; - TO_OBJECT_FUNCTION KSS_GENERIC_TYPE mapper; - - MappedIterable(ITERABLE KEY_SPECIAL_GENERIC_TYPE iterable, TO_OBJECT_FUNCTION KSS_GENERIC_TYPE mapper) { - this.iterable = iterable; - this.mapper = mapper; - } - - public ObjectIterator iterator() { - return ITERATORS.map(iterable.iterator(), mapper); - } - - @Override - public int size() { - ISizeProvider prov = ISizeProvider.of(this); - return prov == null ? -1 : prov.size(); - } - - @Override - public void forEach(Consumer action) { - Objects.requireNonNull(action); - iterable.forEach(E -> action.accept(mapper.apply(E))); - } - } - - private static class FlatMappedIterable KSS_GENERIC_TYPE> implements ObjectIterable - { - ITERABLE KEY_SPECIAL_GENERIC_TYPE iterable; - TO_OBJECT_FUNCTION KSS_GENERIC_TYPE mapper; - - FlatMappedIterable(ITERABLE KEY_SPECIAL_GENERIC_TYPE iterable, TO_OBJECT_FUNCTION KSS_GENERIC_TYPE mapper) { - this.iterable = iterable; - this.mapper = mapper; - } - - @Override - public ObjectIterator iterator() { - return ITERATORS.flatMap(iterable.iterator(), mapper); - } - - @Override - public void forEach(Consumer action) { - Objects.requireNonNull(action); - iterable.forEach(E -> mapper.apply(E).forEach(action)); - } - - } - - private static class FlatMappedArrayIterable KSS_GENERIC_TYPE implements ObjectIterable - { - ITERABLE KEY_SPECIAL_GENERIC_TYPE iterable; - TO_OBJECT_FUNCTION KSS_GENERIC_TYPE mapper; - - FlatMappedArrayIterable(ITERABLE KEY_SPECIAL_GENERIC_TYPE iterable, TO_OBJECT_FUNCTION KSS_GENERIC_TYPE mapper) { - this.iterable = iterable; - this.mapper = mapper; - } - - @Override - public ObjectIterator iterator() { - return ITERATORS.arrayFlatMap(iterable.iterator(), mapper); - } - - @Override - public void forEach(Consumer action) { - Objects.requireNonNull(action); - iterable.forEach(E -> { - T[] array = mapper.apply(E); - for(int i = 0,m=array.length;i action) { - Objects.requireNonNull(action); - COLLECTION KEY_GENERIC_TYPE repeater = COLLECTIONS.wrapper(); - iterable.forEach(T -> {action.accept(T); repeater.add(T);}); - for(int i = 0;i { if(!filter.test(T)) action.accept(T); } ); - } -#else - public void forEach(Consumer action) { - Objects.requireNonNull(action); - iterable.forEach(T -> { if(!filter.test(T)) action.accept(T); } ); - } -#endif - } - - private static class LimitedIterable KEY_GENERIC_TYPE implements ITERABLE KEY_GENERIC_TYPE, ISizeProvider - { - ITERABLE KEY_GENERIC_TYPE iterable; - long limit; - - public LimitedIterable(ITERABLE KEY_GENERIC_TYPE iterable, long limit) { - this.iterable = iterable; - this.limit = limit; - } - - @Override - public ITERATOR KEY_GENERIC_TYPE iterator() { - return ITERATORS.limit(iterable.iterator(), limit); - } - - @Override - public int size() { - ISizeProvider prov = ISizeProvider.of(iterable); - return prov == null ? -1 : (int)Math.min(prov.size(), limit); - } - -#if !TYPE_OBJECT - @Override - public void forEach(CONSUMER action) { - Objects.requireNonNull(action); - AtomicLong counter = new AtomicLong(); - iterable.forEach(T -> { - if(counter.get() >= limit) return; - counter.incrementAndGet(); - action.accept(T); - }); - } -#else - public void forEach(Consumer action) { - Objects.requireNonNull(action); - AtomicLong counter = new AtomicLong(); - iterable.forEach(T -> { - if(counter.get() >= limit) return; - counter.incrementAndGet(); - action.accept(T); - }); - } -#endif - } - - private static class SortedIterable KEY_GENERIC_TYPE implements ITERABLE KEY_GENERIC_TYPE, ISizeProvider - { - ITERABLE KEY_GENERIC_TYPE iterable; - COMPARATOR KEY_GENERIC_TYPE sorter; - - public SortedIterable(ITERABLE KEY_GENERIC_TYPE iterable, COMPARATOR KEY_GENERIC_TYPE sorter) { - this.iterable = iterable; - this.sorter = sorter; - } - - @Override - public ITERATOR KEY_GENERIC_TYPE iterator() { - return ITERATORS.sorted(iterable.iterator(), sorter); - } - - @Override - public int size() { - ISizeProvider prov = ISizeProvider.of(iterable); - return prov == null ? -1 : prov.size(); - } - -#if !TYPE_OBJECT - @Override - public void forEach(CONSUMER action) { - Objects.requireNonNull(action); - COLLECTIONS.CollectionWrapper KEY_GENERIC_TYPE wrapper = COLLECTIONS.wrapper(); - iterable.forEach(wrapper::add); - wrapper.unstableSort(sorter); - wrapper.forEach(action); - } -#else - @Override - public void forEach(Consumer action) { - Objects.requireNonNull(action); - COLLECTIONS.CollectionWrapper KEY_GENERIC_TYPE wrapper = COLLECTIONS.wrapper(); - iterable.forEach(wrapper::add); - wrapper.unstableSort(sorter); - wrapper.forEach(action); - } -#endif - } - - private static class DistinctIterable KEY_GENERIC_TYPE implements ITERABLE KEY_GENERIC_TYPE - { - ITERABLE KEY_GENERIC_TYPE iterable; - - public DistinctIterable(ITERABLE KEY_GENERIC_TYPE iterable) { - this.iterable = iterable; - } - - @Override - public ITERATOR KEY_GENERIC_TYPE iterator() { - return ITERATORS.distinct(iterable.iterator()); - } - -#if !TYPE_OBJECT - @Override - public void forEach(CONSUMER action) { - Objects.requireNonNull(action); -#if TYPE_BOOLEAN - AtomicInteger result = new AtomicInteger(); - iterable.forEach(T -> { - if(((result.get() & (T ? 2 : 1)) != 0)) return; - result.getAndAdd(T ? 2 : 1); - action.accept(T); - }); -#else - COLLECTION KEY_GENERIC_TYPE filtered = COLLECTIONS.distinctWrapper(); - iterable.forEach(T -> { if(filtered.add(T)) action.accept(T); }); -#endif - } -#else - public void forEach(Consumer action) { - Objects.requireNonNull(action); - COLLECTION KEY_GENERIC_TYPE filtered = COLLECTIONS.distinctWrapper(); - iterable.forEach(T -> { if(filtered.add(T)) action.accept(T); }); - } -#endif - } - - private static class PeekIterable KEY_GENERIC_TYPE implements ITERABLE KEY_GENERIC_TYPE, ISizeProvider - { - ITERABLE KEY_GENERIC_TYPE iterable; - CONSUMER KEY_GENERIC_TYPE action; - - public PeekIterable(ITERABLE KEY_GENERIC_TYPE iterable, CONSUMER KEY_GENERIC_TYPE action) { - this.iterable = iterable; - this.action = action; - } - - @Override - public ITERATOR KEY_GENERIC_TYPE iterator() { - return ITERATORS.peek(iterable.iterator(), action); - } - - @Override - public int size() { - ISizeProvider prov = ISizeProvider.of(iterable); - return prov == null ? -1 : prov.size(); - } - -#if !TYPE_OBJECT - @Override - public void forEach(CONSUMER action) { - Objects.requireNonNull(action); - iterable.forEach(this.action.andThen(action)); - } -#else - public void forEach(Consumer action) { - Objects.requireNonNull(action); - iterable.forEach(this.action.andThen(action)); - } -#endif - } +package speiger.src.collections.PACKAGE.utils; + +import java.util.Objects; +#if TYPE_BOOLEAN +import java.util.concurrent.atomic.AtomicInteger; +#else if TYPE_OBJECT +import java.util.Comparator; +#endif +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Consumer; +#if JDK_FUNCTION +import java.util.function.PREDICATE; +#endif + +import speiger.src.collections.PACKAGE.collections.ITERABLE; +import speiger.src.collections.PACKAGE.collections.COLLECTION; +#if !TYPE_OBJECT +import speiger.src.collections.objects.collections.ObjectIterable; +import speiger.src.collections.objects.collections.ObjectIterator; +import speiger.src.collections.PACKAGE.functions.CONSUMER; +import speiger.src.collections.PACKAGE.functions.COMPARATOR; +#endif +import speiger.src.collections.PACKAGE.collections.ITERATOR; +import speiger.src.collections.PACKAGE.functions.function.TO_OBJECT_FUNCTION; +#if !JDK_FUNCTION +import speiger.src.collections.PACKAGE.functions.function.PREDICATE; +#endif +import speiger.src.collections.utils.ISizeProvider; + +/** + * A Helper class for Iterables + */ +public class ITERABLES +{ + /** + * A Helper function that maps a Java-Iterable into a new Type. + * @param iterable the iterable that should be mapped + * @param mapper the function that decides what the result turns into. + * @Type(T) + * @param The return type. + * @return a iterable that is mapped to a new result + */ + public static GENERIC_KEY_SPECIAL_BRACES ObjectIterable map(Iterable iterable, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { + return new MappedIterable<>(wrap(iterable), mapper); + } + + /** + * A Helper function that maps a Iterable into a new Type. + * @param iterable the iterable that should be mapped + * @param mapper the function that decides what the result turns into. + * @Type(T) + * @param The return type. + * @return a iterable that is mapped to a new result + */ + public static GENERIC_KEY_SPECIAL_BRACES ObjectIterable map(ITERABLE KEY_GENERIC_TYPE iterable, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { + return new MappedIterable<>(iterable, mapper); + } + + /** + * A Helper function that flatMaps a Java-Iterable into a new Type. + * @param iterable the iterable that should be flatMapped + * @param mapper the function that decides what the result turns into. + * @Type(T) + * @param The return type supplier. + * @param The return type. + * @return a iterable that is flatMapped to a new result + */ + public static GENERIC_KEY_SPECIAL_BRACES> ObjectIterable flatMap(Iterable iterable, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { + return new FlatMappedIterable<>(wrap(iterable), mapper); + } + + /** + * A Helper function that flatMaps a Iterable into a new Type. + * @param iterable the iterable that should be flatMapped + * @param mapper the function that decides what the result turns into. + * @Type(T) + * @param The return type supplier. + * @param The return type. + * @return a iterable that is flatMapped to a new result + */ + public static GENERIC_KEY_SPECIAL_BRACES> ObjectIterable flatMap(ITERABLE KEY_GENERIC_TYPE iterable, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { + return new FlatMappedIterable<>(iterable, mapper); + } + + /** + * A Helper function that flatMaps a Java-Iterable into a new Type. + * @param iterable the iterable that should be flatMapped + * @param mapper the function that decides what the result turns into. + * @Type(T) + * @param The return type. + * @return a iterable that is flatMapped to a new result + */ + public static GENERIC_KEY_SPECIAL_BRACES ObjectIterable arrayFlatMap(Iterable iterable, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { + return new FlatMappedArrayIterable<>(wrap(iterable), mapper); + } + + /** + * A Helper function that flatMaps a Iterable into a new Type. + * @param iterable the iterable that should be flatMapped + * @param mapper the function that decides what the result turns into. + * @Type(T) + * @param The return type. + * @return a iterable that is flatMapped to a new result + */ + public static GENERIC_KEY_SPECIAL_BRACES ObjectIterable arrayFlatMap(ITERABLE KEY_GENERIC_TYPE iterable, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { + return new FlatMappedArrayIterable<>(iterable, mapper); + } + + /** + * A Helper function that filters out all desired elements from a Java-Iterable + * @param iterable that should be filtered. + * @param filter the filter that decides that should be let through + * @Type(T) + * @return a filtered iterable + */ + public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE filter(Iterable iterable, PREDICATE KEY_GENERIC_TYPE filter) { + return new FilteredIterableBRACES(wrap(iterable), filter); + } + + /** + * A Helper function that filters out all desired elements + * @param iterable that should be filtered. + * @param filter the filter that decides that should be let through + * @Type(T) + * @return a filtered iterable + */ + public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE filter(ITERABLE KEY_GENERIC_TYPE iterable, PREDICATE KEY_GENERIC_TYPE filter) { + return new FilteredIterableBRACES(iterable, filter); + } + + /** + * A Helper function that filters out all duplicated elements. + * @param iterable that should be distinct + * @Type(T) + * @return a distinct iterable + */ + public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE distinct(ITERABLE KEY_GENERIC_TYPE iterable) { + return new DistinctIterableBRACES(iterable); + } + + /** + * A Helper function that filters out all duplicated elements from a Java Iterable. + * @param iterable that should be distinct + * @Type(T) + * @return a distinct iterable + */ + public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE distinct(Iterable iterable) { + return new DistinctIterableBRACES(wrap(iterable)); + } + + /** + * A Helper function that repeats the Iterable a specific amount of times + * @param iterable that should be repeated + * @param repeats the amount of times the iterable should be repeated + * @Type(T) + * @return a repeating iterable + */ + public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE repeat(ITERABLE KEY_GENERIC_TYPE iterable, int repeats) { + return new RepeatingIterableBRACES(iterable, repeats); + } + + /** + * A Helper function that repeats the Iterable a specific amount of times from a Java Iterable + * @param iterable that should be repeated + * @param repeats the amount of times the iterable should be repeated + * @Type(T) + * @return a repeating iterable + */ + public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE repeat(Iterable iterable, int repeats) { + return new RepeatingIterableBRACES(wrap(iterable), repeats); + } + + /** + * A Helper function that hard limits the Iterable to a specific size + * @param iterable that should be limited + * @param limit the amount of elements it should be limited to + * @Type(T) + * @return a limited iterable + */ + public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE limit(ITERABLE KEY_GENERIC_TYPE iterable, long limit) { + return new LimitedIterableBRACES(iterable, limit); + } + + /** + * A Helper function that hard limits the Iterable to a specific size from a Java Iterable + * @param iterable that should be limited + * @param limit the amount of elements it should be limited to + * @Type(T) + * @return a limited iterable + */ + public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE limit(Iterable iterable, long limit) { + return new LimitedIterableBRACES(wrap(iterable), limit); + } + + /** + * A Helper function that sorts the Iterable. + * This operation is heavily hurting performance because it rebuilds the entire iterator and then sorts it. + * @param iterable that should be sorted + * @param sorter that sorts the iterable. Can be null. + * @Type(T) + * @return a sorted iterable. + */ + public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE sorted(ITERABLE KEY_GENERIC_TYPE iterable, COMPARATOR KEY_GENERIC_TYPE sorter) { + return new SortedIterableBRACES(iterable, sorter); + } + + /** + * A Helper function that sorts the Iterable from a Java Iterable + * This operation is heavily hurting performance because it rebuilds the entire iterator and then sorts it. + * @param iterable that should be sorted + * @param sorter that sorts the iterable. Can be null. + * @Type(T) + * @return a sorted iterable. + */ + public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE sorted(Iterable iterable, COMPARATOR KEY_GENERIC_TYPE sorter) { + return new SortedIterableBRACES(wrap(iterable), sorter); + } + + /** + * A Helper function that allows to preview the result of a Iterable. + * @param iterable that should be peeked at + * @param action callback that receives the value before the iterable returns it + * @Type(T) + * @return a peeked iterable + */ + public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE peek(ITERABLE KEY_GENERIC_TYPE iterable, CONSUMER KEY_GENERIC_TYPE action) { + return new PeekIterableBRACES(iterable, action); + } + + /** + * A Helper function that allows to preview the result of a Iterable from a Java Iterable + * @param iterable that should be peeked at + * @param action callback that receives the value before the iterable returns it + * @Type(T) + * @return a peeked iterable + */ + public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE peek(Iterable iterable, CONSUMER KEY_GENERIC_TYPE action) { + return new PeekIterableBRACES(wrap(iterable), action); + } + + /** + * A Wrapper function that wraps a Java-Iterable into a Type Specific Iterable + * @param iterable that should be wrapped + * @Type(T) + * @return a type specific iterable + */ + public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE wrap(Iterable iterable) { + return new WrappedIterableBRACES(iterable); + } + + private static class WrappedIterable KEY_GENERIC_TYPE implements ITERABLE KEY_GENERIC_TYPE, ISizeProvider + { + Iterable iterable; + + public WrappedIterable(Iterable iterable) { + this.iterable = iterable; + } + + public ITERATOR KEY_GENERIC_TYPE iterator() { + return ITERATORS.wrap(iterable.iterator()); + } + + @Override + public int size() { + ISizeProvider prov = ISizeProvider.of(iterable); + return prov == null ? -1 : prov.size(); + } + +#if !TYPE_OBJECT + @Override + public void forEach(CONSUMER action) { + Objects.requireNonNull(action); + iterable.forEach(action); + } +#else + public void forEach(Consumer action) { + Objects.requireNonNull(action); + iterable.forEach(action); + } +#endif + } + + private static class MappedIterable KSS_GENERIC_TYPE implements ObjectIterable, ISizeProvider + { + ITERABLE KEY_SPECIAL_GENERIC_TYPE iterable; + TO_OBJECT_FUNCTION KSS_GENERIC_TYPE mapper; + + MappedIterable(ITERABLE KEY_SPECIAL_GENERIC_TYPE iterable, TO_OBJECT_FUNCTION KSS_GENERIC_TYPE mapper) { + this.iterable = iterable; + this.mapper = mapper; + } + + public ObjectIterator iterator() { + return ITERATORS.map(iterable.iterator(), mapper); + } + + @Override + public int size() { + ISizeProvider prov = ISizeProvider.of(this); + return prov == null ? -1 : prov.size(); + } + + @Override + public void forEach(Consumer action) { + Objects.requireNonNull(action); + iterable.forEach(E -> action.accept(mapper.apply(E))); + } + } + + private static class FlatMappedIterable KSS_GENERIC_TYPE> implements ObjectIterable + { + ITERABLE KEY_SPECIAL_GENERIC_TYPE iterable; + TO_OBJECT_FUNCTION KSS_GENERIC_TYPE mapper; + + FlatMappedIterable(ITERABLE KEY_SPECIAL_GENERIC_TYPE iterable, TO_OBJECT_FUNCTION KSS_GENERIC_TYPE mapper) { + this.iterable = iterable; + this.mapper = mapper; + } + + @Override + public ObjectIterator iterator() { + return ITERATORS.flatMap(iterable.iterator(), mapper); + } + + @Override + public void forEach(Consumer action) { + Objects.requireNonNull(action); + iterable.forEach(E -> mapper.apply(E).forEach(action)); + } + + } + + private static class FlatMappedArrayIterable KSS_GENERIC_TYPE implements ObjectIterable + { + ITERABLE KEY_SPECIAL_GENERIC_TYPE iterable; + TO_OBJECT_FUNCTION KSS_GENERIC_TYPE mapper; + + FlatMappedArrayIterable(ITERABLE KEY_SPECIAL_GENERIC_TYPE iterable, TO_OBJECT_FUNCTION KSS_GENERIC_TYPE mapper) { + this.iterable = iterable; + this.mapper = mapper; + } + + @Override + public ObjectIterator iterator() { + return ITERATORS.arrayFlatMap(iterable.iterator(), mapper); + } + + @Override + public void forEach(Consumer action) { + Objects.requireNonNull(action); + iterable.forEach(E -> { + T[] array = mapper.apply(E); + for(int i = 0,m=array.length;i action) { + Objects.requireNonNull(action); + COLLECTION KEY_GENERIC_TYPE repeater = COLLECTIONS.wrapper(); + iterable.forEach(T -> {action.accept(T); repeater.add(T);}); + for(int i = 0;i { if(!filter.test(T)) action.accept(T); } ); + } +#else + public void forEach(Consumer action) { + Objects.requireNonNull(action); + iterable.forEach(T -> { if(!filter.test(T)) action.accept(T); } ); + } +#endif + } + + private static class LimitedIterable KEY_GENERIC_TYPE implements ITERABLE KEY_GENERIC_TYPE, ISizeProvider + { + ITERABLE KEY_GENERIC_TYPE iterable; + long limit; + + public LimitedIterable(ITERABLE KEY_GENERIC_TYPE iterable, long limit) { + this.iterable = iterable; + this.limit = limit; + } + + @Override + public ITERATOR KEY_GENERIC_TYPE iterator() { + return ITERATORS.limit(iterable.iterator(), limit); + } + + @Override + public int size() { + ISizeProvider prov = ISizeProvider.of(iterable); + return prov == null ? -1 : (int)Math.min(prov.size(), limit); + } + +#if !TYPE_OBJECT + @Override + public void forEach(CONSUMER action) { + Objects.requireNonNull(action); + AtomicLong counter = new AtomicLong(); + iterable.forEach(T -> { + if(counter.get() >= limit) return; + counter.incrementAndGet(); + action.accept(T); + }); + } +#else + public void forEach(Consumer action) { + Objects.requireNonNull(action); + AtomicLong counter = new AtomicLong(); + iterable.forEach(T -> { + if(counter.get() >= limit) return; + counter.incrementAndGet(); + action.accept(T); + }); + } +#endif + } + + private static class SortedIterable KEY_GENERIC_TYPE implements ITERABLE KEY_GENERIC_TYPE, ISizeProvider + { + ITERABLE KEY_GENERIC_TYPE iterable; + COMPARATOR KEY_GENERIC_TYPE sorter; + + public SortedIterable(ITERABLE KEY_GENERIC_TYPE iterable, COMPARATOR KEY_GENERIC_TYPE sorter) { + this.iterable = iterable; + this.sorter = sorter; + } + + @Override + public ITERATOR KEY_GENERIC_TYPE iterator() { + return ITERATORS.sorted(iterable.iterator(), sorter); + } + + @Override + public int size() { + ISizeProvider prov = ISizeProvider.of(iterable); + return prov == null ? -1 : prov.size(); + } + +#if !TYPE_OBJECT + @Override + public void forEach(CONSUMER action) { + Objects.requireNonNull(action); + COLLECTIONS.CollectionWrapper KEY_GENERIC_TYPE wrapper = COLLECTIONS.wrapper(); + iterable.forEach(wrapper::add); + wrapper.unstableSort(sorter); + wrapper.forEach(action); + } +#else + @Override + public void forEach(Consumer action) { + Objects.requireNonNull(action); + COLLECTIONS.CollectionWrapper KEY_GENERIC_TYPE wrapper = COLLECTIONS.wrapper(); + iterable.forEach(wrapper::add); + wrapper.unstableSort(sorter); + wrapper.forEach(action); + } +#endif + } + + private static class DistinctIterable KEY_GENERIC_TYPE implements ITERABLE KEY_GENERIC_TYPE + { + ITERABLE KEY_GENERIC_TYPE iterable; + + public DistinctIterable(ITERABLE KEY_GENERIC_TYPE iterable) { + this.iterable = iterable; + } + + @Override + public ITERATOR KEY_GENERIC_TYPE iterator() { + return ITERATORS.distinct(iterable.iterator()); + } + +#if !TYPE_OBJECT + @Override + public void forEach(CONSUMER action) { + Objects.requireNonNull(action); +#if TYPE_BOOLEAN + AtomicInteger result = new AtomicInteger(); + iterable.forEach(T -> { + if(((result.get() & (T ? 2 : 1)) != 0)) return; + result.getAndAdd(T ? 2 : 1); + action.accept(T); + }); +#else + COLLECTION KEY_GENERIC_TYPE filtered = COLLECTIONS.distinctWrapper(); + iterable.forEach(T -> { if(filtered.add(T)) action.accept(T); }); +#endif + } +#else + public void forEach(Consumer action) { + Objects.requireNonNull(action); + COLLECTION KEY_GENERIC_TYPE filtered = COLLECTIONS.distinctWrapper(); + iterable.forEach(T -> { if(filtered.add(T)) action.accept(T); }); + } +#endif + } + + private static class PeekIterable KEY_GENERIC_TYPE implements ITERABLE KEY_GENERIC_TYPE, ISizeProvider + { + ITERABLE KEY_GENERIC_TYPE iterable; + CONSUMER KEY_GENERIC_TYPE action; + + public PeekIterable(ITERABLE KEY_GENERIC_TYPE iterable, CONSUMER KEY_GENERIC_TYPE action) { + this.iterable = iterable; + this.action = action; + } + + @Override + public ITERATOR KEY_GENERIC_TYPE iterator() { + return ITERATORS.peek(iterable.iterator(), action); + } + + @Override + public int size() { + ISizeProvider prov = ISizeProvider.of(iterable); + return prov == null ? -1 : prov.size(); + } + +#if !TYPE_OBJECT + @Override + public void forEach(CONSUMER action) { + Objects.requireNonNull(action); + iterable.forEach(this.action.andThen(action)); + } +#else + public void forEach(Consumer action) { + Objects.requireNonNull(action); + iterable.forEach(this.action.andThen(action)); + } +#endif + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/collections/templates/utils/Iterators.template b/src/builder/resources/speiger/assets/collections/templates/utils/Iterators.template index d9aebe7..9b7ffa7 100644 --- a/src/builder/resources/speiger/assets/collections/templates/utils/Iterators.template +++ b/src/builder/resources/speiger/assets/collections/templates/utils/Iterators.template @@ -1,1120 +1,1120 @@ -package speiger.src.collections.PACKAGE.utils; - -import java.util.Iterator; -import java.util.NoSuchElementException; -#if TYPE_OBJECT -import java.util.Comparator; -import java.util.function.CONSUMER; -#endif -#if JDK_FUNCTION -import java.util.function.PREDICATE; -#endif - -import speiger.src.collections.PACKAGE.collections.ITERATOR; -#if !TYPE_OBJECT -import speiger.src.collections.objects.collections.ObjectIterator; -import speiger.src.collections.objects.utils.ObjectIterators; -import speiger.src.collections.PACKAGE.functions.CONSUMER; -import speiger.src.collections.PACKAGE.functions.COMPARATOR; -#endif -import speiger.src.collections.PACKAGE.functions.function.TO_OBJECT_FUNCTION; -#if !JDK_FUNCTION -import speiger.src.collections.PACKAGE.functions.function.PREDICATE; -#endif -#if ARRAY_LIST_FEATURE || LINKED_LIST_FEATURE -import speiger.src.collections.PACKAGE.lists.LIST; -#if ARRAY_LIST_FEATURE -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -#else if LINKED_LIST_FEATURE -import speiger.src.collections.PACKAGE.lists.LINKED_LIST; -#endif - -#endif -import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; -import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; -import speiger.src.collections.PACKAGE.collections.COLLECTION; - -/** - * A Helper class for Iterators - */ -public class ITERATORS -{ - /** - * Empty Iterator Reference - */ - private static final EmptyIterator NO_GENERIC_TYPE EMPTY = new EmptyIteratorBRACES(); - - /** - * Returns a Immutable EmptyIterator instance that is automatically casted. - * @Type(T) - * @return an empty iterator - */ - public static GENERIC_KEY_BRACES EmptyIterator KEY_GENERIC_TYPE empty() { -#if TYPE_OBJECT - return (EmptyIterator)EMPTY; -#else - return EMPTY; -#endif - } - - /** - * Inverter function for Bidirectional Iterators - * @param it the iterator that should be inverted - * @Type(T) - * @return a Inverted Bidirectional Iterator. If it was inverted then it just gives back the original reference - */ - public static GENERIC_KEY_BRACES BI_ITERATOR KEY_GENERIC_TYPE invert(BI_ITERATOR KEY_GENERIC_TYPE it) { - return it instanceof ReverseBiIterator ? ((ReverseBiIterator KEY_GENERIC_TYPE)it).it : new ReverseBiIteratorBRACES(it); - } - - /** - * Inverter function for List Iterators - * @param it the iterator that should be inverted - * @Type(T) - * @return a Inverted List Iterator. If it was inverted then it just gives back the original reference - */ - public static GENERIC_KEY_BRACES LIST_ITERATOR KEY_GENERIC_TYPE invert(LIST_ITERATOR KEY_GENERIC_TYPE it) { - return it instanceof ReverseListIterator ? ((ReverseListIterator KEY_GENERIC_TYPE)it).it : new ReverseListIteratorBRACES(it); - } - - /** - * Returns a Immutable Iterator instance based on the instance given. - * @param iterator that should be made immutable/unmodifiable - * @Type(T) - * @return a unmodifiable iterator wrapper. If the Iterator already a unmodifiable wrapper then it just returns itself. - */ - public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE unmodifiable(ITERATOR KEY_GENERIC_TYPE iterator) { - return iterator instanceof UnmodifiableIterator ? iterator : new UnmodifiableIteratorBRACES(iterator); - } - - /** - * Returns a Immutable Iterator instance based on the instance given. - * @param iterator that should be made immutable/unmodifiable - * @Type(T) - * @return a unmodifiable iterator wrapper. If the Iterator already a unmodifiable wrapper then it just returns itself. - */ - public static GENERIC_KEY_BRACES BI_ITERATOR KEY_GENERIC_TYPE unmodifiable(BI_ITERATOR KEY_GENERIC_TYPE iterator) { - return iterator instanceof UnmodifiableBiIterator ? iterator : new UnmodifiableBiIteratorBRACES(iterator); - } - - /** - * Returns a Immutable ListIterator instance based on the instance given. - * @param iterator that should be made immutable/unmodifiable - * @Type(T) - * @return a unmodifiable listiterator wrapper. If the ListIterator already a unmodifiable wrapper then it just returns itself. - */ - public static GENERIC_KEY_BRACES LIST_ITERATOR KEY_GENERIC_TYPE unmodifiable(LIST_ITERATOR KEY_GENERIC_TYPE iterator) { - return iterator instanceof UnmodifiableListIterator ? iterator : new UnmodifiableListIteratorBRACES(iterator); - } - - /** - * A Helper function that maps a Java-Iterator into a new Type. - * @param iterator that should be mapped - * @param mapper the function that decides what the result turns into. - * @Type(T) - * @param The return type. - * @return a iterator that is mapped to a new result - */ - public static GENERIC_KEY_SPECIAL_BRACES ObjectIterator map(Iterator iterator, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { - return new MappedIterator<>(wrap(iterator), mapper); - } - - /** - * A Helper function that maps a Iterator into a new Type. - * @param iterator that should be mapped - * @param mapper the function that decides what the result turns into. - * @Type(T) - * @param The return type. - * @return a iterator that is mapped to a new result - */ - public static GENERIC_KEY_SPECIAL_BRACES ObjectIterator map(ITERATOR KEY_GENERIC_TYPE iterator, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { - return new MappedIterator<>(iterator, mapper); - } - - /** - * A Helper function that flatMaps a Java-Iterator into a new Type. - * @param iterator that should be flatMapped - * @param mapper the function that decides what the result turns into. - * @Type(T) - * @param The return type supplier. - * @param The return type. - * @return a iterator that is flatMapped to a new result - */ - public static GENERIC_KEY_SPECIAL_BRACES> ObjectIterator flatMap(Iterator iterator, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { - return new FlatMappedIterator<>(wrap(iterator), mapper); - } - - /** - * A Helper function that flatMaps a Iterator into a new Type. - * @param iterator that should be flatMapped - * @param mapper the function that decides what the result turns into. - * @Type(T) - * @param The return type supplier. - * @param The return type. - * @return a iterator that is flatMapped to a new result - */ - public static GENERIC_KEY_SPECIAL_BRACES> ObjectIterator flatMap(ITERATOR KEY_GENERIC_TYPE iterator, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { - return new FlatMappedIterator<>(iterator, mapper); - } - - /** - * A Helper function that flatMaps a Java-Iterator into a new Type. - * @param iterator that should be flatMapped - * @param mapper the function that decides what the result turns into. - * @Type(T) - * @param The return type. - * @return a iterator that is flatMapped to a new result - */ - public static GENERIC_KEY_SPECIAL_BRACES ObjectIterator arrayFlatMap(Iterator iterator, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { - return new FlatMappedArrayIterator<>(wrap(iterator), mapper); - } - - /** - * A Helper function that flatMaps a Iterator into a new Type. - * @param iterator that should be flatMapped - * @param mapper the function that decides what the result turns into. - * @Type(T) - * @param The return type. - * @return a iterator that is flatMapped to a new result - */ - public static GENERIC_KEY_SPECIAL_BRACES ObjectIterator arrayFlatMap(ITERATOR KEY_GENERIC_TYPE iterator, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { - return new FlatMappedArrayIterator<>(iterator, mapper); - } - - /** - * A Helper function that filters out all desired elements from a Java-Iterator - * @param iterator that should be filtered. - * @param filter the filter that decides that should be let through - * @Type(T) - * @return a filtered iterator - */ - public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE filter(Iterator iterator, PREDICATE KEY_GENERIC_TYPE filter) { - return new FilteredIteratorBRACES(wrap(iterator), filter); - } - - /** - * A Helper function that filters out all desired elements - * @param iterator that should be filtered. - * @param filter the filter that decides that should be let through - * @Type(T) - * @return a filtered iterator - */ - public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE filter(ITERATOR KEY_GENERIC_TYPE iterator, PREDICATE KEY_GENERIC_TYPE filter) { - return new FilteredIteratorBRACES(iterator, filter); - } - - /** - * A Helper function that filters out all duplicated elements. - * @param iterator that should be distinct - * @Type(T) - * @return a distinct iterator - */ - public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE distinct(ITERATOR KEY_GENERIC_TYPE iterator) { - return new DistinctIteratorBRACES(iterator); - } - - /** - * A Helper function that filters out all duplicated elements from a Java Iterator. - * @param iterator that should be distinct - * @Type(T) - * @return a distinct iterator - */ - public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE distinct(Iterator iterator) { - return new DistinctIteratorBRACES(wrap(iterator)); - } - - /** - * A Helper function that repeats the Iterator a specific amount of times - * @param iterator that should be repeated - * @param repeats the amount of times the iterator should be repeated - * @Type(T) - * @return a repeating iterator - */ - public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE repeat(ITERATOR KEY_GENERIC_TYPE iterator, int repeats) { - return new RepeatingIteratorBRACES(iterator, repeats); - } - - /** - * A Helper function that repeats the Iterator a specific amount of times from a Java Iterator - * @param iterator that should be repeated - * @param repeats the amount of times the iterator should be repeated - * @Type(T) - * @return a repeating iterator - */ - public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE repeat(Iterator iterator, int repeats) { - return new RepeatingIteratorBRACES(wrap(iterator), repeats); - } - - /** - * A Helper function that hard limits the Iterator to a specific size - * @param iterator that should be limited - * @param limit the amount of elements it should be limited to - * @Type(T) - * @return a limited iterator - */ - public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE limit(ITERATOR KEY_GENERIC_TYPE iterator, long limit) { - return new LimitedIteratorBRACES(iterator, limit); - } - - /** - * A Helper function that hard limits the Iterator to a specific size from a Java Iterator - * @param iterator that should be limited - * @param limit the amount of elements it should be limited to - * @Type(T) - * @return a limited iterator - */ - public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE limit(Iterator iterator, long limit) { - return new LimitedIteratorBRACES(wrap(iterator), limit); - } - - /** - * A Helper function that sorts the Iterator beforehand. - * This operation is heavily hurting performance because it rebuilds the entire iterator and then sorts it. - * @param iterator that should be sorted. - * @param sorter the sorter of the iterator. Can be null. - * @Type(T) - * @return a new sorted iterator - */ - public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE sorted(ITERATOR KEY_GENERIC_TYPE iterator, COMPARATOR KEY_GENERIC_TYPE sorter) { - return new SortedIteratorBRACES(iterator, sorter); - } - - /** - * A Helper function that sorts the Iterator beforehand from a Java Iterator. - * This operation is heavily hurting performance because it rebuilds the entire iterator and then sorts it. - * @param iterator that should be sorted. - * @param sorter the sorter of the iterator. Can be null. - * @Type(T) - * @return a new sorted iterator - */ - public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE sorted(Iterator iterator, COMPARATOR KEY_GENERIC_TYPE sorter) { - return new SortedIteratorBRACES(wrap(iterator), sorter); - } - - /** - * A Helper function that allows to preview the result of a Iterator. - * @param iterator that should be peeked at - * @param action callback that receives the value before the iterator returns it - * @Type(T) - * @return a peeked iterator - */ - public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE peek(ITERATOR KEY_GENERIC_TYPE iterator, CONSUMER KEY_GENERIC_TYPE action) { - return new PeekIteratorBRACES(iterator, action); - } - - /** - * A Helper function that allows to preview the result of a Iterator from a Java Iterator - * @param iterator that should be peeked at - * @param action callback that receives the value before the iterator returns it - * @Type(T) - * @return a peeked iterator - */ - public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE peek(Iterator iterator, CONSUMER KEY_GENERIC_TYPE action) { - return new PeekIteratorBRACES(wrap(iterator), action); - } - - /** - * Helper function to convert a Object Iterator into a Primitive Iterator - * @param iterator that should be converted to a unboxing iterator - * @ArrayType(T) - * @return a primitive iterator - */ - public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE wrap(Iterator iterator) { - return iterator instanceof ITERATOR ? (ITERATOR KEY_GENERIC_TYPE)iterator : new IteratorWrapperBRACES(iterator); - } - - /** - * Returns a Array Wrapping iterator - * @param a the array that should be wrapped - * @ArrayType(T) - * @return a Iterator that is wrapping a array. - */ - public static GENERIC_KEY_BRACES ArrayIterator KEY_GENERIC_TYPE wrap(KEY_TYPE... a) { - return wrap(a, 0, a.length); - } - - /** - * Returns a Array Wrapping iterator - * @param a the array that should be wrapped. - * @param start the index to be started from. - * @param end the index that should be ended. - * @ArrayType(T) - * @return a Iterator that is wrapping a array. - */ - public static GENERIC_KEY_BRACES ArrayIterator KEY_GENERIC_TYPE wrap(KEY_TYPE[] a, int start, int end) { - return new ArrayIteratorBRACES(a, start, end); - } - - /** - * Iterates over a iterator and inserts the values into the array and returns the amount that was inserted - * @param a where the elements should be inserted - * @param i the source iterator - * @ArrayType(T) - * @return the amount of elements that were inserted into the array. - */ - public static GENERIC_KEY_BRACES int unwrap(KEY_TYPE[] a, Iterator i) { - return unwrap(a, i, 0, a.length); - } - - /** - * Iterates over a iterator and inserts the values into the array and returns the amount that was inserted - * @param a where the elements should be inserted - * @param i the source iterator - * @param offset the array offset where the start should be - * @ArrayType(T) - * @return the amount of elements that were inserted into the array. - */ - public static GENERIC_KEY_BRACES int unwrap(KEY_TYPE[] a, Iterator i, int offset) { - return unwrap(a, i, offset, a.length - offset); - } - - /** - * Iterates over a iterator and inserts the values into the array and returns the amount that was inserted - * @param a where the elements should be inserted - * @param i the source iterator - * @param offset the array offset where the start should be - * @param max the maximum values that should be extracted from the source - * @ArrayType(T) - * @return the amount of elements that were inserted into the array. - * @throws IllegalStateException if max is smaller the 0 or if the maximum index is larger then the array - */ - public static GENERIC_KEY_BRACES int unwrap(KEY_TYPE[] a, Iterator i, int offset, int max) { - if(max < 0) throw new IllegalStateException("The max size is smaller then 0"); - if(offset + max > a.length) throw new IllegalStateException("largest array index exceeds array size"); - int index = 0; - for(;index a.length) throw new IllegalStateException("largest array index exceeds array size"); - int index = 0; - for(;index a.length) throw new IllegalStateException("largest array index exceeds array size"); - int index = 0; - for(;index iter; - - public IteratorWrapper(Iterator iter) { - this.iter = iter; - } - - @Override - public boolean hasNext() { - return iter.hasNext(); - } - - @Override - public KEY_TYPE NEXT() { - return OBJ_TO_KEY(iter.next()); - } - -#if !TYPE_OBJECT - @Override - @Deprecated - public CLASS_TYPE next() { - return iter.next(); - } -#endif - } - - private static class ConcatIterator KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE - { - ITERATOR KEY_GENERIC_TYPE[] iters; - int offset; - int lastOffset = -1; - int length; - - public ConcatIterator(ITERATOR KEY_GENERIC_TYPE[] iters, int offset, int length) { - this.iters = iters; - this.offset = offset; - this.length = length; - find(); - } - - private void find() { - for(;length != 0 && !iters[offset].hasNext();length--, offset++); - } - - @Override - public boolean hasNext() { - return length > 0; - } - - @Override - public KEY_TYPE NEXT() { - if(!hasNext()) throw new NoSuchElementException(); - KEY_TYPE result = iters[lastOffset = offset].NEXT(); - find(); - return result; - } - - @Override - public void remove() { - if(lastOffset == -1) throw new IllegalStateException(); - iters[lastOffset].remove(); - lastOffset = -1; - } - } - - private static class ReverseBiIterator KEY_GENERIC_TYPE implements BI_ITERATOR KEY_GENERIC_TYPE { - BI_ITERATOR KEY_GENERIC_TYPE it; - - ReverseBiIterator(BI_ITERATOR KEY_GENERIC_TYPE it) { - this.it = it; - } - - @Override - public KEY_TYPE NEXT() { return it.PREVIOUS(); } - @Override - public boolean hasNext() { return it.hasPrevious(); } - @Override - public boolean hasPrevious() { return it.hasNext(); } - @Override - public KEY_TYPE PREVIOUS() { return it.NEXT(); } - @Override - public void remove() { it.remove(); } - } - - private static class ReverseListIterator KEY_GENERIC_TYPE implements LIST_ITERATOR KEY_GENERIC_TYPE { - LIST_ITERATOR KEY_GENERIC_TYPE it; - - ReverseListIterator(LIST_ITERATOR KEY_GENERIC_TYPE it) { - this.it = it; - } - - @Override - public KEY_TYPE NEXT() { return it.PREVIOUS(); } - @Override - public boolean hasNext() { return it.hasPrevious(); } - @Override - public boolean hasPrevious() { return it.hasNext(); } - @Override - public KEY_TYPE PREVIOUS() { return it.NEXT(); } - @Override - public void remove() { it.remove(); } - @Override - public int nextIndex() { return it.previousIndex(); } - @Override - public int previousIndex() { return it.nextIndex(); } - @Override - public void set(KEY_TYPE e) { it.set(e); } - @Override - public void add(KEY_TYPE e) { it.add(e); } - } - - private static class UnmodifiableListIterator KEY_GENERIC_TYPE implements LIST_ITERATOR KEY_GENERIC_TYPE - { - LIST_ITERATOR KEY_GENERIC_TYPE iter; - - UnmodifiableListIterator(LIST_ITERATOR KEY_GENERIC_TYPE iter) { - this.iter = iter; - } - - @Override - public boolean hasNext() { - return iter.hasNext(); - } - - @Override - public boolean hasPrevious() { - return iter.hasPrevious(); - } - - @Override - public int nextIndex() { - return iter.nextIndex(); - } - - @Override - public int previousIndex() { - return iter.previousIndex(); - } - - @Override - public void remove() { throw new UnsupportedOperationException(); } - - @Override - public KEY_TYPE PREVIOUS() { - return iter.PREVIOUS(); - } - - @Override - public KEY_TYPE NEXT() { - return iter.NEXT(); - } - - @Override - public void set(KEY_TYPE e) { throw new UnsupportedOperationException(); } - - @Override - public void add(KEY_TYPE e) { throw new UnsupportedOperationException(); } - } - - private static class UnmodifiableBiIterator KEY_GENERIC_TYPE implements BI_ITERATOR KEY_GENERIC_TYPE - { - BI_ITERATOR KEY_GENERIC_TYPE iter; - - UnmodifiableBiIterator(BI_ITERATOR KEY_GENERIC_TYPE iter) { - this.iter = iter; - } - - @Override - public KEY_TYPE NEXT() { - return iter.NEXT(); - } - - @Override - public boolean hasNext() { - return iter.hasNext(); - } - - @Override - public boolean hasPrevious() { - return iter.hasPrevious(); - } - - @Override - public KEY_TYPE PREVIOUS() { - return iter.PREVIOUS(); - } - } - - private static class UnmodifiableIterator KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE - { - ITERATOR KEY_GENERIC_TYPE iterator; - - UnmodifiableIterator(ITERATOR KEY_GENERIC_TYPE iterator) { - this.iterator = iterator; - } - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public KEY_TYPE NEXT() { - return iterator.NEXT(); - } - } - - private static class EmptyIterator KEY_GENERIC_TYPE implements LIST_ITERATOR KEY_GENERIC_TYPE - { - @Override - public boolean hasNext() { return false; } - @Override - public KEY_TYPE NEXT() { throw new NoSuchElementException(); } - @Override - public boolean hasPrevious() { return false; } - @Override - public KEY_TYPE PREVIOUS() { throw new NoSuchElementException(); } - @Override - public int nextIndex() { return 0; } - @Override - public int previousIndex() { return -1; } - @Override - public void remove() { throw new UnsupportedOperationException(); } - @Override - public void set(KEY_TYPE e) { throw new UnsupportedOperationException(); } - @Override - public void add(KEY_TYPE e) { throw new UnsupportedOperationException(); } - } - - private static class ArrayIterator KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE - { - KEY_TYPE[] a; - int from; - int to; - - ArrayIterator(KEY_TYPE[] a, int from, int to) { - this.a = a; - this.from = from; - this.to = to; - } - - @Override - public boolean hasNext() { - return from < to; - } - - @Override - public KEY_TYPE NEXT() { - if(!hasNext()) throw new NoSuchElementException(); - return a[from++]; - } - - @Override - public int skip(int amount) { - if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed"); - int left = Math.min(amount, to - from); - from += left; - return amount - left; - } - } - - private static class MappedIterator KSS_GENERIC_TYPE implements ObjectIterator - { - ITERATOR KEY_SPECIAL_GENERIC_TYPE iterator; - TO_OBJECT_FUNCTION KSS_GENERIC_TYPE mapper; - - MappedIterator(ITERATOR KEY_SPECIAL_GENERIC_TYPE iterator, TO_OBJECT_FUNCTION KSS_GENERIC_TYPE mapper) { - this.iterator = iterator; - this.mapper = mapper; - } - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public T next() { - return mapper.apply(iterator.NEXT()); - } - - @Override - public int skip(int amount) { - return iterator.skip(amount); - } - } - - private static class FlatMappedIterator KSS_GENERIC_TYPE> implements ObjectIterator - { - ITERATOR KEY_SPECIAL_GENERIC_TYPE iterator; - Iterator last = null; - TO_OBJECT_FUNCTION KSS_GENERIC_TYPE mapper; - boolean foundNext = false; - - FlatMappedIterator(ITERATOR KEY_SPECIAL_GENERIC_TYPE iterator, TO_OBJECT_FUNCTION KSS_GENERIC_TYPE mapper) { - this.iterator = iterator; - this.mapper = mapper; - } - - void compute() { - if(foundNext) return; - foundNext = true; - while(iterator.hasNext()) { - if(last != null && last.hasNext()) return; - last = mapper.apply(iterator.NEXT()).iterator(); - } - } - - @Override - public boolean hasNext() { - compute(); - return last != null && last.hasNext(); - } - - @Override - public T next() { - if(!hasNext()) throw new NoSuchElementException(); - T result = last.next(); - foundNext = false; - return result; - } - } - - private static class FlatMappedArrayIterator KSS_GENERIC_TYPE implements ObjectIterator - { - ITERATOR KEY_SPECIAL_GENERIC_TYPE iterator; - Iterator last = null; - TO_OBJECT_FUNCTION KSS_GENERIC_TYPE mapper; - boolean foundNext = false; - - FlatMappedArrayIterator(ITERATOR KEY_SPECIAL_GENERIC_TYPE iterator, TO_OBJECT_FUNCTION KSS_GENERIC_TYPE mapper) { - this.iterator = iterator; - this.mapper = mapper; - } - - void compute() { - if(foundNext) return; - foundNext = true; - while(iterator.hasNext()) { - if(last != null && last.hasNext()) return; - last = ObjectIterators.wrap(mapper.apply(iterator.NEXT())); - } - } - - @Override - public boolean hasNext() { - compute(); - return last != null && last.hasNext(); - } - - @Override - public T next() { - if(!hasNext()) throw new NoSuchElementException(); - T result = last.next(); - foundNext = false; - return result; - } - } - - private static class RepeatingIterator KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE - { - final int repeats; - int index = 0; - ITERATOR KEY_GENERIC_TYPE iter; - COLLECTION KEY_GENERIC_TYPE repeater = COLLECTIONS.wrapper(); - - public RepeatingIterator(ITERATOR KEY_GENERIC_TYPE iter, int repeat) { - this.iter = iter; - this.repeats = repeat; - } - - @Override - public boolean hasNext() { - if(iter.hasNext()) return true; - if(index < repeats) { - index++; - iter = repeater.iterator(); - return iter.hasNext(); - } - return false; - } - - @Override - public KEY_TYPE NEXT() { - if(!hasNext()) throw new NoSuchElementException(); - KEY_TYPE value = iter.NEXT(); - if(index == 0) repeater.add(value); - return value; - } - } - - private static class SortedIterator KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE - { - ITERATOR KEY_GENERIC_TYPE iterator; - COMPARATOR KEY_GENERIC_TYPE sorter; - COLLECTIONS.CollectionWrapper KEY_GENERIC_TYPE sortedElements = null; - int index = 0; - - public SortedIterator(ITERATOR KEY_GENERIC_TYPE iterator, COMPARATOR KEY_GENERIC_TYPE sorter) { - this.iterator = iterator; - this.sorter = sorter; - } - - @Override - public boolean hasNext() { - if(sortedElements == null) { - boolean hasNext = iterator.hasNext(); - if(hasNext) { - sortedElements = COLLECTIONS.wrapper(); - pour(iterator, sortedElements); - } - else sortedElements = COLLECTIONS.wrapper(); - if(hasNext) sortedElements.unstableSort(sorter); - } - return index < sortedElements.size(); - } - - @Override - public KEY_TYPE NEXT() { - if(!hasNext()) throw new NoSuchElementException(); - return sortedElements.GET_KEY(index++); - } - } - - private static class DistinctIterator KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE - { - ITERATOR KEY_GENERIC_TYPE iterator; -#if TYPE_BOOLEAN - int filtered; -#else - COLLECTION KEY_GENERIC_TYPE filtered = COLLECTIONS.distinctWrapper(); -#endif - KEY_TYPE lastFound; - boolean foundNext = false; - - public DistinctIterator(ITERATOR KEY_GENERIC_TYPE iterator) { - this.iterator = iterator; - } - - void compute() { - if(foundNext) return; -#if TYPE_BOOLEAN - if(filtered == 3) return; -#endif - while(iterator.hasNext()) { - lastFound = iterator.NEXT(); -#if TYPE_BOOLEAN - if((filtered & (lastFound ? 1 : 2)) == 0) { - filtered |= (lastFound ? 1 : 2); - foundNext = true; - break; - } -#else - if(filtered.add(lastFound)) { - foundNext = true; - break; - } -#endif - } - } - - @Override - public boolean hasNext() { - compute(); - return foundNext; - } - - @Override - public KEY_TYPE NEXT() { - if(!hasNext()) throw new NoSuchElementException(); - foundNext = false; - return lastFound; - } - } - - private static class FilteredIterator KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE - { - ITERATOR KEY_GENERIC_TYPE iterator; - PREDICATE KEY_GENERIC_TYPE filter; - KEY_TYPE lastFound; - boolean foundNext = false; - - public FilteredIterator(ITERATOR KEY_GENERIC_TYPE iterator, PREDICATE KEY_GENERIC_TYPE filter) { - this.iterator = iterator; - this.filter = filter; - } - - void compute() { - if(foundNext) return; - while(iterator.hasNext()) { - lastFound = iterator.NEXT(); - if(filter.test(lastFound)) { - foundNext = true; - break; - } - } - } - - @Override - public boolean hasNext() { - compute(); - return foundNext; - } - - @Override - public KEY_TYPE NEXT() { - if(!hasNext()) throw new NoSuchElementException(); - foundNext = false; - return lastFound; - } - } - - private static class LimitedIterator KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE - { - ITERATOR KEY_GENERIC_TYPE iterator; - long limit; - - public LimitedIterator(ITERATOR KEY_GENERIC_TYPE iterator, long limit) { - this.iterator = iterator; - this.limit = limit; - } - - @Override - public boolean hasNext() { - return limit > 0 && iterator.hasNext(); - } - - @Override - public KEY_TYPE NEXT() { - if(!hasNext()) throw new NoSuchElementException(); - limit--; - return iterator.NEXT(); - } - } - - private static class PeekIterator KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE - { - ITERATOR KEY_GENERIC_TYPE iterator; - CONSUMER KEY_GENERIC_TYPE action; - - public PeekIterator(ITERATOR KEY_GENERIC_TYPE iterator, CONSUMER KEY_GENERIC_TYPE action) { - this.iterator = iterator; - this.action = action; - } - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public KEY_TYPE NEXT() { - if(!hasNext()) throw new NoSuchElementException(); - KEY_TYPE result = iterator.NEXT(); - action.accept(result); - return result; - } - } +package speiger.src.collections.PACKAGE.utils; + +import java.util.Iterator; +import java.util.NoSuchElementException; +#if TYPE_OBJECT +import java.util.Comparator; +import java.util.function.CONSUMER; +#endif +#if JDK_FUNCTION +import java.util.function.PREDICATE; +#endif + +import speiger.src.collections.PACKAGE.collections.ITERATOR; +#if !TYPE_OBJECT +import speiger.src.collections.objects.collections.ObjectIterator; +import speiger.src.collections.objects.utils.ObjectIterators; +import speiger.src.collections.PACKAGE.functions.CONSUMER; +import speiger.src.collections.PACKAGE.functions.COMPARATOR; +#endif +import speiger.src.collections.PACKAGE.functions.function.TO_OBJECT_FUNCTION; +#if !JDK_FUNCTION +import speiger.src.collections.PACKAGE.functions.function.PREDICATE; +#endif +#if ARRAY_LIST_FEATURE || LINKED_LIST_FEATURE +import speiger.src.collections.PACKAGE.lists.LIST; +#if ARRAY_LIST_FEATURE +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +#else if LINKED_LIST_FEATURE +import speiger.src.collections.PACKAGE.lists.LINKED_LIST; +#endif + +#endif +import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; +import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; +import speiger.src.collections.PACKAGE.collections.COLLECTION; + +/** + * A Helper class for Iterators + */ +public class ITERATORS +{ + /** + * Empty Iterator Reference + */ + private static final EmptyIterator NO_GENERIC_TYPE EMPTY = new EmptyIteratorBRACES(); + + /** + * Returns a Immutable EmptyIterator instance that is automatically casted. + * @Type(T) + * @return an empty iterator + */ + public static GENERIC_KEY_BRACES EmptyIterator KEY_GENERIC_TYPE empty() { +#if TYPE_OBJECT + return (EmptyIterator)EMPTY; +#else + return EMPTY; +#endif + } + + /** + * Inverter function for Bidirectional Iterators + * @param it the iterator that should be inverted + * @Type(T) + * @return a Inverted Bidirectional Iterator. If it was inverted then it just gives back the original reference + */ + public static GENERIC_KEY_BRACES BI_ITERATOR KEY_GENERIC_TYPE invert(BI_ITERATOR KEY_GENERIC_TYPE it) { + return it instanceof ReverseBiIterator ? ((ReverseBiIterator KEY_GENERIC_TYPE)it).it : new ReverseBiIteratorBRACES(it); + } + + /** + * Inverter function for List Iterators + * @param it the iterator that should be inverted + * @Type(T) + * @return a Inverted List Iterator. If it was inverted then it just gives back the original reference + */ + public static GENERIC_KEY_BRACES LIST_ITERATOR KEY_GENERIC_TYPE invert(LIST_ITERATOR KEY_GENERIC_TYPE it) { + return it instanceof ReverseListIterator ? ((ReverseListIterator KEY_GENERIC_TYPE)it).it : new ReverseListIteratorBRACES(it); + } + + /** + * Returns a Immutable Iterator instance based on the instance given. + * @param iterator that should be made immutable/unmodifiable + * @Type(T) + * @return a unmodifiable iterator wrapper. If the Iterator already a unmodifiable wrapper then it just returns itself. + */ + public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE unmodifiable(ITERATOR KEY_GENERIC_TYPE iterator) { + return iterator instanceof UnmodifiableIterator ? iterator : new UnmodifiableIteratorBRACES(iterator); + } + + /** + * Returns a Immutable Iterator instance based on the instance given. + * @param iterator that should be made immutable/unmodifiable + * @Type(T) + * @return a unmodifiable iterator wrapper. If the Iterator already a unmodifiable wrapper then it just returns itself. + */ + public static GENERIC_KEY_BRACES BI_ITERATOR KEY_GENERIC_TYPE unmodifiable(BI_ITERATOR KEY_GENERIC_TYPE iterator) { + return iterator instanceof UnmodifiableBiIterator ? iterator : new UnmodifiableBiIteratorBRACES(iterator); + } + + /** + * Returns a Immutable ListIterator instance based on the instance given. + * @param iterator that should be made immutable/unmodifiable + * @Type(T) + * @return a unmodifiable listiterator wrapper. If the ListIterator already a unmodifiable wrapper then it just returns itself. + */ + public static GENERIC_KEY_BRACES LIST_ITERATOR KEY_GENERIC_TYPE unmodifiable(LIST_ITERATOR KEY_GENERIC_TYPE iterator) { + return iterator instanceof UnmodifiableListIterator ? iterator : new UnmodifiableListIteratorBRACES(iterator); + } + + /** + * A Helper function that maps a Java-Iterator into a new Type. + * @param iterator that should be mapped + * @param mapper the function that decides what the result turns into. + * @Type(T) + * @param The return type. + * @return a iterator that is mapped to a new result + */ + public static GENERIC_KEY_SPECIAL_BRACES ObjectIterator map(Iterator iterator, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { + return new MappedIterator<>(wrap(iterator), mapper); + } + + /** + * A Helper function that maps a Iterator into a new Type. + * @param iterator that should be mapped + * @param mapper the function that decides what the result turns into. + * @Type(T) + * @param The return type. + * @return a iterator that is mapped to a new result + */ + public static GENERIC_KEY_SPECIAL_BRACES ObjectIterator map(ITERATOR KEY_GENERIC_TYPE iterator, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { + return new MappedIterator<>(iterator, mapper); + } + + /** + * A Helper function that flatMaps a Java-Iterator into a new Type. + * @param iterator that should be flatMapped + * @param mapper the function that decides what the result turns into. + * @Type(T) + * @param The return type supplier. + * @param The return type. + * @return a iterator that is flatMapped to a new result + */ + public static GENERIC_KEY_SPECIAL_BRACES> ObjectIterator flatMap(Iterator iterator, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { + return new FlatMappedIterator<>(wrap(iterator), mapper); + } + + /** + * A Helper function that flatMaps a Iterator into a new Type. + * @param iterator that should be flatMapped + * @param mapper the function that decides what the result turns into. + * @Type(T) + * @param The return type supplier. + * @param The return type. + * @return a iterator that is flatMapped to a new result + */ + public static GENERIC_KEY_SPECIAL_BRACES> ObjectIterator flatMap(ITERATOR KEY_GENERIC_TYPE iterator, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { + return new FlatMappedIterator<>(iterator, mapper); + } + + /** + * A Helper function that flatMaps a Java-Iterator into a new Type. + * @param iterator that should be flatMapped + * @param mapper the function that decides what the result turns into. + * @Type(T) + * @param The return type. + * @return a iterator that is flatMapped to a new result + */ + public static GENERIC_KEY_SPECIAL_BRACES ObjectIterator arrayFlatMap(Iterator iterator, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { + return new FlatMappedArrayIterator<>(wrap(iterator), mapper); + } + + /** + * A Helper function that flatMaps a Iterator into a new Type. + * @param iterator that should be flatMapped + * @param mapper the function that decides what the result turns into. + * @Type(T) + * @param The return type. + * @return a iterator that is flatMapped to a new result + */ + public static GENERIC_KEY_SPECIAL_BRACES ObjectIterator arrayFlatMap(ITERATOR KEY_GENERIC_TYPE iterator, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE mapper) { + return new FlatMappedArrayIterator<>(iterator, mapper); + } + + /** + * A Helper function that filters out all desired elements from a Java-Iterator + * @param iterator that should be filtered. + * @param filter the filter that decides that should be let through + * @Type(T) + * @return a filtered iterator + */ + public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE filter(Iterator iterator, PREDICATE KEY_GENERIC_TYPE filter) { + return new FilteredIteratorBRACES(wrap(iterator), filter); + } + + /** + * A Helper function that filters out all desired elements + * @param iterator that should be filtered. + * @param filter the filter that decides that should be let through + * @Type(T) + * @return a filtered iterator + */ + public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE filter(ITERATOR KEY_GENERIC_TYPE iterator, PREDICATE KEY_GENERIC_TYPE filter) { + return new FilteredIteratorBRACES(iterator, filter); + } + + /** + * A Helper function that filters out all duplicated elements. + * @param iterator that should be distinct + * @Type(T) + * @return a distinct iterator + */ + public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE distinct(ITERATOR KEY_GENERIC_TYPE iterator) { + return new DistinctIteratorBRACES(iterator); + } + + /** + * A Helper function that filters out all duplicated elements from a Java Iterator. + * @param iterator that should be distinct + * @Type(T) + * @return a distinct iterator + */ + public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE distinct(Iterator iterator) { + return new DistinctIteratorBRACES(wrap(iterator)); + } + + /** + * A Helper function that repeats the Iterator a specific amount of times + * @param iterator that should be repeated + * @param repeats the amount of times the iterator should be repeated + * @Type(T) + * @return a repeating iterator + */ + public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE repeat(ITERATOR KEY_GENERIC_TYPE iterator, int repeats) { + return new RepeatingIteratorBRACES(iterator, repeats); + } + + /** + * A Helper function that repeats the Iterator a specific amount of times from a Java Iterator + * @param iterator that should be repeated + * @param repeats the amount of times the iterator should be repeated + * @Type(T) + * @return a repeating iterator + */ + public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE repeat(Iterator iterator, int repeats) { + return new RepeatingIteratorBRACES(wrap(iterator), repeats); + } + + /** + * A Helper function that hard limits the Iterator to a specific size + * @param iterator that should be limited + * @param limit the amount of elements it should be limited to + * @Type(T) + * @return a limited iterator + */ + public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE limit(ITERATOR KEY_GENERIC_TYPE iterator, long limit) { + return new LimitedIteratorBRACES(iterator, limit); + } + + /** + * A Helper function that hard limits the Iterator to a specific size from a Java Iterator + * @param iterator that should be limited + * @param limit the amount of elements it should be limited to + * @Type(T) + * @return a limited iterator + */ + public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE limit(Iterator iterator, long limit) { + return new LimitedIteratorBRACES(wrap(iterator), limit); + } + + /** + * A Helper function that sorts the Iterator beforehand. + * This operation is heavily hurting performance because it rebuilds the entire iterator and then sorts it. + * @param iterator that should be sorted. + * @param sorter the sorter of the iterator. Can be null. + * @Type(T) + * @return a new sorted iterator + */ + public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE sorted(ITERATOR KEY_GENERIC_TYPE iterator, COMPARATOR KEY_GENERIC_TYPE sorter) { + return new SortedIteratorBRACES(iterator, sorter); + } + + /** + * A Helper function that sorts the Iterator beforehand from a Java Iterator. + * This operation is heavily hurting performance because it rebuilds the entire iterator and then sorts it. + * @param iterator that should be sorted. + * @param sorter the sorter of the iterator. Can be null. + * @Type(T) + * @return a new sorted iterator + */ + public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE sorted(Iterator iterator, COMPARATOR KEY_GENERIC_TYPE sorter) { + return new SortedIteratorBRACES(wrap(iterator), sorter); + } + + /** + * A Helper function that allows to preview the result of a Iterator. + * @param iterator that should be peeked at + * @param action callback that receives the value before the iterator returns it + * @Type(T) + * @return a peeked iterator + */ + public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE peek(ITERATOR KEY_GENERIC_TYPE iterator, CONSUMER KEY_GENERIC_TYPE action) { + return new PeekIteratorBRACES(iterator, action); + } + + /** + * A Helper function that allows to preview the result of a Iterator from a Java Iterator + * @param iterator that should be peeked at + * @param action callback that receives the value before the iterator returns it + * @Type(T) + * @return a peeked iterator + */ + public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE peek(Iterator iterator, CONSUMER KEY_GENERIC_TYPE action) { + return new PeekIteratorBRACES(wrap(iterator), action); + } + + /** + * Helper function to convert a Object Iterator into a Primitive Iterator + * @param iterator that should be converted to a unboxing iterator + * @ArrayType(T) + * @return a primitive iterator + */ + public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE wrap(Iterator iterator) { + return iterator instanceof ITERATOR ? (ITERATOR KEY_GENERIC_TYPE)iterator : new IteratorWrapperBRACES(iterator); + } + + /** + * Returns a Array Wrapping iterator + * @param a the array that should be wrapped + * @ArrayType(T) + * @return a Iterator that is wrapping a array. + */ + public static GENERIC_KEY_BRACES ArrayIterator KEY_GENERIC_TYPE wrap(KEY_TYPE... a) { + return wrap(a, 0, a.length); + } + + /** + * Returns a Array Wrapping iterator + * @param a the array that should be wrapped. + * @param start the index to be started from. + * @param end the index that should be ended. + * @ArrayType(T) + * @return a Iterator that is wrapping a array. + */ + public static GENERIC_KEY_BRACES ArrayIterator KEY_GENERIC_TYPE wrap(KEY_TYPE[] a, int start, int end) { + return new ArrayIteratorBRACES(a, start, end); + } + + /** + * Iterates over a iterator and inserts the values into the array and returns the amount that was inserted + * @param a where the elements should be inserted + * @param i the source iterator + * @ArrayType(T) + * @return the amount of elements that were inserted into the array. + */ + public static GENERIC_KEY_BRACES int unwrap(KEY_TYPE[] a, Iterator i) { + return unwrap(a, i, 0, a.length); + } + + /** + * Iterates over a iterator and inserts the values into the array and returns the amount that was inserted + * @param a where the elements should be inserted + * @param i the source iterator + * @param offset the array offset where the start should be + * @ArrayType(T) + * @return the amount of elements that were inserted into the array. + */ + public static GENERIC_KEY_BRACES int unwrap(KEY_TYPE[] a, Iterator i, int offset) { + return unwrap(a, i, offset, a.length - offset); + } + + /** + * Iterates over a iterator and inserts the values into the array and returns the amount that was inserted + * @param a where the elements should be inserted + * @param i the source iterator + * @param offset the array offset where the start should be + * @param max the maximum values that should be extracted from the source + * @ArrayType(T) + * @return the amount of elements that were inserted into the array. + * @throws IllegalStateException if max is smaller the 0 or if the maximum index is larger then the array + */ + public static GENERIC_KEY_BRACES int unwrap(KEY_TYPE[] a, Iterator i, int offset, int max) { + if(max < 0) throw new IllegalStateException("The max size is smaller then 0"); + if(offset + max > a.length) throw new IllegalStateException("largest array index exceeds array size"); + int index = 0; + for(;index a.length) throw new IllegalStateException("largest array index exceeds array size"); + int index = 0; + for(;index a.length) throw new IllegalStateException("largest array index exceeds array size"); + int index = 0; + for(;index iter; + + public IteratorWrapper(Iterator iter) { + this.iter = iter; + } + + @Override + public boolean hasNext() { + return iter.hasNext(); + } + + @Override + public KEY_TYPE NEXT() { + return OBJ_TO_KEY(iter.next()); + } + +#if !TYPE_OBJECT + @Override + @Deprecated + public CLASS_TYPE next() { + return iter.next(); + } +#endif + } + + private static class ConcatIterator KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE + { + ITERATOR KEY_GENERIC_TYPE[] iters; + int offset; + int lastOffset = -1; + int length; + + public ConcatIterator(ITERATOR KEY_GENERIC_TYPE[] iters, int offset, int length) { + this.iters = iters; + this.offset = offset; + this.length = length; + find(); + } + + private void find() { + for(;length != 0 && !iters[offset].hasNext();length--, offset++); + } + + @Override + public boolean hasNext() { + return length > 0; + } + + @Override + public KEY_TYPE NEXT() { + if(!hasNext()) throw new NoSuchElementException(); + KEY_TYPE result = iters[lastOffset = offset].NEXT(); + find(); + return result; + } + + @Override + public void remove() { + if(lastOffset == -1) throw new IllegalStateException(); + iters[lastOffset].remove(); + lastOffset = -1; + } + } + + private static class ReverseBiIterator KEY_GENERIC_TYPE implements BI_ITERATOR KEY_GENERIC_TYPE { + BI_ITERATOR KEY_GENERIC_TYPE it; + + ReverseBiIterator(BI_ITERATOR KEY_GENERIC_TYPE it) { + this.it = it; + } + + @Override + public KEY_TYPE NEXT() { return it.PREVIOUS(); } + @Override + public boolean hasNext() { return it.hasPrevious(); } + @Override + public boolean hasPrevious() { return it.hasNext(); } + @Override + public KEY_TYPE PREVIOUS() { return it.NEXT(); } + @Override + public void remove() { it.remove(); } + } + + private static class ReverseListIterator KEY_GENERIC_TYPE implements LIST_ITERATOR KEY_GENERIC_TYPE { + LIST_ITERATOR KEY_GENERIC_TYPE it; + + ReverseListIterator(LIST_ITERATOR KEY_GENERIC_TYPE it) { + this.it = it; + } + + @Override + public KEY_TYPE NEXT() { return it.PREVIOUS(); } + @Override + public boolean hasNext() { return it.hasPrevious(); } + @Override + public boolean hasPrevious() { return it.hasNext(); } + @Override + public KEY_TYPE PREVIOUS() { return it.NEXT(); } + @Override + public void remove() { it.remove(); } + @Override + public int nextIndex() { return it.previousIndex(); } + @Override + public int previousIndex() { return it.nextIndex(); } + @Override + public void set(KEY_TYPE e) { it.set(e); } + @Override + public void add(KEY_TYPE e) { it.add(e); } + } + + private static class UnmodifiableListIterator KEY_GENERIC_TYPE implements LIST_ITERATOR KEY_GENERIC_TYPE + { + LIST_ITERATOR KEY_GENERIC_TYPE iter; + + UnmodifiableListIterator(LIST_ITERATOR KEY_GENERIC_TYPE iter) { + this.iter = iter; + } + + @Override + public boolean hasNext() { + return iter.hasNext(); + } + + @Override + public boolean hasPrevious() { + return iter.hasPrevious(); + } + + @Override + public int nextIndex() { + return iter.nextIndex(); + } + + @Override + public int previousIndex() { + return iter.previousIndex(); + } + + @Override + public void remove() { throw new UnsupportedOperationException(); } + + @Override + public KEY_TYPE PREVIOUS() { + return iter.PREVIOUS(); + } + + @Override + public KEY_TYPE NEXT() { + return iter.NEXT(); + } + + @Override + public void set(KEY_TYPE e) { throw new UnsupportedOperationException(); } + + @Override + public void add(KEY_TYPE e) { throw new UnsupportedOperationException(); } + } + + private static class UnmodifiableBiIterator KEY_GENERIC_TYPE implements BI_ITERATOR KEY_GENERIC_TYPE + { + BI_ITERATOR KEY_GENERIC_TYPE iter; + + UnmodifiableBiIterator(BI_ITERATOR KEY_GENERIC_TYPE iter) { + this.iter = iter; + } + + @Override + public KEY_TYPE NEXT() { + return iter.NEXT(); + } + + @Override + public boolean hasNext() { + return iter.hasNext(); + } + + @Override + public boolean hasPrevious() { + return iter.hasPrevious(); + } + + @Override + public KEY_TYPE PREVIOUS() { + return iter.PREVIOUS(); + } + } + + private static class UnmodifiableIterator KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE + { + ITERATOR KEY_GENERIC_TYPE iterator; + + UnmodifiableIterator(ITERATOR KEY_GENERIC_TYPE iterator) { + this.iterator = iterator; + } + + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + + @Override + public KEY_TYPE NEXT() { + return iterator.NEXT(); + } + } + + private static class EmptyIterator KEY_GENERIC_TYPE implements LIST_ITERATOR KEY_GENERIC_TYPE + { + @Override + public boolean hasNext() { return false; } + @Override + public KEY_TYPE NEXT() { throw new NoSuchElementException(); } + @Override + public boolean hasPrevious() { return false; } + @Override + public KEY_TYPE PREVIOUS() { throw new NoSuchElementException(); } + @Override + public int nextIndex() { return 0; } + @Override + public int previousIndex() { return -1; } + @Override + public void remove() { throw new UnsupportedOperationException(); } + @Override + public void set(KEY_TYPE e) { throw new UnsupportedOperationException(); } + @Override + public void add(KEY_TYPE e) { throw new UnsupportedOperationException(); } + } + + private static class ArrayIterator KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE + { + KEY_TYPE[] a; + int from; + int to; + + ArrayIterator(KEY_TYPE[] a, int from, int to) { + this.a = a; + this.from = from; + this.to = to; + } + + @Override + public boolean hasNext() { + return from < to; + } + + @Override + public KEY_TYPE NEXT() { + if(!hasNext()) throw new NoSuchElementException(); + return a[from++]; + } + + @Override + public int skip(int amount) { + if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed"); + int left = Math.min(amount, to - from); + from += left; + return amount - left; + } + } + + private static class MappedIterator KSS_GENERIC_TYPE implements ObjectIterator + { + ITERATOR KEY_SPECIAL_GENERIC_TYPE iterator; + TO_OBJECT_FUNCTION KSS_GENERIC_TYPE mapper; + + MappedIterator(ITERATOR KEY_SPECIAL_GENERIC_TYPE iterator, TO_OBJECT_FUNCTION KSS_GENERIC_TYPE mapper) { + this.iterator = iterator; + this.mapper = mapper; + } + + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + + @Override + public T next() { + return mapper.apply(iterator.NEXT()); + } + + @Override + public int skip(int amount) { + return iterator.skip(amount); + } + } + + private static class FlatMappedIterator KSS_GENERIC_TYPE> implements ObjectIterator + { + ITERATOR KEY_SPECIAL_GENERIC_TYPE iterator; + Iterator last = null; + TO_OBJECT_FUNCTION KSS_GENERIC_TYPE mapper; + boolean foundNext = false; + + FlatMappedIterator(ITERATOR KEY_SPECIAL_GENERIC_TYPE iterator, TO_OBJECT_FUNCTION KSS_GENERIC_TYPE mapper) { + this.iterator = iterator; + this.mapper = mapper; + } + + void compute() { + if(foundNext) return; + foundNext = true; + while(iterator.hasNext()) { + if(last != null && last.hasNext()) return; + last = mapper.apply(iterator.NEXT()).iterator(); + } + } + + @Override + public boolean hasNext() { + compute(); + return last != null && last.hasNext(); + } + + @Override + public T next() { + if(!hasNext()) throw new NoSuchElementException(); + T result = last.next(); + foundNext = false; + return result; + } + } + + private static class FlatMappedArrayIterator KSS_GENERIC_TYPE implements ObjectIterator + { + ITERATOR KEY_SPECIAL_GENERIC_TYPE iterator; + Iterator last = null; + TO_OBJECT_FUNCTION KSS_GENERIC_TYPE mapper; + boolean foundNext = false; + + FlatMappedArrayIterator(ITERATOR KEY_SPECIAL_GENERIC_TYPE iterator, TO_OBJECT_FUNCTION KSS_GENERIC_TYPE mapper) { + this.iterator = iterator; + this.mapper = mapper; + } + + void compute() { + if(foundNext) return; + foundNext = true; + while(iterator.hasNext()) { + if(last != null && last.hasNext()) return; + last = ObjectIterators.wrap(mapper.apply(iterator.NEXT())); + } + } + + @Override + public boolean hasNext() { + compute(); + return last != null && last.hasNext(); + } + + @Override + public T next() { + if(!hasNext()) throw new NoSuchElementException(); + T result = last.next(); + foundNext = false; + return result; + } + } + + private static class RepeatingIterator KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE + { + final int repeats; + int index = 0; + ITERATOR KEY_GENERIC_TYPE iter; + COLLECTION KEY_GENERIC_TYPE repeater = COLLECTIONS.wrapper(); + + public RepeatingIterator(ITERATOR KEY_GENERIC_TYPE iter, int repeat) { + this.iter = iter; + this.repeats = repeat; + } + + @Override + public boolean hasNext() { + if(iter.hasNext()) return true; + if(index < repeats) { + index++; + iter = repeater.iterator(); + return iter.hasNext(); + } + return false; + } + + @Override + public KEY_TYPE NEXT() { + if(!hasNext()) throw new NoSuchElementException(); + KEY_TYPE value = iter.NEXT(); + if(index == 0) repeater.add(value); + return value; + } + } + + private static class SortedIterator KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE + { + ITERATOR KEY_GENERIC_TYPE iterator; + COMPARATOR KEY_GENERIC_TYPE sorter; + COLLECTIONS.CollectionWrapper KEY_GENERIC_TYPE sortedElements = null; + int index = 0; + + public SortedIterator(ITERATOR KEY_GENERIC_TYPE iterator, COMPARATOR KEY_GENERIC_TYPE sorter) { + this.iterator = iterator; + this.sorter = sorter; + } + + @Override + public boolean hasNext() { + if(sortedElements == null) { + boolean hasNext = iterator.hasNext(); + if(hasNext) { + sortedElements = COLLECTIONS.wrapper(); + pour(iterator, sortedElements); + } + else sortedElements = COLLECTIONS.wrapper(); + if(hasNext) sortedElements.unstableSort(sorter); + } + return index < sortedElements.size(); + } + + @Override + public KEY_TYPE NEXT() { + if(!hasNext()) throw new NoSuchElementException(); + return sortedElements.GET_KEY(index++); + } + } + + private static class DistinctIterator KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE + { + ITERATOR KEY_GENERIC_TYPE iterator; +#if TYPE_BOOLEAN + int filtered; +#else + COLLECTION KEY_GENERIC_TYPE filtered = COLLECTIONS.distinctWrapper(); +#endif + KEY_TYPE lastFound; + boolean foundNext = false; + + public DistinctIterator(ITERATOR KEY_GENERIC_TYPE iterator) { + this.iterator = iterator; + } + + void compute() { + if(foundNext) return; +#if TYPE_BOOLEAN + if(filtered == 3) return; +#endif + while(iterator.hasNext()) { + lastFound = iterator.NEXT(); +#if TYPE_BOOLEAN + if((filtered & (lastFound ? 1 : 2)) == 0) { + filtered |= (lastFound ? 1 : 2); + foundNext = true; + break; + } +#else + if(filtered.add(lastFound)) { + foundNext = true; + break; + } +#endif + } + } + + @Override + public boolean hasNext() { + compute(); + return foundNext; + } + + @Override + public KEY_TYPE NEXT() { + if(!hasNext()) throw new NoSuchElementException(); + foundNext = false; + return lastFound; + } + } + + private static class FilteredIterator KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE + { + ITERATOR KEY_GENERIC_TYPE iterator; + PREDICATE KEY_GENERIC_TYPE filter; + KEY_TYPE lastFound; + boolean foundNext = false; + + public FilteredIterator(ITERATOR KEY_GENERIC_TYPE iterator, PREDICATE KEY_GENERIC_TYPE filter) { + this.iterator = iterator; + this.filter = filter; + } + + void compute() { + if(foundNext) return; + while(iterator.hasNext()) { + lastFound = iterator.NEXT(); + if(filter.test(lastFound)) { + foundNext = true; + break; + } + } + } + + @Override + public boolean hasNext() { + compute(); + return foundNext; + } + + @Override + public KEY_TYPE NEXT() { + if(!hasNext()) throw new NoSuchElementException(); + foundNext = false; + return lastFound; + } + } + + private static class LimitedIterator KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE + { + ITERATOR KEY_GENERIC_TYPE iterator; + long limit; + + public LimitedIterator(ITERATOR KEY_GENERIC_TYPE iterator, long limit) { + this.iterator = iterator; + this.limit = limit; + } + + @Override + public boolean hasNext() { + return limit > 0 && iterator.hasNext(); + } + + @Override + public KEY_TYPE NEXT() { + if(!hasNext()) throw new NoSuchElementException(); + limit--; + return iterator.NEXT(); + } + } + + private static class PeekIterator KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE + { + ITERATOR KEY_GENERIC_TYPE iterator; + CONSUMER KEY_GENERIC_TYPE action; + + public PeekIterator(ITERATOR KEY_GENERIC_TYPE iterator, CONSUMER KEY_GENERIC_TYPE action) { + this.iterator = iterator; + this.action = action; + } + + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + + @Override + public KEY_TYPE NEXT() { + if(!hasNext()) throw new NoSuchElementException(); + KEY_TYPE result = iterator.NEXT(); + action.accept(result); + return result; + } + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/collections/templates/utils/Lists.template b/src/builder/resources/speiger/assets/collections/templates/utils/Lists.template index 70d59c1..5ba3fc6 100644 --- a/src/builder/resources/speiger/assets/collections/templates/utils/Lists.template +++ b/src/builder/resources/speiger/assets/collections/templates/utils/Lists.template @@ -1,648 +1,645 @@ -package speiger.src.collections.PACKAGE.utils; - -import java.util.Collection; -import java.util.List; -#if IARRAY_FEATURE -import java.util.Objects; -#endif -#if JAVA_VERSION>=17 -import java.util.random.RANDOM; -#else -import java.util.RANDOM; -#endif -import java.util.RandomAccess; -#if IARRAY_FEATURE || TYPE_OBJECT -import java.util.function.Consumer; -#endif -#if PRIMITIVES -import java.nio.JAVA_BUFFER; -#endif - -import speiger.src.collections.PACKAGE.collections.COLLECTION; -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.functions.CONSUMER; -#endif -import speiger.src.collections.PACKAGE.lists.ABSTRACT_LIST; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; -#if IARRAY_FEATURE -import speiger.src.collections.PACKAGE.utils.ARRAYS; -#endif -import speiger.src.collections.utils.SanityChecks; - -/** - * A Helper class for Lists - */ -public class LISTS -{ - /** - * Empty List reference - */ - private static final EmptyList NO_GENERIC_TYPE EMPTY = new EmptyListBRACES(); - - /** - * Returns a Immutable EmptyList instance that is automatically casted. - * @Type(T) - * @return an empty list - */ - public static GENERIC_KEY_BRACES EmptyList KEY_GENERIC_TYPE empty() { -#if TYPE_OBJECT - return (EmptyList)EMPTY; -#else - return EMPTY; -#endif - } - - /** - * Returns a Immutable List instance based on the instance given. - * @param l that should be made immutable/unmodifiable - * @Type(T) - * @return a unmodifiable list wrapper. If the list is implementing RandomAccess that is also transferred. If the List already a unmodifiable wrapper then it just returns itself. - */ - public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE unmodifiable(LIST KEY_GENERIC_TYPE l) { - return l instanceof UnmodifiableList ? l : l instanceof RandomAccess ? new UnmodifiableRandomListBRACES(l) : new UnmodifiableListBRACES(l); - } - - /** - * Returns a synchronized List instance based on the instance given. - * @param l that should be synchronized - * @Type(T) - * @return a synchronized list wrapper. If the list is implementing RandomAccess or IARRAY that is also transferred. If the List already a synchronized wrapper then it just returns itself. - */ - public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE synchronize(LIST KEY_GENERIC_TYPE l) { -#if IARRAY_FEATURE - return l instanceof SynchronizedList ? l : (l instanceof IARRAY ? new SynchronizedArrayListBRACES(l) : (l instanceof RandomAccess ? new SynchronizedRandomAccessListBRACES(l) : new SynchronizedListBRACES(l))); -#else - return l instanceof SynchronizedList ? l : (l instanceof RandomAccess ? new SynchronizedRandomAccessListBRACES(l) : new SynchronizedListBRACES(l)); -#endif - } - - /** - * Returns a synchronized List instance based on the instance given. - * @param l that should be synchronized - * @param mutex is the controller of the synchronization block. - * @Type(T) - * @return a synchronized list wrapper. If the list is implementing RandomAccess or IARRAY that is also transferred. If the List already a synchronized wrapper then it just returns itself. - */ - public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE synchronize(LIST KEY_GENERIC_TYPE l, Object mutex) { -#if IARRAY_FEATURE - return l instanceof SynchronizedList ? l : (l instanceof IARRAY ? new SynchronizedArrayListBRACES(l, mutex) : (l instanceof RandomAccess ? new SynchronizedRandomAccessListBRACES(l, mutex) : new SynchronizedListBRACES(l, mutex))); -#else - return l instanceof SynchronizedList ? l : (l instanceof RandomAccess ? new SynchronizedRandomAccessListBRACES(l, mutex) : new SynchronizedListBRACES(l, mutex)); -#endif - } - - /** - * Creates a Unmodifiable Singleton list - * @param element that should be used in the Singleton - * @Type(T) - * @return a singleton list that is unmodifiable - */ - public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE singleton(KEY_TYPE element) { - return new SingletonListBRACES(element); - } - - /** - * Reverses the list - * @param list that should be reversed. - * @Type(T) - * @return the input list - */ - public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE reverse(LIST KEY_GENERIC_TYPE list) { - int size = list.size(); -#if IARRAY_FEATURE - if(list instanceof IARRAY) { - IARRAY KEY_GENERIC_TYPE array = (IARRAY KEY_GENERIC_TYPE)list; -#if TYPE_OBJECT - if(array.isCastable()) { - if(list instanceof SynchronizedArrayList) array.elements(T -> ARRAYS.reverse(T, size)); - else ARRAYS.reverse(array.elements(), size); - return list; - } -#else - if(list instanceof SynchronizedArrayList) array.elements(T -> ARRAYS.reverse(T, size)); - else ARRAYS.reverse(array.elements(), size); - return list; -#endif - } -#endif - if(list instanceof RandomAccess) { - for (int i = 0, mid = size >> 1, j = size - 1; i < mid; i++, j--) { - KEY_TYPE t = list.GET_KEY(i); - list.set(i, list.GET_KEY(j)); - list.set(j, t); - } - return list; - } - LIST_ITERATOR KEY_GENERIC_TYPE fwd = list.listIterator(); - LIST_ITERATOR KEY_GENERIC_TYPE rev = list.listIterator(size); - for(int i = 0, mid = size >> 1; i < mid; i++) { - KEY_TYPE tmp = fwd.NEXT(); - fwd.set(rev.PREVIOUS()); - rev.set(tmp); - } - return list; - } - - /** - * Shuffles the list - * @param list that should be Shuffled. - * @Type(T) - * @return the input list - */ - public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE shuffle(LIST KEY_GENERIC_TYPE list) { - return shuffle(list, SanityChecks.getRandom()); - } - - /** - * Shuffles the list - * @param list that should be Shuffled. - * @param random the random that should be used - * @Type(T) - * @return the input list - */ - public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE shuffle(LIST KEY_GENERIC_TYPE list, RANDOM random) { - int size = list.size(); -#if IARRAY_FEATURE - if(list instanceof IARRAY) { - IARRAY KEY_GENERIC_TYPE array = (IARRAY KEY_GENERIC_TYPE)list; -#if TYPE_OBJECT - if(array.isCastable()) { - if(list instanceof SynchronizedArrayList) array.elements(T -> ARRAYS.shuffle(T, size, random)); - else ARRAYS.shuffle(array.elements(), size, random); - } - else { - for(int i = list.size(); i-- != 0;) { - int p = random.nextInt(i + 1); - KEY_TYPE t = list.GET_KEY(i); - list.set(i, list.GET_KEY(p)); - list.set(p, t); - } - } -#else - if(list instanceof SynchronizedArrayList) array.elements(T -> ARRAYS.shuffle(T, size, random)); - else ARRAYS.shuffle(array.elements(), size, random); -#endif - return list; - } -#endif - for(int i = size; i-- != 0;) { - int p = random.nextInt(i + 1); - KEY_TYPE t = list.GET_KEY(i); - list.set(i, list.GET_KEY(p)); - list.set(p, t); - } - return list; - } - - private static class SingletonList KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE - { - KEY_TYPE element; - - SingletonList(KEY_TYPE element) - { - this.element = element; - } - @Override - public void add(int index, KEY_TYPE e) { throw new UnsupportedOperationException(); } - @Override - public boolean addAll(int index, Collection c) { throw new UnsupportedOperationException(); } - @Override - public boolean addAll(int index, COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } - @Override - public boolean addAll(int index, LIST KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } - - @Override - public KEY_TYPE GET_KEY(int index) { - if(index == 0) return element; - throw new IndexOutOfBoundsException(); - } - - @Override - public KEY_TYPE set(int index, KEY_TYPE e) { throw new UnsupportedOperationException(); } - @Override - public KEY_TYPE REMOVE(int index) { throw new UnsupportedOperationException(); } - @Override - public KEY_TYPE swapRemove(int index) { throw new UnsupportedOperationException(); } - @Override - public void addElements(int from, KEY_TYPE[] a, int offset, int length) { throw new UnsupportedOperationException(); } - @Override - public KEY_TYPE[] getElements(int from, KEY_TYPE[] a, int offset, int length) { - if(from != 0 || length != 1) throw new IndexOutOfBoundsException(); - a[offset] = element; - return a; - } -#if PRIMITIVES - @Override - public void fillBuffer(JAVA_BUFFER buffer) { buffer.put(element); } -#endif - - @Override - public void removeElements(int from, int to) { throw new UnsupportedOperationException(); } -#if TYPE_OBJECT - @Override - public K[] extractElements(int from, int to, Class type) { throw new UnsupportedOperationException(); } -#else - @Override - public KEY_TYPE[] extractElements(int from, int to) { throw new UnsupportedOperationException(); } -#endif - @Override - public int size() { return 1; } - - @Override - public SingletonList KEY_GENERIC_TYPE copy() { return new SingletonListBRACES(element); } - } - -#if IARRAY_FEATURE - private static class SynchronizedArrayList KEY_GENERIC_TYPE extends SynchronizedList KEY_GENERIC_TYPE implements IARRAY KEY_GENERIC_TYPE - { - IARRAY KEY_GENERIC_TYPE l; - - SynchronizedArrayList(LIST KEY_GENERIC_TYPE l) { - super(l); - this.l = (IARRAY KEY_GENERIC_TYPE)l; - } - - SynchronizedArrayList(LIST KEY_GENERIC_TYPE l, Object mutex) { - super(l, mutex); - this.l = (IARRAY KEY_GENERIC_TYPE)l; - } - - @Override - public void ensureCapacity(int size) { synchronized(mutex) { l.ensureCapacity(size); } } - - @Override - public boolean trim(int size) { synchronized(mutex) { return l.trim(size); } } - - @Override - public void clearAndTrim(int size) { synchronized(mutex) { l.clearAndTrim(size); } } - - @Override - public KEY_TYPE[] elements() { synchronized(mutex) { return l.elements(); } } - -#if TYPE_OBJECT - @Override - public boolean isCastable() { synchronized(mutex) { return l.isCastable(); } } - -#endif - @Override - public void elements(Consumer action) { - Objects.requireNonNull(action); - synchronized(mutex) { - l.elements(action); - } - } - } - -#endif - private static class SynchronizedRandomAccessList KEY_GENERIC_TYPE extends SynchronizedList KEY_GENERIC_TYPE implements RandomAccess - { - SynchronizedRandomAccessList(LIST KEY_GENERIC_TYPE l) { - super(l); - } - - SynchronizedRandomAccessList(LIST KEY_GENERIC_TYPE l, Object mutex) { - super(l, mutex); - } - } - - private static class SynchronizedList KEY_GENERIC_TYPE extends COLLECTIONS.SynchronizedCollection KEY_GENERIC_TYPE implements LIST KEY_GENERIC_TYPE - { - LIST KEY_GENERIC_TYPE l; - - SynchronizedList(LIST KEY_GENERIC_TYPE l) { - super(l); - this.l = l; - } - - SynchronizedList(LIST KEY_GENERIC_TYPE l, Object mutex) { - super(l, mutex); - this.l = l; - } - - @Override - public boolean addAll(int index, Collection c) { synchronized(mutex) { return l.addAll(index, c); } } - - @Override - public void add(int index, CLASS_TYPE element) { synchronized(mutex) { l.add(index, element); } } - -#if !TYPE_OBJECT - @Override - public void add(int index, KEY_TYPE e) { synchronized(mutex) { l.add(index, e); } } - -#endif - @Override - public boolean addAll(int index, COLLECTION KEY_GENERIC_TYPE c) { synchronized(mutex) { return l.addAll(index, c); } } - - @Override - public boolean addAll(LIST KEY_GENERIC_TYPE c) { synchronized(mutex) { return l.addAll(c); } } - - @Override - public boolean addAll(int index, LIST KEY_GENERIC_TYPE c) { synchronized(mutex) { return l.addAll(index, c); } } - - @Override - public KEY_TYPE GET_KEY(int index) { synchronized(mutex) { return l.GET_KEY(index); } } - -#if !TYPE_OBJECT - @Override - public void forEach(CONSUMER action) { synchronized(mutex) { l.forEach(action); } } - -#else - @Override - public void forEach(Consumer action) { synchronized(mutex) { l.forEach(action); } } - -#endif - @Override - public KEY_TYPE set(int index, KEY_TYPE e) { synchronized(mutex) { return l.set(index, e); } } - - @Override - public KEY_TYPE REMOVE(int index) { synchronized(mutex) { return l.REMOVE(index); } } - - @Override - public KEY_TYPE swapRemove(int index) { synchronized(mutex) { return l.swapRemove(index); } } - - @Override - public boolean REMOVE_SWAP(KEY_TYPE e) { synchronized(mutex) { return l.REMOVE_SWAP(e); } } - - @Override - @Primitive - public int indexOf(Object e) { synchronized(mutex) { return l.indexOf(e); } } - - @Override - @Primitive - public int lastIndexOf(Object e) { synchronized(mutex) { return l.lastIndexOf(e); } } - -#if !TYPE_OBJECT - @Override - public int indexOf(KEY_TYPE e) { synchronized(mutex) { return l.indexOf(e); } } - - @Override - public int lastIndexOf(KEY_TYPE e) { synchronized(mutex) { return l.lastIndexOf(e); } } - -#endif - @Override - public void addElements(int from, KEY_TYPE[] a, int offset, int length) { synchronized(mutex) { l.addElements(from, a, offset, length); } } - - @Override - public KEY_TYPE[] getElements(int from, KEY_TYPE[] a, int offset, int length) { synchronized(mutex) { return l.getElements(from, a, offset, length); } } - - @Override - public void removeElements(int from, int to) { synchronized(mutex) { l.removeElements(from, to); } } - -#if !TYPE_OBJECT - @Override - public KEY_TYPE[] extractElements(int from, int to) { synchronized(mutex) { return l.extractElements(from, to); } } - -#else - @Override - public K[] extractElements(int from, int to, Class clz) { synchronized(mutex) { return l.extractElements(from, to, clz); } } - -#endif -#if PRIMITIVES - public void fillBuffer(JAVA_BUFFER buffer) { synchronized(mutex) { l.fillBuffer(buffer); } } -#endif - @Override - public LIST_ITERATOR KEY_GENERIC_TYPE listIterator() { - return l.listIterator(); - } - - @Override - public LIST_ITERATOR KEY_GENERIC_TYPE listIterator(int index) { - return l.listIterator(index); - } - - @Override - public LIST KEY_GENERIC_TYPE subList(int from, int to) { - return LISTS.synchronize(l.subList(from, to)); - } - - @Override - public void size(int size) { synchronized(mutex) { l.size(size); } } - - @Override - public LIST KEY_GENERIC_TYPE copy() { synchronized(mutex) { return l.copy(); } } - } - - private static class UnmodifiableRandomList KEY_GENERIC_TYPE extends UnmodifiableList KEY_GENERIC_TYPE implements RandomAccess - { - UnmodifiableRandomList(LIST KEY_GENERIC_TYPE l) { - super(l); - } - } - - private static class UnmodifiableList KEY_GENERIC_TYPE extends COLLECTIONS.UnmodifiableCollection KEY_GENERIC_TYPE implements LIST KEY_GENERIC_TYPE - { - final LIST KEY_GENERIC_TYPE l; - - UnmodifiableList(LIST KEY_GENERIC_TYPE l) { - super(l); - this.l = l; - } - - @Override - public boolean addAll(int index, Collection c) { throw new UnsupportedOperationException(); } - - @Override - public void add(int index, CLASS_TYPE element) { throw new UnsupportedOperationException(); } - -#if !TYPE_OBJECT - @Override - public void add(int index, KEY_TYPE e) { throw new UnsupportedOperationException(); } - -#endif - @Override - public boolean addAll(int index, COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } - - @Override - public boolean addAll(LIST KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } - - @Override - public boolean addAll(int index, LIST KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } - - @Override - public KEY_TYPE GET_KEY(int index) { return l.GET_KEY(index); } - -#if !TYPE_OBJECT - @Override - public void forEach(CONSUMER action) { l.forEach(action); } - -#else - @Override - public void forEach(Consumer action) { l.forEach(action); } - -#endif - @Override - public KEY_TYPE set(int index, KEY_TYPE e) { throw new UnsupportedOperationException(); } - - @Override - public KEY_TYPE REMOVE(int index) { throw new UnsupportedOperationException(); } - - @Override - public KEY_TYPE swapRemove(int index) { throw new UnsupportedOperationException(); } - - @Override - public boolean REMOVE_SWAP(KEY_TYPE e) { throw new UnsupportedOperationException(); } - - @Override - @Primitive - public int indexOf(Object e) { return l.indexOf(e); } - - @Override - @Primitive - public int lastIndexOf(Object e) { return l.lastIndexOf(e); } - -#if !TYPE_OBJECT - @Override - public int indexOf(KEY_TYPE e) { return l.indexOf(e); } - - @Override - public int lastIndexOf(KEY_TYPE e) { return l.lastIndexOf(e); } - -#endif - @Override - public void addElements(int from, KEY_TYPE[] a, int offset, int length) { throw new UnsupportedOperationException(); } - - @Override - public KEY_TYPE[] getElements(int from, KEY_TYPE[] a, int offset, int length) { - return l.getElements(from, a, offset, length); - } - - @Override - public void removeElements(int from, int to) { throw new UnsupportedOperationException(); } - -#if !TYPE_OBJECT - @Override - public KEY_TYPE[] extractElements(int from, int to) { throw new UnsupportedOperationException(); } - -#else - @Override - public K[] extractElements(int from, int to, Class clz) { throw new UnsupportedOperationException(); } - -#endif -#if PRIMITIVES - public void fillBuffer(JAVA_BUFFER buffer) { l.fillBuffer(buffer); } - -#endif - @Override - public LIST_ITERATOR KEY_GENERIC_TYPE listIterator() { - return ITERATORS.unmodifiable(l.listIterator()); - } - - @Override - public LIST_ITERATOR KEY_GENERIC_TYPE listIterator(int index) { - return ITERATORS.unmodifiable(l.listIterator(index)); - } - - @Override - public LIST KEY_GENERIC_TYPE subList(int from, int to) { - return LISTS.unmodifiable(l.subList(from, to)); - } - - @Override - public void size(int size) { throw new UnsupportedOperationException(); } - - @Override - public LIST KEY_GENERIC_TYPE copy() { return l.copy(); } - } - - private static class EmptyList KEY_GENERIC_TYPE extends COLLECTIONS.EmptyCollection KEY_GENERIC_TYPE implements LIST KEY_GENERIC_TYPE - { - @Override - public boolean addAll(int index, Collection c) { throw new UnsupportedOperationException(); } - - @Override - public void add(int index, CLASS_TYPE element) { throw new UnsupportedOperationException(); } - -#if !TYPE_OBJECT - @Override - public void add(int index, KEY_TYPE e) { throw new UnsupportedOperationException(); } - -#endif - @Override - public boolean addAll(int index, COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } - - @Override - public boolean addAll(LIST KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } - - @Override - public boolean addAll(int index, LIST KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } - - @Override - public KEY_TYPE GET_KEY(int index) { throw new IndexOutOfBoundsException(); } - - @Override - public KEY_TYPE set(int index, KEY_TYPE e) { throw new UnsupportedOperationException(); } - - @Override - public KEY_TYPE REMOVE(int index) { throw new UnsupportedOperationException(); } - - @Override - public KEY_TYPE swapRemove(int index) { throw new UnsupportedOperationException(); } - - @Override - public boolean REMOVE_SWAP(KEY_TYPE e) { throw new UnsupportedOperationException(); } - - @Override - public int indexOf(Object e) { return -1; } - - @Override - public int lastIndexOf(Object e) { return -1; } - -#if !TYPE_OBJECT - @Override - public int indexOf(KEY_TYPE e) { return -1; } - - @Override - public int lastIndexOf(KEY_TYPE e) { return -1; } - -#endif - @Override - public void addElements(int from, KEY_TYPE[] a, int offset, int length){ throw new UnsupportedOperationException(); } - - @Override - public KEY_TYPE[] getElements(int from, KEY_TYPE[] a, int offset, int length) { throw new IndexOutOfBoundsException(); } - - @Override - public void removeElements(int from, int to) { throw new UnsupportedOperationException(); } - -#if !TYPE_OBJECT - @Override - public KEY_TYPE[] extractElements(int from, int to) { throw new UnsupportedOperationException(); } - -#else - @Override - public K[] extractElements(int from, int to, Class clz) { throw new UnsupportedOperationException(); } - -#endif - @Override - public LIST_ITERATOR KEY_GENERIC_TYPE listIterator() { - return ITERATORS.empty(); - } - - @Override - public LIST_ITERATOR KEY_GENERIC_TYPE listIterator(int index) { - if(index != 0) - throw new IndexOutOfBoundsException(); - return ITERATORS.empty(); - } - - @Override - public int hashCode() { return 1; } - - @Override - public boolean equals(Object o) { - if(o == this) return true; - if(!(o instanceof List)) return false; - return ((List)o).isEmpty(); - } - - @Override - public LIST KEY_GENERIC_TYPE subList(int from, int to) { throw new UnsupportedOperationException(); } - - @Override - public void size(int size) { throw new UnsupportedOperationException(); } - - @Override - public EmptyList KEY_GENERIC_TYPE copy() { return this; } - } -} +package speiger.src.collections.PACKAGE.utils; + +import java.util.Collection; +import java.util.List; +#if IARRAY_FEATURE +import java.util.Objects; +#endif +#if JAVA_VERSION>=17 +import java.util.random.RANDOM; +#else +import java.util.RANDOM; +#endif +import java.util.RandomAccess; +#if IARRAY_FEATURE || TYPE_OBJECT +import java.util.function.Consumer; +#endif +#if PRIMITIVES +import java.nio.JAVA_BUFFER; +#endif + +import speiger.src.collections.PACKAGE.collections.COLLECTION; +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.functions.CONSUMER; +#endif +import speiger.src.collections.PACKAGE.lists.ABSTRACT_LIST; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; +import speiger.src.collections.utils.SanityChecks; + +/** + * A Helper class for Lists + */ +public class LISTS +{ + /** + * Empty List reference + */ + private static final EmptyList NO_GENERIC_TYPE EMPTY = new EmptyListBRACES(); + + /** + * Returns a Immutable EmptyList instance that is automatically casted. + * @Type(T) + * @return an empty list + */ + public static GENERIC_KEY_BRACES EmptyList KEY_GENERIC_TYPE empty() { +#if TYPE_OBJECT + return (EmptyList)EMPTY; +#else + return EMPTY; +#endif + } + + /** + * Returns a Immutable List instance based on the instance given. + * @param l that should be made immutable/unmodifiable + * @Type(T) + * @return a unmodifiable list wrapper. If the list is implementing RandomAccess that is also transferred. If the List already a unmodifiable wrapper then it just returns itself. + */ + public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE unmodifiable(LIST KEY_GENERIC_TYPE l) { + return l instanceof UnmodifiableList ? l : l instanceof RandomAccess ? new UnmodifiableRandomListBRACES(l) : new UnmodifiableListBRACES(l); + } + + /** + * Returns a synchronized List instance based on the instance given. + * @param l that should be synchronized + * @Type(T) + * @return a synchronized list wrapper. If the list is implementing RandomAccess or IARRAY that is also transferred. If the List already a synchronized wrapper then it just returns itself. + */ + public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE synchronize(LIST KEY_GENERIC_TYPE l) { +#if IARRAY_FEATURE + return l instanceof SynchronizedList ? l : (l instanceof IARRAY ? new SynchronizedArrayListBRACES(l) : (l instanceof RandomAccess ? new SynchronizedRandomAccessListBRACES(l) : new SynchronizedListBRACES(l))); +#else + return l instanceof SynchronizedList ? l : (l instanceof RandomAccess ? new SynchronizedRandomAccessListBRACES(l) : new SynchronizedListBRACES(l)); +#endif + } + + /** + * Returns a synchronized List instance based on the instance given. + * @param l that should be synchronized + * @param mutex is the controller of the synchronization block. + * @Type(T) + * @return a synchronized list wrapper. If the list is implementing RandomAccess or IARRAY that is also transferred. If the List already a synchronized wrapper then it just returns itself. + */ + public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE synchronize(LIST KEY_GENERIC_TYPE l, Object mutex) { +#if IARRAY_FEATURE + return l instanceof SynchronizedList ? l : (l instanceof IARRAY ? new SynchronizedArrayListBRACES(l, mutex) : (l instanceof RandomAccess ? new SynchronizedRandomAccessListBRACES(l, mutex) : new SynchronizedListBRACES(l, mutex))); +#else + return l instanceof SynchronizedList ? l : (l instanceof RandomAccess ? new SynchronizedRandomAccessListBRACES(l, mutex) : new SynchronizedListBRACES(l, mutex)); +#endif + } + + /** + * Creates a Unmodifiable Singleton list + * @param element that should be used in the Singleton + * @Type(T) + * @return a singleton list that is unmodifiable + */ + public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE singleton(KEY_TYPE element) { + return new SingletonListBRACES(element); + } + + /** + * Reverses the list + * @param list that should be reversed. + * @Type(T) + * @return the input list + */ + public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE reverse(LIST KEY_GENERIC_TYPE list) { + int size = list.size(); +#if IARRAY_FEATURE + if(list instanceof IARRAY) { + IARRAY KEY_GENERIC_TYPE array = (IARRAY KEY_GENERIC_TYPE)list; +#if TYPE_OBJECT + if(array.isCastable()) { + if(list instanceof SynchronizedArrayList) array.elements(T -> ARRAYS.reverse(T, size)); + else ARRAYS.reverse(array.elements(), size); + return list; + } +#else + if(list instanceof SynchronizedArrayList) array.elements(T -> ARRAYS.reverse(T, size)); + else ARRAYS.reverse(array.elements(), size); + return list; +#endif + } +#endif + if(list instanceof RandomAccess) { + for (int i = 0, mid = size >> 1, j = size - 1; i < mid; i++, j--) { + KEY_TYPE t = list.GET_KEY(i); + list.set(i, list.GET_KEY(j)); + list.set(j, t); + } + return list; + } + LIST_ITERATOR KEY_GENERIC_TYPE fwd = list.listIterator(); + LIST_ITERATOR KEY_GENERIC_TYPE rev = list.listIterator(size); + for(int i = 0, mid = size >> 1; i < mid; i++) { + KEY_TYPE tmp = fwd.NEXT(); + fwd.set(rev.PREVIOUS()); + rev.set(tmp); + } + return list; + } + + /** + * Shuffles the list + * @param list that should be Shuffled. + * @Type(T) + * @return the input list + */ + public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE shuffle(LIST KEY_GENERIC_TYPE list) { + return shuffle(list, SanityChecks.getRandom()); + } + + /** + * Shuffles the list + * @param list that should be Shuffled. + * @param random the random that should be used + * @Type(T) + * @return the input list + */ + public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE shuffle(LIST KEY_GENERIC_TYPE list, RANDOM random) { + int size = list.size(); +#if IARRAY_FEATURE + if(list instanceof IARRAY) { + IARRAY KEY_GENERIC_TYPE array = (IARRAY KEY_GENERIC_TYPE)list; +#if TYPE_OBJECT + if(array.isCastable()) { + if(list instanceof SynchronizedArrayList) array.elements(T -> ARRAYS.shuffle(T, size, random)); + else ARRAYS.shuffle(array.elements(), size, random); + } + else { + for(int i = list.size(); i-- != 0;) { + int p = random.nextInt(i + 1); + KEY_TYPE t = list.GET_KEY(i); + list.set(i, list.GET_KEY(p)); + list.set(p, t); + } + } +#else + if(list instanceof SynchronizedArrayList) array.elements(T -> ARRAYS.shuffle(T, size, random)); + else ARRAYS.shuffle(array.elements(), size, random); +#endif + return list; + } +#endif + for(int i = size; i-- != 0;) { + int p = random.nextInt(i + 1); + KEY_TYPE t = list.GET_KEY(i); + list.set(i, list.GET_KEY(p)); + list.set(p, t); + } + return list; + } + + private static class SingletonList KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE + { + KEY_TYPE element; + + SingletonList(KEY_TYPE element) + { + this.element = element; + } + @Override + public void add(int index, KEY_TYPE e) { throw new UnsupportedOperationException(); } + @Override + public boolean addAll(int index, Collection c) { throw new UnsupportedOperationException(); } + @Override + public boolean addAll(int index, COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } + @Override + public boolean addAll(int index, LIST KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } + + @Override + public KEY_TYPE GET_KEY(int index) { + if(index == 0) return element; + throw new IndexOutOfBoundsException(); + } + + @Override + public KEY_TYPE set(int index, KEY_TYPE e) { throw new UnsupportedOperationException(); } + @Override + public KEY_TYPE REMOVE(int index) { throw new UnsupportedOperationException(); } + @Override + public KEY_TYPE swapRemove(int index) { throw new UnsupportedOperationException(); } + @Override + public void addElements(int from, KEY_TYPE[] a, int offset, int length) { throw new UnsupportedOperationException(); } + @Override + public KEY_TYPE[] getElements(int from, KEY_TYPE[] a, int offset, int length) { + if(from != 0 || length != 1) throw new IndexOutOfBoundsException(); + a[offset] = element; + return a; + } +#if PRIMITIVES + @Override + public void fillBuffer(JAVA_BUFFER buffer) { buffer.put(element); } +#endif + + @Override + public void removeElements(int from, int to) { throw new UnsupportedOperationException(); } +#if TYPE_OBJECT + @Override + public K[] extractElements(int from, int to, Class type) { throw new UnsupportedOperationException(); } +#else + @Override + public KEY_TYPE[] extractElements(int from, int to) { throw new UnsupportedOperationException(); } +#endif + @Override + public int size() { return 1; } + + @Override + public SingletonList KEY_GENERIC_TYPE copy() { return new SingletonListBRACES(element); } + } + +#if IARRAY_FEATURE + private static class SynchronizedArrayList KEY_GENERIC_TYPE extends SynchronizedList KEY_GENERIC_TYPE implements IARRAY KEY_GENERIC_TYPE + { + IARRAY KEY_GENERIC_TYPE l; + + SynchronizedArrayList(LIST KEY_GENERIC_TYPE l) { + super(l); + this.l = (IARRAY KEY_GENERIC_TYPE)l; + } + + SynchronizedArrayList(LIST KEY_GENERIC_TYPE l, Object mutex) { + super(l, mutex); + this.l = (IARRAY KEY_GENERIC_TYPE)l; + } + + @Override + public void ensureCapacity(int size) { synchronized(mutex) { l.ensureCapacity(size); } } + + @Override + public boolean trim(int size) { synchronized(mutex) { return l.trim(size); } } + + @Override + public void clearAndTrim(int size) { synchronized(mutex) { l.clearAndTrim(size); } } + + @Override + public KEY_TYPE[] elements() { synchronized(mutex) { return l.elements(); } } + +#if TYPE_OBJECT + @Override + public boolean isCastable() { synchronized(mutex) { return l.isCastable(); } } + +#endif + @Override + public void elements(Consumer action) { + Objects.requireNonNull(action); + synchronized(mutex) { + l.elements(action); + } + } + } + +#endif + private static class SynchronizedRandomAccessList KEY_GENERIC_TYPE extends SynchronizedList KEY_GENERIC_TYPE implements RandomAccess + { + SynchronizedRandomAccessList(LIST KEY_GENERIC_TYPE l) { + super(l); + } + + SynchronizedRandomAccessList(LIST KEY_GENERIC_TYPE l, Object mutex) { + super(l, mutex); + } + } + + private static class SynchronizedList KEY_GENERIC_TYPE extends COLLECTIONS.SynchronizedCollection KEY_GENERIC_TYPE implements LIST KEY_GENERIC_TYPE + { + LIST KEY_GENERIC_TYPE l; + + SynchronizedList(LIST KEY_GENERIC_TYPE l) { + super(l); + this.l = l; + } + + SynchronizedList(LIST KEY_GENERIC_TYPE l, Object mutex) { + super(l, mutex); + this.l = l; + } + + @Override + public boolean addAll(int index, Collection c) { synchronized(mutex) { return l.addAll(index, c); } } + + @Override + public void add(int index, CLASS_TYPE element) { synchronized(mutex) { l.add(index, element); } } + +#if !TYPE_OBJECT + @Override + public void add(int index, KEY_TYPE e) { synchronized(mutex) { l.add(index, e); } } + +#endif + @Override + public boolean addAll(int index, COLLECTION KEY_GENERIC_TYPE c) { synchronized(mutex) { return l.addAll(index, c); } } + + @Override + public boolean addAll(LIST KEY_GENERIC_TYPE c) { synchronized(mutex) { return l.addAll(c); } } + + @Override + public boolean addAll(int index, LIST KEY_GENERIC_TYPE c) { synchronized(mutex) { return l.addAll(index, c); } } + + @Override + public KEY_TYPE GET_KEY(int index) { synchronized(mutex) { return l.GET_KEY(index); } } + +#if !TYPE_OBJECT + @Override + public void forEach(CONSUMER action) { synchronized(mutex) { l.forEach(action); } } + +#else + @Override + public void forEach(Consumer action) { synchronized(mutex) { l.forEach(action); } } + +#endif + @Override + public KEY_TYPE set(int index, KEY_TYPE e) { synchronized(mutex) { return l.set(index, e); } } + + @Override + public KEY_TYPE REMOVE(int index) { synchronized(mutex) { return l.REMOVE(index); } } + + @Override + public KEY_TYPE swapRemove(int index) { synchronized(mutex) { return l.swapRemove(index); } } + + @Override + public boolean REMOVE_SWAP(KEY_TYPE e) { synchronized(mutex) { return l.REMOVE_SWAP(e); } } + + @Override + @Primitive + public int indexOf(Object e) { synchronized(mutex) { return l.indexOf(e); } } + + @Override + @Primitive + public int lastIndexOf(Object e) { synchronized(mutex) { return l.lastIndexOf(e); } } + +#if !TYPE_OBJECT + @Override + public int indexOf(KEY_TYPE e) { synchronized(mutex) { return l.indexOf(e); } } + + @Override + public int lastIndexOf(KEY_TYPE e) { synchronized(mutex) { return l.lastIndexOf(e); } } + +#endif + @Override + public void addElements(int from, KEY_TYPE[] a, int offset, int length) { synchronized(mutex) { l.addElements(from, a, offset, length); } } + + @Override + public KEY_TYPE[] getElements(int from, KEY_TYPE[] a, int offset, int length) { synchronized(mutex) { return l.getElements(from, a, offset, length); } } + + @Override + public void removeElements(int from, int to) { synchronized(mutex) { l.removeElements(from, to); } } + +#if !TYPE_OBJECT + @Override + public KEY_TYPE[] extractElements(int from, int to) { synchronized(mutex) { return l.extractElements(from, to); } } + +#else + @Override + public K[] extractElements(int from, int to, Class clz) { synchronized(mutex) { return l.extractElements(from, to, clz); } } + +#endif +#if PRIMITIVES + public void fillBuffer(JAVA_BUFFER buffer) { synchronized(mutex) { l.fillBuffer(buffer); } } +#endif + @Override + public LIST_ITERATOR KEY_GENERIC_TYPE listIterator() { + return l.listIterator(); + } + + @Override + public LIST_ITERATOR KEY_GENERIC_TYPE listIterator(int index) { + return l.listIterator(index); + } + + @Override + public LIST KEY_GENERIC_TYPE subList(int from, int to) { + return LISTS.synchronize(l.subList(from, to)); + } + + @Override + public void size(int size) { synchronized(mutex) { l.size(size); } } + + @Override + public LIST KEY_GENERIC_TYPE copy() { synchronized(mutex) { return l.copy(); } } + } + + private static class UnmodifiableRandomList KEY_GENERIC_TYPE extends UnmodifiableList KEY_GENERIC_TYPE implements RandomAccess + { + UnmodifiableRandomList(LIST KEY_GENERIC_TYPE l) { + super(l); + } + } + + private static class UnmodifiableList KEY_GENERIC_TYPE extends COLLECTIONS.UnmodifiableCollection KEY_GENERIC_TYPE implements LIST KEY_GENERIC_TYPE + { + final LIST KEY_GENERIC_TYPE l; + + UnmodifiableList(LIST KEY_GENERIC_TYPE l) { + super(l); + this.l = l; + } + + @Override + public boolean addAll(int index, Collection c) { throw new UnsupportedOperationException(); } + + @Override + public void add(int index, CLASS_TYPE element) { throw new UnsupportedOperationException(); } + +#if !TYPE_OBJECT + @Override + public void add(int index, KEY_TYPE e) { throw new UnsupportedOperationException(); } + +#endif + @Override + public boolean addAll(int index, COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } + + @Override + public boolean addAll(LIST KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } + + @Override + public boolean addAll(int index, LIST KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } + + @Override + public KEY_TYPE GET_KEY(int index) { return l.GET_KEY(index); } + +#if !TYPE_OBJECT + @Override + public void forEach(CONSUMER action) { l.forEach(action); } + +#else + @Override + public void forEach(Consumer action) { l.forEach(action); } + +#endif + @Override + public KEY_TYPE set(int index, KEY_TYPE e) { throw new UnsupportedOperationException(); } + + @Override + public KEY_TYPE REMOVE(int index) { throw new UnsupportedOperationException(); } + + @Override + public KEY_TYPE swapRemove(int index) { throw new UnsupportedOperationException(); } + + @Override + public boolean REMOVE_SWAP(KEY_TYPE e) { throw new UnsupportedOperationException(); } + + @Override + @Primitive + public int indexOf(Object e) { return l.indexOf(e); } + + @Override + @Primitive + public int lastIndexOf(Object e) { return l.lastIndexOf(e); } + +#if !TYPE_OBJECT + @Override + public int indexOf(KEY_TYPE e) { return l.indexOf(e); } + + @Override + public int lastIndexOf(KEY_TYPE e) { return l.lastIndexOf(e); } + +#endif + @Override + public void addElements(int from, KEY_TYPE[] a, int offset, int length) { throw new UnsupportedOperationException(); } + + @Override + public KEY_TYPE[] getElements(int from, KEY_TYPE[] a, int offset, int length) { + return l.getElements(from, a, offset, length); + } + + @Override + public void removeElements(int from, int to) { throw new UnsupportedOperationException(); } + +#if !TYPE_OBJECT + @Override + public KEY_TYPE[] extractElements(int from, int to) { throw new UnsupportedOperationException(); } + +#else + @Override + public K[] extractElements(int from, int to, Class clz) { throw new UnsupportedOperationException(); } + +#endif +#if PRIMITIVES + public void fillBuffer(JAVA_BUFFER buffer) { l.fillBuffer(buffer); } + +#endif + @Override + public LIST_ITERATOR KEY_GENERIC_TYPE listIterator() { + return ITERATORS.unmodifiable(l.listIterator()); + } + + @Override + public LIST_ITERATOR KEY_GENERIC_TYPE listIterator(int index) { + return ITERATORS.unmodifiable(l.listIterator(index)); + } + + @Override + public LIST KEY_GENERIC_TYPE subList(int from, int to) { + return LISTS.unmodifiable(l.subList(from, to)); + } + + @Override + public void size(int size) { throw new UnsupportedOperationException(); } + + @Override + public LIST KEY_GENERIC_TYPE copy() { return l.copy(); } + } + + private static class EmptyList KEY_GENERIC_TYPE extends COLLECTIONS.EmptyCollection KEY_GENERIC_TYPE implements LIST KEY_GENERIC_TYPE + { + @Override + public boolean addAll(int index, Collection c) { throw new UnsupportedOperationException(); } + + @Override + public void add(int index, CLASS_TYPE element) { throw new UnsupportedOperationException(); } + +#if !TYPE_OBJECT + @Override + public void add(int index, KEY_TYPE e) { throw new UnsupportedOperationException(); } + +#endif + @Override + public boolean addAll(int index, COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } + + @Override + public boolean addAll(LIST KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } + + @Override + public boolean addAll(int index, LIST KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } + + @Override + public KEY_TYPE GET_KEY(int index) { throw new IndexOutOfBoundsException(); } + + @Override + public KEY_TYPE set(int index, KEY_TYPE e) { throw new UnsupportedOperationException(); } + + @Override + public KEY_TYPE REMOVE(int index) { throw new UnsupportedOperationException(); } + + @Override + public KEY_TYPE swapRemove(int index) { throw new UnsupportedOperationException(); } + + @Override + public boolean REMOVE_SWAP(KEY_TYPE e) { throw new UnsupportedOperationException(); } + + @Override + public int indexOf(Object e) { return -1; } + + @Override + public int lastIndexOf(Object e) { return -1; } + +#if !TYPE_OBJECT + @Override + public int indexOf(KEY_TYPE e) { return -1; } + + @Override + public int lastIndexOf(KEY_TYPE e) { return -1; } + +#endif + @Override + public void addElements(int from, KEY_TYPE[] a, int offset, int length){ throw new UnsupportedOperationException(); } + + @Override + public KEY_TYPE[] getElements(int from, KEY_TYPE[] a, int offset, int length) { throw new IndexOutOfBoundsException(); } + + @Override + public void removeElements(int from, int to) { throw new UnsupportedOperationException(); } + +#if !TYPE_OBJECT + @Override + public KEY_TYPE[] extractElements(int from, int to) { throw new UnsupportedOperationException(); } + +#else + @Override + public K[] extractElements(int from, int to, Class clz) { throw new UnsupportedOperationException(); } + +#endif + @Override + public LIST_ITERATOR KEY_GENERIC_TYPE listIterator() { + return ITERATORS.empty(); + } + + @Override + public LIST_ITERATOR KEY_GENERIC_TYPE listIterator(int index) { + if(index != 0) + throw new IndexOutOfBoundsException(); + return ITERATORS.empty(); + } + + @Override + public int hashCode() { return 1; } + + @Override + public boolean equals(Object o) { + if(o == this) return true; + if(!(o instanceof List)) return false; + return ((List)o).isEmpty(); + } + + @Override + public LIST KEY_GENERIC_TYPE subList(int from, int to) { throw new UnsupportedOperationException(); } + + @Override + public void size(int size) { throw new UnsupportedOperationException(); } + + @Override + public EmptyList KEY_GENERIC_TYPE copy() { return this; } + } +} diff --git a/src/builder/resources/speiger/assets/collections/templates/utils/maps/Maps.template b/src/builder/resources/speiger/assets/collections/templates/utils/maps/Maps.template index 768845d..a640b9a 100644 --- a/src/builder/resources/speiger/assets/collections/templates/utils/maps/Maps.template +++ b/src/builder/resources/speiger/assets/collections/templates/utils/maps/Maps.template @@ -1,1180 +1,1180 @@ -package speiger.src.collections.PACKAGE.utils.maps; - -#if !TYPE_BOOLEAN -import java.util.Map; -import java.util.Objects; -#if TYPE_OBJECT && SORTED_MAP_FEATURE -import java.util.Comparator; -#else if !TYPE_OBJECT -import java.util.function.BiConsumer; -import java.util.function.BiFunction; -#endif -#endif -import java.util.function.Consumer; -#if !TYPE_OBJECT && !TYPE_BOOLEAN -import java.util.function.Function; -#endif -#if VALUE_BOOLEAN && JDK_TYPE -import java.util.function.PREDICATE; -#endif - -import speiger.src.collections.objects.collections.ObjectIterable; -import speiger.src.collections.objects.collections.ObjectIterator; -import speiger.src.collections.objects.sets.ObjectSet; -import speiger.src.collections.objects.collections.ObjectBidirectionalIterator; -import speiger.src.collections.objects.utils.ObjectIterators; -import speiger.src.collections.objects.utils.ObjectSets; -#if !TYPE_OBJECT -import speiger.src.collections.objects.sets.ObjectOrderedSet; -#if SORTED_MAP_FEATURE -import speiger.src.collections.PACKAGE.functions.COMPARATOR; -#endif -#endif -import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; -#if !VALUE_BOOLEAN || !JDK_TYPE -import speiger.src.collections.PACKAGE.functions.function.FUNCTION; -#endif -import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; -import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -#if SORTED_MAP_FEATURE -import speiger.src.collections.PACKAGE.maps.interfaces.NAVIGABLE_MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.SORTED_MAP; -#endif -#if ORDERED_MAP_FEATURE -import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP; -#endif -#if SORTED_MAP_FEATURE -import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET; -import speiger.src.collections.PACKAGE.sets.SORTED_SET; -#endif -#if ORDERED_MAP_FEATURE -import speiger.src.collections.PACKAGE.sets.ORDERED_SET; -#endif -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.sets.SET; -import speiger.src.collections.PACKAGE.utils.SETS; -#endif -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; -#if !SAME_TYPE -import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR; -#endif -import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_SUPPLIER; -import speiger.src.collections.VALUE_PACKAGE.utils.VALUE_COLLECTIONS; - -/** - * A Helper class that provides you with Singleton/Empty/Synchronized/Unmodifyable Maps - */ -public class MAPS -{ -#if !TYPE_BOOLEAN - /** - * Empty Map Variable - */ - private static final MAP NO_KV_GENERIC_TYPE EMPTY = new EmptyMapKV_BRACES(); - - /** - * Empty Map getter function that autocasts to the desired Key and Value - * @Type(T) - * @ValueType(V) - * @return empty map of desired type - */ - public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE empty() { -#if TYPE_OBJECT || VALUE_OBJECT - return (MAP KEY_VALUE_GENERIC_TYPE)EMPTY; -#else - return EMPTY; -#endif - } - -#endif - /** - * Helper method that provides the fastIterator that recycles a single Entry to increase throughput. - * @param map the map the fastIterator should be accessed from - * @Type(T) - * @ValueType(V) - * @return either a normal iterator if it does not support this feature to a fastIterator - */ - public static GENERIC_KEY_VALUE_BRACES ObjectIterator fastIterator(MAP KEY_VALUE_GENERIC_TYPE map) { - ObjectSet entries = map.ENTRY_SET(); - return entries instanceof MAP.FastEntrySet ? ((MAP.FastEntrySet KEY_VALUE_GENERIC_TYPE)entries).fastIterator() : entries.iterator(); - } - - /** - * Helper method that provides the fastIterable that recycles a single Entry to increase throughput. - * @param map the map the fastIterable should be accessed from - * @Type(T) - * @ValueType(V) - * @return either a normal iterable if it does not support this feature to a fastIterable - */ - public static GENERIC_KEY_VALUE_BRACES ObjectIterable fastIterable(MAP KEY_VALUE_GENERIC_TYPE map) { - ObjectSet entries = map.ENTRY_SET(); - return map instanceof MAP.FastEntrySet ? new ObjectIterable(){ - @Override - public ObjectIterator iterator() { return ((MAP.FastEntrySet KEY_VALUE_GENERIC_TYPE)entries).fastIterator(); } - @Override - public void forEach(Consumer action) { ((MAP.FastEntrySet KEY_VALUE_GENERIC_TYPE)entries).fastForEach(action); } - } : entries; - } - - /** - * A Helper function that provides a faster forEach iterator implementation that recycles the entry to increase throughput - * @param map the map the fast forEach should be accessed from - * @param action the action that should be performed on each entry - * @Type(T) - * @ValueType(V) - * @note if the fast forEach is not supported will default to a normal forEach - */ - public static GENERIC_KEY_VALUE_BRACES void fastForEach(MAP KEY_VALUE_GENERIC_TYPE map, Consumer action) { - ObjectSet entries = map.ENTRY_SET(); - if(entries instanceof MAP.FastEntrySet) ((MAP.FastEntrySet KEY_VALUE_GENERIC_TYPE)entries).fastForEach(action); - else entries.forEach(action); - } - - /** - * Helper function that creates a Helper wrapper to synchronize access into the map. - * @param map the map that should be synchronized - * @Type(T) - * @ValueType(V) - * @return a synchronized Map - * @note if the inputted map is already synchronized then it will just return it instead - * @note iterators do not support synchronization - */ - public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE synchronize(MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof SynchronizedMap ? map : new SynchronizedMapKV_BRACES(map); } - /** - * Helper function that creates a Helper wrapper to synchronize access with custom access control into the map. - * @param map the map that should be synchronized - * @param mutex the object that controls access - * @Type(T) - * @ValueType(V) - * @return a synchronized Map - * @note if the inputted map is already synchronized then it will just return it instead - * @note iterators do not support synchronization - */ - public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE synchronize(MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { return map instanceof SynchronizedMap ? map : new SynchronizedMapKV_BRACES(map, mutex); } - -#if SORTED_MAP_FEATURE - /** - * Helper function that creates a Helper wrapper to synchronize access into the SortedMap. - * @param map the SortedMap that should be synchronized - * @Type(T) - * @ValueType(V) - * @return a synchronized SortedMap - * @note if the inputted map is already synchronized then it will just return it instead - * @note iterators do not support synchronization - */ - public static GENERIC_KEY_VALUE_BRACES SORTED_MAP KEY_VALUE_GENERIC_TYPE synchronize(SORTED_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof SynchronizedSortedMap ? map : new SynchronizedSortedMapKV_BRACES(map); } - /** - * Helper function that creates a Helper wrapper to synchronize access with custom access control into the SortedMap. - * @param map the SortedMap that should be synchronized - * @param mutex the object that controls access - * @Type(T) - * @ValueType(V) - * @return a synchronized SortedMap - * @note if the inputted map is already synchronized then it will just return it instead - * @note iterators do not support synchronization - */ - public static GENERIC_KEY_VALUE_BRACES SORTED_MAP KEY_VALUE_GENERIC_TYPE synchronize(SORTED_MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { return map instanceof SynchronizedSortedMap ? map : new SynchronizedSortedMapKV_BRACES(map, mutex); } - -#endif -#if ORDERED_MAP_FEATURE - /** - * Helper function that creates a Helper wrapper to synchronize access into the OrderedMap. - * @param map the OrderedMap that should be synchronized - * @Type(T) - * @ValueType(V) - * @return a synchronized OrderedMap - * @note if the inputted map is already synchronized then it will just return it instead - * @note iterators do not support synchronization - */ - public static GENERIC_KEY_VALUE_BRACES ORDERED_MAP KEY_VALUE_GENERIC_TYPE synchronize(ORDERED_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof SynchronizedOrderedMap ? map : new SynchronizedOrderedMapKV_BRACES(map); } - /** - * Helper function that creates a Helper wrapper to synchronize access with custom access control into the OrderedMap. - * @param map the OrderedMap that should be synchronized - * @param mutex the object that controls access - * @Type(T) - * @ValueType(V) - * @return a synchronized OrderedMap - * @note if the inputted map is already synchronized then it will just return it instead - * @note iterators do not support synchronization - */ - public static GENERIC_KEY_VALUE_BRACES ORDERED_MAP KEY_VALUE_GENERIC_TYPE synchronize(ORDERED_MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { return map instanceof SynchronizedOrderedMap ? map : new SynchronizedOrderedMapKV_BRACES(map, mutex); } - -#endif -#if SORTED_MAP_FEATURE - /** - * Helper function that creates a Helper wrapper to synchronize access into the NavigableMap. - * @param map the NavigableMap that should be synchronized - * @Type(T) - * @ValueType(V) - * @return a synchronized NavigableMap - * @note if the inputted map is already synchronized then it will just return it instead - * @note iterators do not support synchronization - */ - public static GENERIC_KEY_VALUE_BRACES NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE synchronize(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof SynchronizedNavigableMap ? map : new SynchronizedNavigableMapKV_BRACES(map); } - /** - * Helper function that creates a Helper wrapper to synchronize access with custom access control into the NavigableMap. - * @param map the NavigableMap that should be synchronized - * @param mutex the object that controls access - * @Type(T) - * @ValueType(V) - * @return a synchronized NavigableMap - * @note if the inputted map is already synchronized then it will just return it instead - * @note iterators do not support synchronization - */ - public static GENERIC_KEY_VALUE_BRACES NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE synchronize(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { return map instanceof SynchronizedNavigableMap ? map : new SynchronizedNavigableMapKV_BRACES(map, mutex); } - -#endif - /** - * A Helper function that creates a Helper wrapper to only allow Read Access into the Map - * @param map the map that should be made Unmodifiable - * @Type(T) - * @ValueType(V) - * @return a unmodifiable Map - * @note if the inputted map is already unmodifiable then it will just return it instead - */ - public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE unmodifiable(MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof UnmodifyableMap ? map : new UnmodifyableMapKV_BRACES(map); } - -#if ORDERED_MAP_FEATURE - /** - * A Helper function that creates a Helper wrapper to only allow Read Access into the OrderedMap - * @param map the OrderedMap that should be made Unmodifiable - * @Type(T) - * @ValueType(V) - * @return a unmodifiable OrderedMap - * @note if the inputted OrderedMap is already unmodifiable then it will just return it instead - */ - public static GENERIC_KEY_VALUE_BRACES ORDERED_MAP KEY_VALUE_GENERIC_TYPE unmodifiable(ORDERED_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof UnmodifyableOrderedMap ? map : new UnmodifyableOrderedMapKV_BRACES(map); } - -#endif -#if SORTED_MAP_FEATURE - /** - * A Helper function that creates a Helper wrapper to only allow Read Access into the SortedMap - * @param map the SortedMap that should be made Unmodifiable - * @Type(T) - * @ValueType(V) - * @return a unmodifiable SortedMap - * @note if the inputted SortedMap is already unmodifiable then it will just return it instead - */ - public static GENERIC_KEY_VALUE_BRACES SORTED_MAP KEY_VALUE_GENERIC_TYPE unmodifiable(SORTED_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof UnmodifyableSortedMap ? map : new UnmodifyableSortedMapKV_BRACES(map); } - - /** - * A Helper function that creates a Helper wrapper to only allow Read Access into NavigableMap Map - * @param map the NavigableMap that should be made Unmodifiable - * @Type(T) - * @ValueType(V) - * @return a unmodifiable NavigableMap - * @note if the inputted NavigableMap is already unmodifiable then it will just return it instead - */ - public static GENERIC_KEY_VALUE_BRACES NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE unmodifiable(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof UnmodifyableNavigableMap ? map : new UnmodifyableNavigableMapKV_BRACES(map); } - -#endif - /** - * A Helper function that creates a Unmodifyable Entry - * @param entry the Entry that should be made unmodifiable - * @Type(T) - * @ValueType(V) - * @return a Unmodifyable Entry - */ - public static GENERIC_KEY_VALUE_BRACES MAP.Entry KEY_VALUE_GENERIC_TYPE unmodifiable(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { return entry instanceof UnmodifyableEntry ? entry : (entry == null ? null : new UnmodifyableEntryKV_BRACES(entry)); } - /** - * A Helper function that creates a Unmodifyable Entry - * @param entry the Entry that should be made unmodifiable - * @Type(T) - * @ValueType(V) - * @return a Unmodifyable Entry - */ - public static GENERIC_KEY_VALUE_BRACES MAP.Entry KEY_VALUE_GENERIC_TYPE unmodifiable(Map.Entry entry) { return entry instanceof UnmodifyableEntry ? (UnmodifyableEntry KEY_VALUE_GENERIC_TYPE)entry : (entry == null ? null : new UnmodifyableEntryKV_BRACES(entry)); } - - /** - * Creates a Singleton map from the provided values. - * This reduces overhead that normal Map implementations have. - * @param key the key that should be turned into a singleton - * @param value the value that should be turned into a singleton - * @Type(T) - * @ValueType(V) - * @return a unmodifiable Singleton map. - */ - public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE singleton(KEY_TYPE key, VALUE_TYPE value) { return new SingletonMapKV_BRACES(key, value); } - - /** - * Singleton Map instance that is used in the helper method - * @Type(T) - * @ValueType(V) - */ - public static class SingletonMap KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE { - final KEY_TYPE key; - final VALUE_TYPE value; - SET KEY_GENERIC_TYPE keySet; - VALUE_COLLECTION VALUE_GENERIC_TYPE values; - ObjectSet entrySet; - - SingletonMap(KEY_TYPE key, VALUE_TYPE value) { - this.key = key; - this.value = value; - } - - @Override - public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } - @Override - public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } -#if VALUE_PRIMITIVES - @Override - public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } - @Override - public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } -#endif - @Override - public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { throw new UnsupportedOperationException(); } - @Override - public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { throw new UnsupportedOperationException(); } -#if !TYPE_OBJECT || !VALUE_OBJECT - @Override - public boolean remove(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } -#endif - @Override - public VALUE_TYPE GET_VALUE(KEY_TYPE key) { return EQUALS_KEY_TYPE(key, this.key) ? value : getDefaultReturnValue(); } -#if !TYPE_OBJECT || !VALUE_OBJECT - @Override - public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { return EQUALS_KEY_TYPE(key, this.key) ? value : defaultValue; } -#endif - @Override - public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } - @Override - public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } - @Override - public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } - @Override - public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) { throw new UnsupportedOperationException(); } - @Override - public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } - @Override - public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } - @Override - public SingletonMap KEY_VALUE_GENERIC_TYPE copy() { return new SingletonMapKV_BRACES(key, value); } - @Override - public SET KEY_GENERIC_TYPE keySet() { - if(keySet == null) keySet = SETS.singleton(key); - return keySet; - } - - @Override - public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { - if(values == null) values = VALUE_COLLECTIONS.singleton(value); - return values; - } - @Override - public ObjectSet ENTRY_SET() { - if(entrySet == null) entrySet = ObjectSets.singleton(new ABSTRACT_MAP.BasicEntryKV_BRACES(key, value)); - return entrySet; - } - } - - /** - * Empty Map impementation that is used for the emptyMap() function - * @Type(T) - * @ValueType(V) - */ - public static class EmptyMap KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE { - @Override - public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } - @Override - public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } -#if VALUE_PRIMITIVES - @Override - public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } - @Override - public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } -#endif - @Override - public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { throw new UnsupportedOperationException(); } - @Override - public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { throw new UnsupportedOperationException(); } -#if !TYPE_OBJECT || !VALUE_OBJECT - @Override - public boolean remove(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } -#endif - @Override - public VALUE_TYPE GET_VALUE(KEY_TYPE key) { return getDefaultReturnValue(); } -#if !TYPE_OBJECT || !VALUE_OBJECT - @Override - public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { return defaultValue; } -#endif - @Override - public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } - @Override - public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } - @Override - public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } - @Override - public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) { throw new UnsupportedOperationException(); } - @Override - public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } - @Override - public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } - @Override - public SET KEY_GENERIC_TYPE keySet() { return SETS.empty(); } - @Override - public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { return VALUE_COLLECTIONS.empty(); } - @Override - public ObjectSet ENTRY_SET() { return ObjectSets.empty(); } - @Override - public EmptyMap KEY_VALUE_GENERIC_TYPE copy() { return this; } - } - - /** - * The Unmodifyable Entry implementation for the helper function unmodifiableEntry() - * @Type(T) - * @ValueType(V) - */ - public static class UnmodifyableEntry KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP.BasicEntry KEY_VALUE_GENERIC_TYPE { - - UnmodifyableEntry(Map.Entry entry) { - super(entry.getKey(), entry.getValue()); - } - - UnmodifyableEntry(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { - super(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); - } - - @Override - public void set(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } - } - -#if SORTED_MAP_FEATURE - /** - * The Unmodifyable Navigable Map implementation that is sued for the unmodifyableMap function - * @Type(T) - * @ValueType(V) - */ - public static class UnmodifyableNavigableMap KEY_VALUE_GENERIC_TYPE extends UnmodifyableSortedMap KEY_VALUE_GENERIC_TYPE implements NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE { - NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map; - - UnmodifyableNavigableMap(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map) { - super(map); - this.map = map; - } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap() { return MAPS.unmodifiable(map.descendingMap()); } - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE navigableKeySet() { return SETS.unmodifiable(map.navigableKeySet()); } - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE keySet() { return SETS.unmodifiable(map.keySet()); } - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE descendingKeySet() { return SETS.unmodifiable(map.descendingKeySet()); } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE firstEntry() { return MAPS.unmodifiable(map.firstEntry()); } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE lastEntry() { return MAPS.unmodifiable(map.lastEntry()); } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirstEntry() { throw new UnsupportedOperationException(); } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLastEntry() { throw new UnsupportedOperationException(); } - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, boolean fromInclusive, KEY_TYPE toKey, boolean toInclusive) { return MAPS.unmodifiable(map.subMap(fromKey, fromInclusive, toKey, toInclusive)); } - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey, boolean inclusive) { return MAPS.unmodifiable(map.headMap(toKey, inclusive)); } - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey, boolean inclusive) { return MAPS.unmodifiable(map.tailMap(fromKey, inclusive)); } - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, KEY_TYPE toKey) { return MAPS.unmodifiable(map.subMap(fromKey, toKey)); } - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey) { return MAPS.unmodifiable(map.headMap(toKey)); } - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey) { return MAPS.unmodifiable(map.tailMap(fromKey)); } -#if !TYPE_OBJECT - @Override - public void setDefaultMaxValue(KEY_TYPE e) { throw new UnsupportedOperationException(); } - @Override - public KEY_TYPE getDefaultMaxValue() { return map.getDefaultMaxValue(); } - @Override - public void setDefaultMinValue(KEY_TYPE e) { throw new UnsupportedOperationException(); } - @Override - public KEY_TYPE getDefaultMinValue() { return map.getDefaultMinValue(); } -#endif - @Override - public KEY_TYPE lowerKey(KEY_TYPE key) { return map.lowerKey(key); } - @Override - public KEY_TYPE higherKey(KEY_TYPE key) { return map.higherKey(key); } - @Override - public KEY_TYPE floorKey(KEY_TYPE key) { return map.floorKey(key); } - @Override - public KEY_TYPE ceilingKey(KEY_TYPE key) { return map.ceilingKey(key); } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE lowerEntry(KEY_TYPE key) { return MAPS.unmodifiable(map.lowerEntry(key)); } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE higherEntry(KEY_TYPE key) { return MAPS.unmodifiable(map.higherEntry(key)); } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE floorEntry(KEY_TYPE key) { return MAPS.unmodifiable(map.floorEntry(key)); } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE ceilingEntry(KEY_TYPE key) { return MAPS.unmodifiable(map.ceilingEntry(key)); } - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE copy() { return map.copy(); } - } - -#endif -#if ORDERED_MAP_FEATURE - /** - * The Unmodifyable Ordered Map implementation that is sued for the unmodifyableMap function - * @Type(T) - * @ValueType(V) - */ - public static class UnmodifyableOrderedMap KEY_VALUE_GENERIC_TYPE extends UnmodifyableMap KEY_VALUE_GENERIC_TYPE implements ORDERED_MAP KEY_VALUE_GENERIC_TYPE { - ORDERED_MAP KEY_VALUE_GENERIC_TYPE map; - - UnmodifyableOrderedMap(ORDERED_MAP KEY_VALUE_GENERIC_TYPE map) { - super(map); - this.map = map; - } - - @Override - public VALUE_TYPE putAndMoveToFirst(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } - @Override - public VALUE_TYPE putAndMoveToLast(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } - @Override - public boolean moveToFirst(KEY_TYPE key) { throw new UnsupportedOperationException(); } - @Override - public boolean moveToLast(KEY_TYPE key) { throw new UnsupportedOperationException(); } - @Override - public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key) { throw new UnsupportedOperationException(); } - @Override - public VALUE_TYPE getAndMoveToLast(KEY_TYPE key) { throw new UnsupportedOperationException(); } - @Override - public KEY_TYPE FIRST_ENTRY_KEY() { return map.FIRST_ENTRY_KEY(); } - @Override - public KEY_TYPE POLL_FIRST_ENTRY_KEY() { throw new UnsupportedOperationException(); } - @Override - public KEY_TYPE LAST_ENTRY_KEY() { return map.LAST_ENTRY_KEY(); } - @Override - public KEY_TYPE POLL_LAST_ENTRY_KEY() { throw new UnsupportedOperationException(); } - @Override - public VALUE_TYPE FIRST_ENTRY_VALUE() { return map.FIRST_ENTRY_VALUE(); } - @Override - public VALUE_TYPE LAST_ENTRY_VALUE() { return map.LAST_ENTRY_VALUE(); } - @Override - public ORDERED_MAP KEY_VALUE_GENERIC_TYPE copy() { return map.copy(); } - @Override - public ORDERED_SET KEY_GENERIC_TYPE keySet() { - if(keys == null) keys = SETS.unmodifiable(map.keySet()); - return (ORDERED_SET KEY_GENERIC_TYPE)keys; - } - - @Override - public ObjectOrderedSet ENTRY_SET() { - if(entrySet == null) entrySet = new UnmodifyableOrderedEntrySetKV_BRACES(map.ENTRY_SET()); - return (ObjectOrderedSet)entrySet; - } - } - -#endif -#if SORTED_MAP_FEATURE - /** - * The Unmodifyable Sorted Map implementation that is sued for the unmodifyableMap function - * @Type(T) - * @ValueType(V) - */ - public static class UnmodifyableSortedMap KEY_VALUE_GENERIC_TYPE extends UnmodifyableMap KEY_VALUE_GENERIC_TYPE implements SORTED_MAP KEY_VALUE_GENERIC_TYPE { - SORTED_MAP KEY_VALUE_GENERIC_TYPE map; - - UnmodifyableSortedMap(SORTED_MAP KEY_VALUE_GENERIC_TYPE map) { - super(map); - this.map = map; - } - - @Override - public COMPARATOR KEY_GENERIC_TYPE comparator() { return map.comparator(); } - @Override - public SORTED_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, KEY_TYPE toKey) { return MAPS.unmodifiable(map.subMap(fromKey, toKey)); } - @Override - public SORTED_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey) { return MAPS.unmodifiable(map.headMap(toKey)); } - @Override - public SORTED_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey) { return MAPS.unmodifiable(map.tailMap(fromKey)); } - @Override - public SORTED_SET KEY_GENERIC_TYPE keySet() { return SETS.unmodifiable(map.keySet()); } - @Override - public KEY_TYPE FIRST_ENTRY_KEY() { return map.FIRST_ENTRY_KEY(); } - @Override - public KEY_TYPE POLL_FIRST_ENTRY_KEY() { throw new UnsupportedOperationException(); } - @Override - public KEY_TYPE LAST_ENTRY_KEY() { return map.LAST_ENTRY_KEY(); } - @Override - public KEY_TYPE POLL_LAST_ENTRY_KEY() { throw new UnsupportedOperationException(); } - @Override - public VALUE_TYPE FIRST_ENTRY_VALUE() { return map.FIRST_ENTRY_VALUE(); } - @Override - public VALUE_TYPE LAST_ENTRY_VALUE() { return map.LAST_ENTRY_VALUE(); } - @Override - public SORTED_MAP KEY_VALUE_GENERIC_TYPE copy() { return map.copy(); } - } - -#endif - /** - * The Unmodifyable Map implementation that is sued for the unmodifyableMap function - * @Type(T) - * @ValueType(V) - */ - public static class UnmodifyableMap KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements MAP KEY_VALUE_GENERIC_TYPE { - MAP KEY_VALUE_GENERIC_TYPE map; - VALUE_COLLECTION VALUE_GENERIC_TYPE values; - SET KEY_GENERIC_TYPE keys; - ObjectSet entrySet; - - UnmodifyableMap(MAP KEY_VALUE_GENERIC_TYPE map) { - this.map = map; - } - - @Override - public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } - @Override - public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value){ throw new UnsupportedOperationException(); } -#if VALUE_PRIMITIVES - @Override - public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } - @Override - public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } -#endif - @Override - public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { throw new UnsupportedOperationException(); } - @Override - public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { throw new UnsupportedOperationException(); } -#if !TYPE_OBJECT || !VALUE_OBJECT - @Override - public boolean remove(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } -#endif - @Override - public VALUE_TYPE GET_VALUE(KEY_TYPE key) { - VALUE_TYPE type = map.GET_VALUE(key); - return VALUE_EQUALS(type, map.getDefaultReturnValue()) && !map.containsKey(key) ? getDefaultReturnValue() : type; - } -#if !TYPE_OBJECT || !VALUE_OBJECT - @Override - public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { return map.getOrDefault(key, defaultValue); } -#endif - @Override - public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } - @Override - public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } - @Override - public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } - @Override - public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) { throw new UnsupportedOperationException(); } - @Override - public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } - @Override - public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } - @Override - public void REPLACE_VALUES(UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } - @Override - public void REPLACE_VALUES(MAP KEY_VALUE_GENERIC_TYPE m) { throw new UnsupportedOperationException(); } - @Override - public MAP KEY_VALUE_GENERIC_TYPE copy() { return map.copy(); } - @Override - public void clear() { throw new UnsupportedOperationException(); } - - @Override - public SET KEY_GENERIC_TYPE keySet() { - if(keys == null) keys = SETS.unmodifiable(map.keySet()); - return keys; - } - - @Override - public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { - if(values == null) values = VALUE_COLLECTIONS.unmodifiable(map.values()); - return values; - } - - @Override - public ObjectSet ENTRY_SET() { - if(entrySet == null) entrySet = new UnmodifyableEntrySetKV_BRACES(map.ENTRY_SET()); - return entrySet; - } - } - -#if ORDERED_MAP_FEATURE - /** - * The Unmodifyable Ordered Set implementation for the Unmodifyable Ordered Map implementation - * @Type(T) - * @ValueType(V) - */ - public static class UnmodifyableOrderedEntrySet KEY_VALUE_GENERIC_TYPE extends UnmodifyableEntrySet KEY_VALUE_GENERIC_TYPE implements ObjectOrderedSet - { - ObjectOrderedSet set; - - UnmodifyableOrderedEntrySet(ObjectOrderedSet c) { - super(c); - set = c; - } - - @Override - public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } - @Override - public boolean addAndMoveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } - @Override - public boolean moveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } - @Override - public boolean moveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } - @Override - public ObjectOrderedSet copy() { return set.copy(); } - @Override - public ObjectBidirectionalIterator iterator() { return ObjectIterators.unmodifiable(set.iterator()); } - @Override - public ObjectBidirectionalIterator iterator(MAP.Entry KEY_VALUE_GENERIC_TYPE fromElement) { return ObjectIterators.unmodifiable(set.iterator(fromElement)); } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE first() { return set.first(); } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirst() { throw new UnsupportedOperationException(); } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE last() { return set.last(); } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLast() { throw new UnsupportedOperationException(); } - } - -#endif - /** - * The Unmodifyable Set implementation for the Unmodifyable Map implementation - * @Type(T) - * @ValueType(V) - */ - public static class UnmodifyableEntrySet KEY_VALUE_GENERIC_TYPE extends ObjectSets.UnmodifiableSet - { - ObjectSet s; - - UnmodifyableEntrySet(ObjectSet c) - { - super(c); - s = c; - } - - @Override - public void forEach(Consumer action) { - s.forEach(T -> action.accept(MAPS.unmodifiable(T))); - } - - @Override - public ObjectIterator iterator() { - return new ObjectIterator() { - ObjectIterator iter = s.iterator(); - @Override - public boolean hasNext() { return iter.hasNext(); } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { return MAPS.unmodifiable(iter.next()); } - }; - } - - } - -#if SORTED_MAP_FEATURE - /** - * The Synchronized Navigable Map implementation used by the synchronizedMap helper function - * @Type(T) - * @ValueType(V) - */ - public static class SynchronizedNavigableMap KEY_VALUE_GENERIC_TYPE extends SynchronizedSortedMap KEY_VALUE_GENERIC_TYPE implements NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE { - NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map; - - SynchronizedNavigableMap(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map) { - super(map); - this.map = map; - } - - SynchronizedNavigableMap(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { - super(map, mutex); - this.map = map; - } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap() { synchronized(mutex) { return MAPS.synchronize(map.descendingMap(), mutex); } } - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE navigableKeySet() { synchronized(mutex) { return SETS.synchronize(map.navigableKeySet(), mutex); } } - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE descendingKeySet() { synchronized(mutex) { return SETS.synchronize(map.descendingKeySet(), mutex); } } - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE keySet() { synchronized(mutex) { return SETS.synchronize(map.keySet(), mutex); } } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE firstEntry() { synchronized(mutex) { return map.firstEntry(); } } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE lastEntry() { synchronized(mutex) { return map.lastEntry(); } } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirstEntry() { synchronized(mutex) { return map.pollFirstEntry(); } } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLastEntry() { synchronized(mutex) { return map.pollLastEntry(); } } - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, boolean fromInclusive, KEY_TYPE toKey, boolean toInclusive) { synchronized(mutex) { return MAPS.synchronize(map.subMap(fromKey, fromInclusive, toKey, toInclusive), mutex); } } - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey, boolean inclusive) { synchronized(mutex) { return MAPS.synchronize(map.headMap(toKey, inclusive), mutex); } } - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey, boolean inclusive) { synchronized(mutex) { return MAPS.synchronize(map.tailMap(fromKey, inclusive), mutex); } } - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, KEY_TYPE toKey) { synchronized(mutex) { return MAPS.synchronize(map.subMap(fromKey, toKey), mutex); } } - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey) { synchronized(mutex) { return MAPS.synchronize(map.headMap(toKey), mutex); } } - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey) { synchronized(mutex) { return MAPS.synchronize(map.tailMap(fromKey), mutex); } } - @Override - public KEY_TYPE lowerKey(KEY_TYPE key) { synchronized(mutex) { return map.lowerKey(key); } } - @Override - public KEY_TYPE higherKey(KEY_TYPE key) { synchronized(mutex) { return map.higherKey(key); } } - @Override - public KEY_TYPE floorKey(KEY_TYPE key) { synchronized(mutex) { return map.floorKey(key); } } - @Override - public KEY_TYPE ceilingKey(KEY_TYPE key) { synchronized(mutex) { return map.ceilingKey(key); } } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE lowerEntry(KEY_TYPE key) { synchronized(mutex) { return map.lowerEntry(key); } } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE higherEntry(KEY_TYPE key) { synchronized(mutex) { return map.higherEntry(key); } } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE floorEntry(KEY_TYPE key) { synchronized(mutex) { return map.floorEntry(key); } } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE ceilingEntry(KEY_TYPE key) { synchronized(mutex) { return map.ceilingEntry(key); } } - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE copy() { synchronized(mutex) { return map.copy(); } } -#if !TYPE_OBJECT - @Override - @Deprecated - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(CLASS_TYPE fromKey, boolean fromInclusive, CLASS_TYPE toKey, boolean toInclusive) { synchronized(mutex) { return MAPS.synchronize(map.subMap(fromKey, fromInclusive, toKey, toInclusive), mutex); } } - @Override - @Deprecated - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(CLASS_TYPE toKey, boolean inclusive) { synchronized(mutex) { return MAPS.synchronize(map.headMap(toKey, inclusive), mutex); } } - @Override - @Deprecated - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(CLASS_TYPE fromKey, boolean inclusive) { synchronized(mutex) { return MAPS.synchronize(map.tailMap(fromKey, inclusive), mutex); } } - @Override - @Deprecated - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(CLASS_TYPE fromKey, CLASS_TYPE toKey) { synchronized(mutex) { return MAPS.synchronize(map.subMap(fromKey, toKey), mutex); } } - @Override - @Deprecated - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(CLASS_TYPE toKey) { synchronized(mutex) { return MAPS.synchronize(map.headMap(toKey), mutex); } } - @Override - @Deprecated - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(CLASS_TYPE fromKey) { synchronized(mutex) { return MAPS.synchronize(map.tailMap(fromKey), mutex); } } - @Override - public void setDefaultMaxValue(KEY_TYPE e) { synchronized(mutex) { map.setDefaultMaxValue(e); } } - @Override - public KEY_TYPE getDefaultMaxValue() { synchronized(mutex) { return map.getDefaultMaxValue(); } } - @Override - public void setDefaultMinValue(KEY_TYPE e) { synchronized(mutex) { map.setDefaultMinValue(e); } } - @Override - public KEY_TYPE getDefaultMinValue() { synchronized(mutex) { return map.getDefaultMinValue(); } } - @Override - @Deprecated - public CLASS_TYPE lowerKey(CLASS_TYPE key) { synchronized(mutex) { return map.lowerKey(key); } } - @Override - @Deprecated - public CLASS_TYPE floorKey(CLASS_TYPE key) { synchronized(mutex) { return map.floorKey(key); } } - @Override - @Deprecated - public CLASS_TYPE ceilingKey(CLASS_TYPE key) { synchronized(mutex) { return map.ceilingKey(key); } } - @Override - @Deprecated - public CLASS_TYPE higherKey(CLASS_TYPE key) { synchronized(mutex) { return map.higherKey(key); } } - @Override - @Deprecated - public MAP.Entry KEY_VALUE_GENERIC_TYPE lowerEntry(CLASS_TYPE key) { synchronized(mutex) { return map.lowerEntry(key); } } - @Override - @Deprecated - public MAP.Entry KEY_VALUE_GENERIC_TYPE floorEntry(CLASS_TYPE key) { synchronized(mutex) { return map.floorEntry(key); } } - @Override - @Deprecated - public MAP.Entry KEY_VALUE_GENERIC_TYPE ceilingEntry(CLASS_TYPE key) { synchronized(mutex) { return map.ceilingEntry(key); } } - @Override - @Deprecated - public MAP.Entry KEY_VALUE_GENERIC_TYPE higherEntry(CLASS_TYPE key) { synchronized(mutex) { return map.higherEntry(key); } } -#endif - } - -#endif -#if ORDERED_MAP_FEATURE - /** - * The Synchronized Ordered Map implementation used by the synchronizedMap helper function - * @Type(T) - * @ValueType(V) - */ - public static class SynchronizedOrderedMap KEY_VALUE_GENERIC_TYPE extends SynchronizedMap KEY_VALUE_GENERIC_TYPE implements ORDERED_MAP KEY_VALUE_GENERIC_TYPE { - ORDERED_MAP KEY_VALUE_GENERIC_TYPE map; - - SynchronizedOrderedMap(ORDERED_MAP KEY_VALUE_GENERIC_TYPE map) { - super(map); - this.map = map; - } - - SynchronizedOrderedMap(ORDERED_MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { - super(map, mutex); - this.map = map; - } - - @Override - public VALUE_TYPE putAndMoveToFirst(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.putAndMoveToFirst(key, value); } } - @Override - public VALUE_TYPE putAndMoveToLast(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.putAndMoveToLast(key, value); } } - @Override - public boolean moveToFirst(KEY_TYPE key) { synchronized(mutex) { return map.moveToFirst(key); } } - @Override - public boolean moveToLast(KEY_TYPE key) { synchronized(mutex) { return map.moveToLast(key); } } - @Override - public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key) { synchronized(mutex) { return map.getAndMoveToFirst(key); } } - @Override - public VALUE_TYPE getAndMoveToLast(KEY_TYPE key) { synchronized(mutex) { return map.getAndMoveToLast(key); } } - @Override - public KEY_TYPE FIRST_ENTRY_KEY() { synchronized(mutex) { return map.FIRST_ENTRY_KEY(); } } - @Override - public KEY_TYPE POLL_FIRST_ENTRY_KEY() { synchronized(mutex) { return map.POLL_FIRST_ENTRY_KEY(); } } - @Override - public KEY_TYPE LAST_ENTRY_KEY() { synchronized(mutex) { return map.LAST_ENTRY_KEY(); } } - @Override - public KEY_TYPE POLL_LAST_ENTRY_KEY() { synchronized(mutex) { return map.POLL_LAST_ENTRY_KEY(); } } - @Override - public VALUE_TYPE FIRST_ENTRY_VALUE() { synchronized(mutex) { return map.FIRST_ENTRY_VALUE(); } } - @Override - public VALUE_TYPE LAST_ENTRY_VALUE() { synchronized(mutex) { return map.LAST_ENTRY_VALUE(); } } - @Override - public ORDERED_MAP KEY_VALUE_GENERIC_TYPE copy() { synchronized(mutex) { return map.copy(); } } - @Override - public ORDERED_SET KEY_GENERIC_TYPE keySet() { - if(keys == null) keys = SETS.synchronize(map.keySet(), mutex); - return (ORDERED_SET KEY_GENERIC_TYPE)keys; - } - - @Override - public ObjectOrderedSet ENTRY_SET() { - if(entrySet == null) entrySet = ObjectSets.synchronize(map.ENTRY_SET(), mutex); - return (ObjectOrderedSet)entrySet; - } - } - -#endif -#if SORTED_MAP_FEATURE - /** - * The Synchronized Sorted Map implementation used by the synchronizedMap helper function - * @Type(T) - * @ValueType(V) - */ - public static class SynchronizedSortedMap KEY_VALUE_GENERIC_TYPE extends SynchronizedMap KEY_VALUE_GENERIC_TYPE implements SORTED_MAP KEY_VALUE_GENERIC_TYPE { - SORTED_MAP KEY_VALUE_GENERIC_TYPE map; - - SynchronizedSortedMap(SORTED_MAP KEY_VALUE_GENERIC_TYPE map) { - super(map); - this.map = map; - } - - SynchronizedSortedMap(SORTED_MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { - super(map, mutex); - this.map = map; - } - - @Override - public COMPARATOR KEY_GENERIC_TYPE comparator() { synchronized(mutex) { return map.comparator(); } } - @Override - public SORTED_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, KEY_TYPE toKey) { synchronized(mutex) { return MAPS.synchronize(map.subMap(fromKey, toKey), mutex); } } - @Override - public SORTED_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey) { synchronized(mutex) { return MAPS.synchronize(map.headMap(toKey), mutex); } } - @Override - public SORTED_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey) { synchronized(mutex) { return MAPS.synchronize(map.tailMap(fromKey), mutex); } } - @Override - public SORTED_SET KEY_GENERIC_TYPE keySet() { synchronized(mutex) { return SETS.synchronize(map.keySet(), mutex); } } - @Override - public KEY_TYPE FIRST_ENTRY_KEY() { synchronized(mutex) { return map.FIRST_ENTRY_KEY(); } } - @Override - public KEY_TYPE POLL_FIRST_ENTRY_KEY() { synchronized(mutex) { return map.POLL_FIRST_ENTRY_KEY(); } } - @Override - public KEY_TYPE LAST_ENTRY_KEY() { synchronized(mutex) { return map.LAST_ENTRY_KEY(); } } - @Override - public KEY_TYPE POLL_LAST_ENTRY_KEY() { synchronized(mutex) { return map.POLL_LAST_ENTRY_KEY(); } } - @Override - public VALUE_TYPE FIRST_ENTRY_VALUE() { synchronized(mutex) { return map.FIRST_ENTRY_VALUE(); } } - @Override - public VALUE_TYPE LAST_ENTRY_VALUE() { synchronized(mutex) { return map.LAST_ENTRY_VALUE(); } } - @Override - public SORTED_MAP KEY_VALUE_GENERIC_TYPE copy() { synchronized(mutex) { return map.copy(); } } -#if !TYPE_OBJECT - @Override - @Deprecated - public CLASS_TYPE firstKey() { synchronized(mutex) { return map.firstKey(); } } - @Override - @Deprecated - public CLASS_TYPE lastKey() { synchronized(mutex) { return map.lastKey(); } } - @Override - @Deprecated - public SORTED_MAP KEY_VALUE_GENERIC_TYPE subMap(CLASS_TYPE fromKey, CLASS_TYPE toKey) { synchronized(mutex) { return MAPS.synchronize(map.subMap(fromKey, toKey), mutex); } } - @Override - @Deprecated - public SORTED_MAP KEY_VALUE_GENERIC_TYPE headMap(CLASS_TYPE toKey) { synchronized(mutex) { return MAPS.synchronize(map.headMap(toKey), mutex); } } - @Override - @Deprecated - public SORTED_MAP KEY_VALUE_GENERIC_TYPE tailMap(CLASS_TYPE fromKey) { synchronized(mutex) { return MAPS.synchronize(map.tailMap(fromKey), mutex); } } -#endif - } - -#endif - /** - * The Synchronized Map implementation used by the synchronizedMap helper function - * @Type(T) - * @ValueType(V) - */ - public static class SynchronizedMap KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements MAP KEY_VALUE_GENERIC_TYPE { - MAP KEY_VALUE_GENERIC_TYPE map; - VALUE_COLLECTION VALUE_GENERIC_TYPE values; - SET KEY_GENERIC_TYPE keys; - ObjectSet entrySet; - - protected Object mutex; - - SynchronizedMap(MAP KEY_VALUE_GENERIC_TYPE map) { - this.map = map; - mutex = this; - } - - SynchronizedMap(MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { - this.map = map; - this.mutex = mutex; - } - - @Override - public VALUE_TYPE getDefaultReturnValue() { synchronized(mutex) { return map.getDefaultReturnValue(); } } - @Override - public ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE setDefaultReturnValue(VALUE_TYPE v) { - synchronized(mutex) { - map.setDefaultReturnValue(v); - return this; - } - } - @Override - public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.put(key, value); } } - @Override - public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.putIfAbsent(key, value); } } - public void putAllIfAbsent(MAP KEY_VALUE_GENERIC_TYPE m) { synchronized(mutex) { map.putAllIfAbsent(m); } } -#if VALUE_PRIMITIVES - @Override - public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.addTo(key, value); } } - @Override - public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.subFrom(key, value); } } - public void addToAll(MAP KEY_VALUE_GENERIC_TYPE m) { synchronized(mutex) { map.addToAll(m); } } -#endif - @Override - public void putAll(MAP KEY_VALUE_GENERIC_TYPE m) { synchronized(mutex) { map.putAll(m); } } - @Override - public void putAll(Map m) { synchronized(mutex) { map.putAll(m); } } - @Override - public void putAll(KEY_TYPE[] keys, VALUE_TYPE[] values, int offset, int size) { synchronized(mutex) { map.putAll(keys, values, offset, size); } } - -#if !TYPE_OBJECT - @Override - public boolean containsKey(KEY_TYPE key) { synchronized(mutex) { return map.containsKey(key); } } -#endif -#if !VALUE_OBJECT - @Override - public boolean containsValue(VALUE_TYPE value) { synchronized(mutex) { return map.containsValue(value); } } -#endif - @Override - public VALUE_TYPE GET_VALUE(KEY_TYPE key) { synchronized(mutex) { return map.GET_VALUE(key); } } - @Override - public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { synchronized(mutex) { return map.REMOVE_VALUE(key); } } - @Override - public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { synchronized(mutex) { return map.REMOVE_VALUEOrDefault(key, defaultValue); } } -#if !TYPE_OBJECT || !VALUE_OBJECT - @Override - public boolean remove(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.remove(key, value); } } -#endif - @Override - public boolean replace(KEY_TYPE key, VALUE_TYPE oldValue, VALUE_TYPE newValue) { synchronized(mutex) { return map.replace(key, oldValue, newValue); } } - @Override - public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.replace(key, value); } } - @Override - public void REPLACE_VALUES(MAP KEY_VALUE_GENERIC_TYPE m) { synchronized(mutex) { map.REPLACE_VALUES(m); } } - @Override - public void REPLACE_VALUES(UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { synchronized(mutex) { map.REPLACE_VALUES(mappingFunction); } } - @Override - public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { synchronized(mutex) { return map.COMPUTE(key, mappingFunction); } } - @Override - public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) { synchronized(mutex) { return map.COMPUTE_IF_ABSENT(key, mappingFunction); } } - @Override - public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { synchronized(mutex) { return map.COMPUTE_IF_PRESENT(key, mappingFunction); } } - @Override - public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) { synchronized(mutex) { return map.SUPPLY_IF_ABSENT(key, valueProvider); } } - @Override - public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { synchronized(mutex) { return map.MERGE(key, value, mappingFunction); } } - @Override - public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { synchronized(mutex) { map.BULK_MERGE(m, mappingFunction); } } -#if !TYPE_OBJECT || !VALUE_OBJECT - @Override - public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { synchronized(mutex) { return map.getOrDefault(key, defaultValue); } } -#endif - @Override - public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { synchronized(mutex) { map.forEach(action); } } - @Override - public int size() { synchronized(mutex) { return map.size(); } } - @Override - public MAP KEY_VALUE_GENERIC_TYPE copy() { synchronized(mutex) { return map.copy(); } } - @Override - public SET KEY_GENERIC_TYPE keySet() { - if(keys == null) keys = SETS.synchronize(map.keySet(), mutex); - return keys; - } - - @Override - public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { - if(values == null) values = VALUE_COLLECTIONS.synchronize(map.values(), mutex); - return values; - } - - @Override - public ObjectSet ENTRY_SET() { - if(entrySet == null) entrySet = ObjectSets.synchronize(map.ENTRY_SET(), mutex); - return entrySet; - } - -#if !TYPE_OBJECT - @Override - @Deprecated - public CLASS_VALUE_TYPE get(Object key) { synchronized(mutex) { return map.get(key); } } - @Override - @Deprecated - public CLASS_VALUE_TYPE getOrDefault(Object key, CLASS_VALUE_TYPE defaultValue) { synchronized(mutex) { return map.getOrDefault(key, defaultValue); } } - @Override - @Deprecated - public boolean containsValue(Object value) { synchronized(mutex) { return map.containsValue(value); } } - @Override - @Deprecated - public boolean containsKey(Object key) { synchronized(mutex) { return map.containsKey(key); } } - @Override - @Deprecated - public CLASS_VALUE_TYPE put(CLASS_TYPE key, CLASS_VALUE_TYPE value) { synchronized(mutex) { return map.put(key, value); } } - @Override - @Deprecated - public CLASS_VALUE_TYPE remove(Object key) { synchronized(mutex) { return map.remove(key); } } - @Override - @Deprecated - public void clear() { synchronized(mutex) { map.clear(); } } - @Override - @Deprecated - public CLASS_VALUE_TYPE putIfAbsent(CLASS_TYPE key, CLASS_VALUE_TYPE value) { synchronized(mutex) { return map.putIfAbsent(key, value); } } - @Override - @Deprecated - public boolean remove(Object key, Object value) { synchronized(mutex) { return map.remove(key, value); } } - @Override - @Deprecated - public boolean replace(CLASS_TYPE key, CLASS_VALUE_TYPE oldValue, CLASS_VALUE_TYPE newValue) { synchronized(mutex) { return map.replace(key, oldValue, newValue); } } - @Override - @Deprecated - public CLASS_VALUE_TYPE replace(CLASS_TYPE key, CLASS_VALUE_TYPE value) { synchronized(mutex) { return map.replace(key, value); } } - @Override - @Deprecated - public void replaceAll(BiFunction mappingFunction) { synchronized(mutex) { map.replaceAll(mappingFunction); } } - @Override - @Deprecated - public CLASS_VALUE_TYPE compute(CLASS_TYPE key, BiFunction mappingFunction) { synchronized(mutex) { return map.compute(key, mappingFunction); } } - @Override - @Deprecated - public CLASS_VALUE_TYPE computeIfAbsent(CLASS_TYPE key, Function mappingFunction) { synchronized(mutex) { return map.computeIfAbsent(key, mappingFunction); } } - @Override - @Deprecated - public CLASS_VALUE_TYPE computeIfPresent(CLASS_TYPE key, BiFunction mappingFunction) { synchronized(mutex) { return computeIfPresent(key, mappingFunction); } } - @Override - @Deprecated - public CLASS_VALUE_TYPE merge(CLASS_TYPE key, CLASS_VALUE_TYPE value, BiFunction mappingFunction) { synchronized(mutex) { return map.merge(key, value, mappingFunction); } } - @Override - @Deprecated - public void forEach(BiConsumer action) { synchronized(mutex) { map.forEach(action); } } -#endif - } +package speiger.src.collections.PACKAGE.utils.maps; + +#if !TYPE_BOOLEAN +import java.util.Map; +import java.util.Objects; +#if TYPE_OBJECT && SORTED_MAP_FEATURE +import java.util.Comparator; +#else if !TYPE_OBJECT +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +#endif +#endif +import java.util.function.Consumer; +#if !TYPE_OBJECT && !TYPE_BOOLEAN +import java.util.function.Function; +#endif +#if VALUE_BOOLEAN && JDK_TYPE +import java.util.function.PREDICATE; +#endif + +import speiger.src.collections.objects.collections.ObjectIterable; +import speiger.src.collections.objects.collections.ObjectIterator; +import speiger.src.collections.objects.sets.ObjectSet; +import speiger.src.collections.objects.collections.ObjectBidirectionalIterator; +import speiger.src.collections.objects.utils.ObjectIterators; +import speiger.src.collections.objects.utils.ObjectSets; +#if !TYPE_OBJECT +import speiger.src.collections.objects.sets.ObjectOrderedSet; +#if SORTED_MAP_FEATURE +import speiger.src.collections.PACKAGE.functions.COMPARATOR; +#endif +#endif +import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; +#if !VALUE_BOOLEAN || !JDK_TYPE +import speiger.src.collections.PACKAGE.functions.function.FUNCTION; +#endif +import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; +import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +#if SORTED_MAP_FEATURE +import speiger.src.collections.PACKAGE.maps.interfaces.NAVIGABLE_MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.SORTED_MAP; +#endif +#if ORDERED_MAP_FEATURE +import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP; +#endif +#if SORTED_MAP_FEATURE +import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET; +import speiger.src.collections.PACKAGE.sets.SORTED_SET; +#endif +#if ORDERED_MAP_FEATURE +import speiger.src.collections.PACKAGE.sets.ORDERED_SET; +#endif +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.sets.SET; +import speiger.src.collections.PACKAGE.utils.SETS; +#endif +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; +#if !SAME_TYPE +import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR; +#endif +import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_SUPPLIER; +import speiger.src.collections.VALUE_PACKAGE.utils.VALUE_COLLECTIONS; + +/** + * A Helper class that provides you with Singleton/Empty/Synchronized/Unmodifyable Maps + */ +public class MAPS +{ +#if !TYPE_BOOLEAN + /** + * Empty Map Variable + */ + private static final MAP NO_KV_GENERIC_TYPE EMPTY = new EmptyMapKV_BRACES(); + + /** + * Empty Map getter function that autocasts to the desired Key and Value + * @Type(T) + * @ValueType(V) + * @return empty map of desired type + */ + public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE empty() { +#if TYPE_OBJECT || VALUE_OBJECT + return (MAP KEY_VALUE_GENERIC_TYPE)EMPTY; +#else + return EMPTY; +#endif + } + +#endif + /** + * Helper method that provides the fastIterator that recycles a single Entry to increase throughput. + * @param map the map the fastIterator should be accessed from + * @Type(T) + * @ValueType(V) + * @return either a normal iterator if it does not support this feature to a fastIterator + */ + public static GENERIC_KEY_VALUE_BRACES ObjectIterator fastIterator(MAP KEY_VALUE_GENERIC_TYPE map) { + ObjectSet entries = map.ENTRY_SET(); + return entries instanceof MAP.FastEntrySet ? ((MAP.FastEntrySet KEY_VALUE_GENERIC_TYPE)entries).fastIterator() : entries.iterator(); + } + + /** + * Helper method that provides the fastIterable that recycles a single Entry to increase throughput. + * @param map the map the fastIterable should be accessed from + * @Type(T) + * @ValueType(V) + * @return either a normal iterable if it does not support this feature to a fastIterable + */ + public static GENERIC_KEY_VALUE_BRACES ObjectIterable fastIterable(MAP KEY_VALUE_GENERIC_TYPE map) { + ObjectSet entries = map.ENTRY_SET(); + return map instanceof MAP.FastEntrySet ? new ObjectIterable(){ + @Override + public ObjectIterator iterator() { return ((MAP.FastEntrySet KEY_VALUE_GENERIC_TYPE)entries).fastIterator(); } + @Override + public void forEach(Consumer action) { ((MAP.FastEntrySet KEY_VALUE_GENERIC_TYPE)entries).fastForEach(action); } + } : entries; + } + + /** + * A Helper function that provides a faster forEach iterator implementation that recycles the entry to increase throughput + * @param map the map the fast forEach should be accessed from + * @param action the action that should be performed on each entry + * @Type(T) + * @ValueType(V) + * @note if the fast forEach is not supported will default to a normal forEach + */ + public static GENERIC_KEY_VALUE_BRACES void fastForEach(MAP KEY_VALUE_GENERIC_TYPE map, Consumer action) { + ObjectSet entries = map.ENTRY_SET(); + if(entries instanceof MAP.FastEntrySet) ((MAP.FastEntrySet KEY_VALUE_GENERIC_TYPE)entries).fastForEach(action); + else entries.forEach(action); + } + + /** + * Helper function that creates a Helper wrapper to synchronize access into the map. + * @param map the map that should be synchronized + * @Type(T) + * @ValueType(V) + * @return a synchronized Map + * @note if the inputted map is already synchronized then it will just return it instead + * @note iterators do not support synchronization + */ + public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE synchronize(MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof SynchronizedMap ? map : new SynchronizedMapKV_BRACES(map); } + /** + * Helper function that creates a Helper wrapper to synchronize access with custom access control into the map. + * @param map the map that should be synchronized + * @param mutex the object that controls access + * @Type(T) + * @ValueType(V) + * @return a synchronized Map + * @note if the inputted map is already synchronized then it will just return it instead + * @note iterators do not support synchronization + */ + public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE synchronize(MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { return map instanceof SynchronizedMap ? map : new SynchronizedMapKV_BRACES(map, mutex); } + +#if SORTED_MAP_FEATURE + /** + * Helper function that creates a Helper wrapper to synchronize access into the SortedMap. + * @param map the SortedMap that should be synchronized + * @Type(T) + * @ValueType(V) + * @return a synchronized SortedMap + * @note if the inputted map is already synchronized then it will just return it instead + * @note iterators do not support synchronization + */ + public static GENERIC_KEY_VALUE_BRACES SORTED_MAP KEY_VALUE_GENERIC_TYPE synchronize(SORTED_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof SynchronizedSortedMap ? map : new SynchronizedSortedMapKV_BRACES(map); } + /** + * Helper function that creates a Helper wrapper to synchronize access with custom access control into the SortedMap. + * @param map the SortedMap that should be synchronized + * @param mutex the object that controls access + * @Type(T) + * @ValueType(V) + * @return a synchronized SortedMap + * @note if the inputted map is already synchronized then it will just return it instead + * @note iterators do not support synchronization + */ + public static GENERIC_KEY_VALUE_BRACES SORTED_MAP KEY_VALUE_GENERIC_TYPE synchronize(SORTED_MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { return map instanceof SynchronizedSortedMap ? map : new SynchronizedSortedMapKV_BRACES(map, mutex); } + +#endif +#if ORDERED_MAP_FEATURE + /** + * Helper function that creates a Helper wrapper to synchronize access into the OrderedMap. + * @param map the OrderedMap that should be synchronized + * @Type(T) + * @ValueType(V) + * @return a synchronized OrderedMap + * @note if the inputted map is already synchronized then it will just return it instead + * @note iterators do not support synchronization + */ + public static GENERIC_KEY_VALUE_BRACES ORDERED_MAP KEY_VALUE_GENERIC_TYPE synchronize(ORDERED_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof SynchronizedOrderedMap ? map : new SynchronizedOrderedMapKV_BRACES(map); } + /** + * Helper function that creates a Helper wrapper to synchronize access with custom access control into the OrderedMap. + * @param map the OrderedMap that should be synchronized + * @param mutex the object that controls access + * @Type(T) + * @ValueType(V) + * @return a synchronized OrderedMap + * @note if the inputted map is already synchronized then it will just return it instead + * @note iterators do not support synchronization + */ + public static GENERIC_KEY_VALUE_BRACES ORDERED_MAP KEY_VALUE_GENERIC_TYPE synchronize(ORDERED_MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { return map instanceof SynchronizedOrderedMap ? map : new SynchronizedOrderedMapKV_BRACES(map, mutex); } + +#endif +#if SORTED_MAP_FEATURE + /** + * Helper function that creates a Helper wrapper to synchronize access into the NavigableMap. + * @param map the NavigableMap that should be synchronized + * @Type(T) + * @ValueType(V) + * @return a synchronized NavigableMap + * @note if the inputted map is already synchronized then it will just return it instead + * @note iterators do not support synchronization + */ + public static GENERIC_KEY_VALUE_BRACES NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE synchronize(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof SynchronizedNavigableMap ? map : new SynchronizedNavigableMapKV_BRACES(map); } + /** + * Helper function that creates a Helper wrapper to synchronize access with custom access control into the NavigableMap. + * @param map the NavigableMap that should be synchronized + * @param mutex the object that controls access + * @Type(T) + * @ValueType(V) + * @return a synchronized NavigableMap + * @note if the inputted map is already synchronized then it will just return it instead + * @note iterators do not support synchronization + */ + public static GENERIC_KEY_VALUE_BRACES NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE synchronize(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { return map instanceof SynchronizedNavigableMap ? map : new SynchronizedNavigableMapKV_BRACES(map, mutex); } + +#endif + /** + * A Helper function that creates a Helper wrapper to only allow Read Access into the Map + * @param map the map that should be made Unmodifiable + * @Type(T) + * @ValueType(V) + * @return a unmodifiable Map + * @note if the inputted map is already unmodifiable then it will just return it instead + */ + public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE unmodifiable(MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof UnmodifyableMap ? map : new UnmodifyableMapKV_BRACES(map); } + +#if ORDERED_MAP_FEATURE + /** + * A Helper function that creates a Helper wrapper to only allow Read Access into the OrderedMap + * @param map the OrderedMap that should be made Unmodifiable + * @Type(T) + * @ValueType(V) + * @return a unmodifiable OrderedMap + * @note if the inputted OrderedMap is already unmodifiable then it will just return it instead + */ + public static GENERIC_KEY_VALUE_BRACES ORDERED_MAP KEY_VALUE_GENERIC_TYPE unmodifiable(ORDERED_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof UnmodifyableOrderedMap ? map : new UnmodifyableOrderedMapKV_BRACES(map); } + +#endif +#if SORTED_MAP_FEATURE + /** + * A Helper function that creates a Helper wrapper to only allow Read Access into the SortedMap + * @param map the SortedMap that should be made Unmodifiable + * @Type(T) + * @ValueType(V) + * @return a unmodifiable SortedMap + * @note if the inputted SortedMap is already unmodifiable then it will just return it instead + */ + public static GENERIC_KEY_VALUE_BRACES SORTED_MAP KEY_VALUE_GENERIC_TYPE unmodifiable(SORTED_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof UnmodifyableSortedMap ? map : new UnmodifyableSortedMapKV_BRACES(map); } + + /** + * A Helper function that creates a Helper wrapper to only allow Read Access into NavigableMap Map + * @param map the NavigableMap that should be made Unmodifiable + * @Type(T) + * @ValueType(V) + * @return a unmodifiable NavigableMap + * @note if the inputted NavigableMap is already unmodifiable then it will just return it instead + */ + public static GENERIC_KEY_VALUE_BRACES NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE unmodifiable(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof UnmodifyableNavigableMap ? map : new UnmodifyableNavigableMapKV_BRACES(map); } + +#endif + /** + * A Helper function that creates a Unmodifyable Entry + * @param entry the Entry that should be made unmodifiable + * @Type(T) + * @ValueType(V) + * @return a Unmodifyable Entry + */ + public static GENERIC_KEY_VALUE_BRACES MAP.Entry KEY_VALUE_GENERIC_TYPE unmodifiable(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { return entry instanceof UnmodifyableEntry ? entry : (entry == null ? null : new UnmodifyableEntryKV_BRACES(entry)); } + /** + * A Helper function that creates a Unmodifyable Entry + * @param entry the Entry that should be made unmodifiable + * @Type(T) + * @ValueType(V) + * @return a Unmodifyable Entry + */ + public static GENERIC_KEY_VALUE_BRACES MAP.Entry KEY_VALUE_GENERIC_TYPE unmodifiable(Map.Entry entry) { return entry instanceof UnmodifyableEntry ? (UnmodifyableEntry KEY_VALUE_GENERIC_TYPE)entry : (entry == null ? null : new UnmodifyableEntryKV_BRACES(entry)); } + + /** + * Creates a Singleton map from the provided values. + * This reduces overhead that normal Map implementations have. + * @param key the key that should be turned into a singleton + * @param value the value that should be turned into a singleton + * @Type(T) + * @ValueType(V) + * @return a unmodifiable Singleton map. + */ + public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE singleton(KEY_TYPE key, VALUE_TYPE value) { return new SingletonMapKV_BRACES(key, value); } + + /** + * Singleton Map instance that is used in the helper method + * @Type(T) + * @ValueType(V) + */ + public static class SingletonMap KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE { + final KEY_TYPE key; + final VALUE_TYPE value; + SET KEY_GENERIC_TYPE keySet; + VALUE_COLLECTION VALUE_GENERIC_TYPE values; + ObjectSet entrySet; + + SingletonMap(KEY_TYPE key, VALUE_TYPE value) { + this.key = key; + this.value = value; + } + + @Override + public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } + @Override + public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } +#if VALUE_PRIMITIVES + @Override + public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } + @Override + public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } +#endif + @Override + public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { throw new UnsupportedOperationException(); } + @Override + public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { throw new UnsupportedOperationException(); } +#if !TYPE_OBJECT || !VALUE_OBJECT + @Override + public boolean remove(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } +#endif + @Override + public VALUE_TYPE GET_VALUE(KEY_TYPE key) { return EQUALS_KEY_TYPE(key, this.key) ? value : getDefaultReturnValue(); } +#if !TYPE_OBJECT || !VALUE_OBJECT + @Override + public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { return EQUALS_KEY_TYPE(key, this.key) ? value : defaultValue; } +#endif + @Override + public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } + @Override + public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } + @Override + public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } + @Override + public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) { throw new UnsupportedOperationException(); } + @Override + public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } + @Override + public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } + @Override + public SingletonMap KEY_VALUE_GENERIC_TYPE copy() { return new SingletonMapKV_BRACES(key, value); } + @Override + public SET KEY_GENERIC_TYPE keySet() { + if(keySet == null) keySet = SETS.singleton(key); + return keySet; + } + + @Override + public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { + if(values == null) values = VALUE_COLLECTIONS.singleton(value); + return values; + } + @Override + public ObjectSet ENTRY_SET() { + if(entrySet == null) entrySet = ObjectSets.singleton(new ABSTRACT_MAP.BasicEntryKV_BRACES(key, value)); + return entrySet; + } + } + + /** + * Empty Map impementation that is used for the emptyMap() function + * @Type(T) + * @ValueType(V) + */ + public static class EmptyMap KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE { + @Override + public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } + @Override + public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } +#if VALUE_PRIMITIVES + @Override + public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } + @Override + public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } +#endif + @Override + public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { throw new UnsupportedOperationException(); } + @Override + public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { throw new UnsupportedOperationException(); } +#if !TYPE_OBJECT || !VALUE_OBJECT + @Override + public boolean remove(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } +#endif + @Override + public VALUE_TYPE GET_VALUE(KEY_TYPE key) { return getDefaultReturnValue(); } +#if !TYPE_OBJECT || !VALUE_OBJECT + @Override + public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { return defaultValue; } +#endif + @Override + public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } + @Override + public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } + @Override + public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } + @Override + public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) { throw new UnsupportedOperationException(); } + @Override + public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } + @Override + public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } + @Override + public SET KEY_GENERIC_TYPE keySet() { return SETS.empty(); } + @Override + public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { return VALUE_COLLECTIONS.empty(); } + @Override + public ObjectSet ENTRY_SET() { return ObjectSets.empty(); } + @Override + public EmptyMap KEY_VALUE_GENERIC_TYPE copy() { return this; } + } + + /** + * The Unmodifyable Entry implementation for the helper function unmodifiableEntry() + * @Type(T) + * @ValueType(V) + */ + public static class UnmodifyableEntry KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP.BasicEntry KEY_VALUE_GENERIC_TYPE { + + UnmodifyableEntry(Map.Entry entry) { + super(entry.getKey(), entry.getValue()); + } + + UnmodifyableEntry(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { + super(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); + } + + @Override + public void set(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } + } + +#if SORTED_MAP_FEATURE + /** + * The Unmodifyable Navigable Map implementation that is sued for the unmodifyableMap function + * @Type(T) + * @ValueType(V) + */ + public static class UnmodifyableNavigableMap KEY_VALUE_GENERIC_TYPE extends UnmodifyableSortedMap KEY_VALUE_GENERIC_TYPE implements NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE { + NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map; + + UnmodifyableNavigableMap(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map) { + super(map); + this.map = map; + } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap() { return MAPS.unmodifiable(map.descendingMap()); } + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE navigableKeySet() { return SETS.unmodifiable(map.navigableKeySet()); } + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE keySet() { return SETS.unmodifiable(map.keySet()); } + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE descendingKeySet() { return SETS.unmodifiable(map.descendingKeySet()); } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE firstEntry() { return MAPS.unmodifiable(map.firstEntry()); } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE lastEntry() { return MAPS.unmodifiable(map.lastEntry()); } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirstEntry() { throw new UnsupportedOperationException(); } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLastEntry() { throw new UnsupportedOperationException(); } + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, boolean fromInclusive, KEY_TYPE toKey, boolean toInclusive) { return MAPS.unmodifiable(map.subMap(fromKey, fromInclusive, toKey, toInclusive)); } + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey, boolean inclusive) { return MAPS.unmodifiable(map.headMap(toKey, inclusive)); } + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey, boolean inclusive) { return MAPS.unmodifiable(map.tailMap(fromKey, inclusive)); } + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, KEY_TYPE toKey) { return MAPS.unmodifiable(map.subMap(fromKey, toKey)); } + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey) { return MAPS.unmodifiable(map.headMap(toKey)); } + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey) { return MAPS.unmodifiable(map.tailMap(fromKey)); } +#if !TYPE_OBJECT + @Override + public void setDefaultMaxValue(KEY_TYPE e) { throw new UnsupportedOperationException(); } + @Override + public KEY_TYPE getDefaultMaxValue() { return map.getDefaultMaxValue(); } + @Override + public void setDefaultMinValue(KEY_TYPE e) { throw new UnsupportedOperationException(); } + @Override + public KEY_TYPE getDefaultMinValue() { return map.getDefaultMinValue(); } +#endif + @Override + public KEY_TYPE lowerKey(KEY_TYPE key) { return map.lowerKey(key); } + @Override + public KEY_TYPE higherKey(KEY_TYPE key) { return map.higherKey(key); } + @Override + public KEY_TYPE floorKey(KEY_TYPE key) { return map.floorKey(key); } + @Override + public KEY_TYPE ceilingKey(KEY_TYPE key) { return map.ceilingKey(key); } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE lowerEntry(KEY_TYPE key) { return MAPS.unmodifiable(map.lowerEntry(key)); } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE higherEntry(KEY_TYPE key) { return MAPS.unmodifiable(map.higherEntry(key)); } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE floorEntry(KEY_TYPE key) { return MAPS.unmodifiable(map.floorEntry(key)); } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE ceilingEntry(KEY_TYPE key) { return MAPS.unmodifiable(map.ceilingEntry(key)); } + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE copy() { return map.copy(); } + } + +#endif +#if ORDERED_MAP_FEATURE + /** + * The Unmodifyable Ordered Map implementation that is sued for the unmodifyableMap function + * @Type(T) + * @ValueType(V) + */ + public static class UnmodifyableOrderedMap KEY_VALUE_GENERIC_TYPE extends UnmodifyableMap KEY_VALUE_GENERIC_TYPE implements ORDERED_MAP KEY_VALUE_GENERIC_TYPE { + ORDERED_MAP KEY_VALUE_GENERIC_TYPE map; + + UnmodifyableOrderedMap(ORDERED_MAP KEY_VALUE_GENERIC_TYPE map) { + super(map); + this.map = map; + } + + @Override + public VALUE_TYPE putAndMoveToFirst(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } + @Override + public VALUE_TYPE putAndMoveToLast(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } + @Override + public boolean moveToFirst(KEY_TYPE key) { throw new UnsupportedOperationException(); } + @Override + public boolean moveToLast(KEY_TYPE key) { throw new UnsupportedOperationException(); } + @Override + public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key) { throw new UnsupportedOperationException(); } + @Override + public VALUE_TYPE getAndMoveToLast(KEY_TYPE key) { throw new UnsupportedOperationException(); } + @Override + public KEY_TYPE FIRST_ENTRY_KEY() { return map.FIRST_ENTRY_KEY(); } + @Override + public KEY_TYPE POLL_FIRST_ENTRY_KEY() { throw new UnsupportedOperationException(); } + @Override + public KEY_TYPE LAST_ENTRY_KEY() { return map.LAST_ENTRY_KEY(); } + @Override + public KEY_TYPE POLL_LAST_ENTRY_KEY() { throw new UnsupportedOperationException(); } + @Override + public VALUE_TYPE FIRST_ENTRY_VALUE() { return map.FIRST_ENTRY_VALUE(); } + @Override + public VALUE_TYPE LAST_ENTRY_VALUE() { return map.LAST_ENTRY_VALUE(); } + @Override + public ORDERED_MAP KEY_VALUE_GENERIC_TYPE copy() { return map.copy(); } + @Override + public ORDERED_SET KEY_GENERIC_TYPE keySet() { + if(keys == null) keys = SETS.unmodifiable(map.keySet()); + return (ORDERED_SET KEY_GENERIC_TYPE)keys; + } + + @Override + public ObjectOrderedSet ENTRY_SET() { + if(entrySet == null) entrySet = new UnmodifyableOrderedEntrySetKV_BRACES(map.ENTRY_SET()); + return (ObjectOrderedSet)entrySet; + } + } + +#endif +#if SORTED_MAP_FEATURE + /** + * The Unmodifyable Sorted Map implementation that is sued for the unmodifyableMap function + * @Type(T) + * @ValueType(V) + */ + public static class UnmodifyableSortedMap KEY_VALUE_GENERIC_TYPE extends UnmodifyableMap KEY_VALUE_GENERIC_TYPE implements SORTED_MAP KEY_VALUE_GENERIC_TYPE { + SORTED_MAP KEY_VALUE_GENERIC_TYPE map; + + UnmodifyableSortedMap(SORTED_MAP KEY_VALUE_GENERIC_TYPE map) { + super(map); + this.map = map; + } + + @Override + public COMPARATOR KEY_GENERIC_TYPE comparator() { return map.comparator(); } + @Override + public SORTED_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, KEY_TYPE toKey) { return MAPS.unmodifiable(map.subMap(fromKey, toKey)); } + @Override + public SORTED_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey) { return MAPS.unmodifiable(map.headMap(toKey)); } + @Override + public SORTED_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey) { return MAPS.unmodifiable(map.tailMap(fromKey)); } + @Override + public SORTED_SET KEY_GENERIC_TYPE keySet() { return SETS.unmodifiable(map.keySet()); } + @Override + public KEY_TYPE FIRST_ENTRY_KEY() { return map.FIRST_ENTRY_KEY(); } + @Override + public KEY_TYPE POLL_FIRST_ENTRY_KEY() { throw new UnsupportedOperationException(); } + @Override + public KEY_TYPE LAST_ENTRY_KEY() { return map.LAST_ENTRY_KEY(); } + @Override + public KEY_TYPE POLL_LAST_ENTRY_KEY() { throw new UnsupportedOperationException(); } + @Override + public VALUE_TYPE FIRST_ENTRY_VALUE() { return map.FIRST_ENTRY_VALUE(); } + @Override + public VALUE_TYPE LAST_ENTRY_VALUE() { return map.LAST_ENTRY_VALUE(); } + @Override + public SORTED_MAP KEY_VALUE_GENERIC_TYPE copy() { return map.copy(); } + } + +#endif + /** + * The Unmodifyable Map implementation that is sued for the unmodifyableMap function + * @Type(T) + * @ValueType(V) + */ + public static class UnmodifyableMap KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements MAP KEY_VALUE_GENERIC_TYPE { + MAP KEY_VALUE_GENERIC_TYPE map; + VALUE_COLLECTION VALUE_GENERIC_TYPE values; + SET KEY_GENERIC_TYPE keys; + ObjectSet entrySet; + + UnmodifyableMap(MAP KEY_VALUE_GENERIC_TYPE map) { + this.map = map; + } + + @Override + public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } + @Override + public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value){ throw new UnsupportedOperationException(); } +#if VALUE_PRIMITIVES + @Override + public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } + @Override + public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } +#endif + @Override + public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { throw new UnsupportedOperationException(); } + @Override + public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { throw new UnsupportedOperationException(); } +#if !TYPE_OBJECT || !VALUE_OBJECT + @Override + public boolean remove(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } +#endif + @Override + public VALUE_TYPE GET_VALUE(KEY_TYPE key) { + VALUE_TYPE type = map.GET_VALUE(key); + return VALUE_EQUALS(type, map.getDefaultReturnValue()) && !map.containsKey(key) ? getDefaultReturnValue() : type; + } +#if !TYPE_OBJECT || !VALUE_OBJECT + @Override + public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { return map.getOrDefault(key, defaultValue); } +#endif + @Override + public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } + @Override + public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } + @Override + public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } + @Override + public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) { throw new UnsupportedOperationException(); } + @Override + public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } + @Override + public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } + @Override + public void REPLACE_VALUES(UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { throw new UnsupportedOperationException(); } + @Override + public void REPLACE_VALUES(MAP KEY_VALUE_GENERIC_TYPE m) { throw new UnsupportedOperationException(); } + @Override + public MAP KEY_VALUE_GENERIC_TYPE copy() { return map.copy(); } + @Override + public void clear() { throw new UnsupportedOperationException(); } + + @Override + public SET KEY_GENERIC_TYPE keySet() { + if(keys == null) keys = SETS.unmodifiable(map.keySet()); + return keys; + } + + @Override + public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { + if(values == null) values = VALUE_COLLECTIONS.unmodifiable(map.values()); + return values; + } + + @Override + public ObjectSet ENTRY_SET() { + if(entrySet == null) entrySet = new UnmodifyableEntrySetKV_BRACES(map.ENTRY_SET()); + return entrySet; + } + } + +#if ORDERED_MAP_FEATURE + /** + * The Unmodifyable Ordered Set implementation for the Unmodifyable Ordered Map implementation + * @Type(T) + * @ValueType(V) + */ + public static class UnmodifyableOrderedEntrySet KEY_VALUE_GENERIC_TYPE extends UnmodifyableEntrySet KEY_VALUE_GENERIC_TYPE implements ObjectOrderedSet + { + ObjectOrderedSet set; + + UnmodifyableOrderedEntrySet(ObjectOrderedSet c) { + super(c); + set = c; + } + + @Override + public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } + @Override + public boolean addAndMoveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } + @Override + public boolean moveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } + @Override + public boolean moveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } + @Override + public ObjectOrderedSet copy() { return set.copy(); } + @Override + public ObjectBidirectionalIterator iterator() { return ObjectIterators.unmodifiable(set.iterator()); } + @Override + public ObjectBidirectionalIterator iterator(MAP.Entry KEY_VALUE_GENERIC_TYPE fromElement) { return ObjectIterators.unmodifiable(set.iterator(fromElement)); } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE first() { return set.first(); } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirst() { throw new UnsupportedOperationException(); } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE last() { return set.last(); } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLast() { throw new UnsupportedOperationException(); } + } + +#endif + /** + * The Unmodifyable Set implementation for the Unmodifyable Map implementation + * @Type(T) + * @ValueType(V) + */ + public static class UnmodifyableEntrySet KEY_VALUE_GENERIC_TYPE extends ObjectSets.UnmodifiableSet + { + ObjectSet s; + + UnmodifyableEntrySet(ObjectSet c) + { + super(c); + s = c; + } + + @Override + public void forEach(Consumer action) { + s.forEach(T -> action.accept(MAPS.unmodifiable(T))); + } + + @Override + public ObjectIterator iterator() { + return new ObjectIterator() { + ObjectIterator iter = s.iterator(); + @Override + public boolean hasNext() { return iter.hasNext(); } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { return MAPS.unmodifiable(iter.next()); } + }; + } + + } + +#if SORTED_MAP_FEATURE + /** + * The Synchronized Navigable Map implementation used by the synchronizedMap helper function + * @Type(T) + * @ValueType(V) + */ + public static class SynchronizedNavigableMap KEY_VALUE_GENERIC_TYPE extends SynchronizedSortedMap KEY_VALUE_GENERIC_TYPE implements NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE { + NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map; + + SynchronizedNavigableMap(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map) { + super(map); + this.map = map; + } + + SynchronizedNavigableMap(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { + super(map, mutex); + this.map = map; + } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap() { synchronized(mutex) { return MAPS.synchronize(map.descendingMap(), mutex); } } + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE navigableKeySet() { synchronized(mutex) { return SETS.synchronize(map.navigableKeySet(), mutex); } } + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE descendingKeySet() { synchronized(mutex) { return SETS.synchronize(map.descendingKeySet(), mutex); } } + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE keySet() { synchronized(mutex) { return SETS.synchronize(map.keySet(), mutex); } } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE firstEntry() { synchronized(mutex) { return map.firstEntry(); } } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE lastEntry() { synchronized(mutex) { return map.lastEntry(); } } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirstEntry() { synchronized(mutex) { return map.pollFirstEntry(); } } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLastEntry() { synchronized(mutex) { return map.pollLastEntry(); } } + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, boolean fromInclusive, KEY_TYPE toKey, boolean toInclusive) { synchronized(mutex) { return MAPS.synchronize(map.subMap(fromKey, fromInclusive, toKey, toInclusive), mutex); } } + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey, boolean inclusive) { synchronized(mutex) { return MAPS.synchronize(map.headMap(toKey, inclusive), mutex); } } + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey, boolean inclusive) { synchronized(mutex) { return MAPS.synchronize(map.tailMap(fromKey, inclusive), mutex); } } + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, KEY_TYPE toKey) { synchronized(mutex) { return MAPS.synchronize(map.subMap(fromKey, toKey), mutex); } } + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey) { synchronized(mutex) { return MAPS.synchronize(map.headMap(toKey), mutex); } } + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey) { synchronized(mutex) { return MAPS.synchronize(map.tailMap(fromKey), mutex); } } + @Override + public KEY_TYPE lowerKey(KEY_TYPE key) { synchronized(mutex) { return map.lowerKey(key); } } + @Override + public KEY_TYPE higherKey(KEY_TYPE key) { synchronized(mutex) { return map.higherKey(key); } } + @Override + public KEY_TYPE floorKey(KEY_TYPE key) { synchronized(mutex) { return map.floorKey(key); } } + @Override + public KEY_TYPE ceilingKey(KEY_TYPE key) { synchronized(mutex) { return map.ceilingKey(key); } } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE lowerEntry(KEY_TYPE key) { synchronized(mutex) { return map.lowerEntry(key); } } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE higherEntry(KEY_TYPE key) { synchronized(mutex) { return map.higherEntry(key); } } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE floorEntry(KEY_TYPE key) { synchronized(mutex) { return map.floorEntry(key); } } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE ceilingEntry(KEY_TYPE key) { synchronized(mutex) { return map.ceilingEntry(key); } } + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE copy() { synchronized(mutex) { return map.copy(); } } +#if !TYPE_OBJECT + @Override + @Deprecated + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(CLASS_TYPE fromKey, boolean fromInclusive, CLASS_TYPE toKey, boolean toInclusive) { synchronized(mutex) { return MAPS.synchronize(map.subMap(fromKey, fromInclusive, toKey, toInclusive), mutex); } } + @Override + @Deprecated + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(CLASS_TYPE toKey, boolean inclusive) { synchronized(mutex) { return MAPS.synchronize(map.headMap(toKey, inclusive), mutex); } } + @Override + @Deprecated + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(CLASS_TYPE fromKey, boolean inclusive) { synchronized(mutex) { return MAPS.synchronize(map.tailMap(fromKey, inclusive), mutex); } } + @Override + @Deprecated + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(CLASS_TYPE fromKey, CLASS_TYPE toKey) { synchronized(mutex) { return MAPS.synchronize(map.subMap(fromKey, toKey), mutex); } } + @Override + @Deprecated + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(CLASS_TYPE toKey) { synchronized(mutex) { return MAPS.synchronize(map.headMap(toKey), mutex); } } + @Override + @Deprecated + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(CLASS_TYPE fromKey) { synchronized(mutex) { return MAPS.synchronize(map.tailMap(fromKey), mutex); } } + @Override + public void setDefaultMaxValue(KEY_TYPE e) { synchronized(mutex) { map.setDefaultMaxValue(e); } } + @Override + public KEY_TYPE getDefaultMaxValue() { synchronized(mutex) { return map.getDefaultMaxValue(); } } + @Override + public void setDefaultMinValue(KEY_TYPE e) { synchronized(mutex) { map.setDefaultMinValue(e); } } + @Override + public KEY_TYPE getDefaultMinValue() { synchronized(mutex) { return map.getDefaultMinValue(); } } + @Override + @Deprecated + public CLASS_TYPE lowerKey(CLASS_TYPE key) { synchronized(mutex) { return map.lowerKey(key); } } + @Override + @Deprecated + public CLASS_TYPE floorKey(CLASS_TYPE key) { synchronized(mutex) { return map.floorKey(key); } } + @Override + @Deprecated + public CLASS_TYPE ceilingKey(CLASS_TYPE key) { synchronized(mutex) { return map.ceilingKey(key); } } + @Override + @Deprecated + public CLASS_TYPE higherKey(CLASS_TYPE key) { synchronized(mutex) { return map.higherKey(key); } } + @Override + @Deprecated + public MAP.Entry KEY_VALUE_GENERIC_TYPE lowerEntry(CLASS_TYPE key) { synchronized(mutex) { return map.lowerEntry(key); } } + @Override + @Deprecated + public MAP.Entry KEY_VALUE_GENERIC_TYPE floorEntry(CLASS_TYPE key) { synchronized(mutex) { return map.floorEntry(key); } } + @Override + @Deprecated + public MAP.Entry KEY_VALUE_GENERIC_TYPE ceilingEntry(CLASS_TYPE key) { synchronized(mutex) { return map.ceilingEntry(key); } } + @Override + @Deprecated + public MAP.Entry KEY_VALUE_GENERIC_TYPE higherEntry(CLASS_TYPE key) { synchronized(mutex) { return map.higherEntry(key); } } +#endif + } + +#endif +#if ORDERED_MAP_FEATURE + /** + * The Synchronized Ordered Map implementation used by the synchronizedMap helper function + * @Type(T) + * @ValueType(V) + */ + public static class SynchronizedOrderedMap KEY_VALUE_GENERIC_TYPE extends SynchronizedMap KEY_VALUE_GENERIC_TYPE implements ORDERED_MAP KEY_VALUE_GENERIC_TYPE { + ORDERED_MAP KEY_VALUE_GENERIC_TYPE map; + + SynchronizedOrderedMap(ORDERED_MAP KEY_VALUE_GENERIC_TYPE map) { + super(map); + this.map = map; + } + + SynchronizedOrderedMap(ORDERED_MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { + super(map, mutex); + this.map = map; + } + + @Override + public VALUE_TYPE putAndMoveToFirst(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.putAndMoveToFirst(key, value); } } + @Override + public VALUE_TYPE putAndMoveToLast(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.putAndMoveToLast(key, value); } } + @Override + public boolean moveToFirst(KEY_TYPE key) { synchronized(mutex) { return map.moveToFirst(key); } } + @Override + public boolean moveToLast(KEY_TYPE key) { synchronized(mutex) { return map.moveToLast(key); } } + @Override + public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key) { synchronized(mutex) { return map.getAndMoveToFirst(key); } } + @Override + public VALUE_TYPE getAndMoveToLast(KEY_TYPE key) { synchronized(mutex) { return map.getAndMoveToLast(key); } } + @Override + public KEY_TYPE FIRST_ENTRY_KEY() { synchronized(mutex) { return map.FIRST_ENTRY_KEY(); } } + @Override + public KEY_TYPE POLL_FIRST_ENTRY_KEY() { synchronized(mutex) { return map.POLL_FIRST_ENTRY_KEY(); } } + @Override + public KEY_TYPE LAST_ENTRY_KEY() { synchronized(mutex) { return map.LAST_ENTRY_KEY(); } } + @Override + public KEY_TYPE POLL_LAST_ENTRY_KEY() { synchronized(mutex) { return map.POLL_LAST_ENTRY_KEY(); } } + @Override + public VALUE_TYPE FIRST_ENTRY_VALUE() { synchronized(mutex) { return map.FIRST_ENTRY_VALUE(); } } + @Override + public VALUE_TYPE LAST_ENTRY_VALUE() { synchronized(mutex) { return map.LAST_ENTRY_VALUE(); } } + @Override + public ORDERED_MAP KEY_VALUE_GENERIC_TYPE copy() { synchronized(mutex) { return map.copy(); } } + @Override + public ORDERED_SET KEY_GENERIC_TYPE keySet() { + if(keys == null) keys = SETS.synchronize(map.keySet(), mutex); + return (ORDERED_SET KEY_GENERIC_TYPE)keys; + } + + @Override + public ObjectOrderedSet ENTRY_SET() { + if(entrySet == null) entrySet = ObjectSets.synchronize(map.ENTRY_SET(), mutex); + return (ObjectOrderedSet)entrySet; + } + } + +#endif +#if SORTED_MAP_FEATURE + /** + * The Synchronized Sorted Map implementation used by the synchronizedMap helper function + * @Type(T) + * @ValueType(V) + */ + public static class SynchronizedSortedMap KEY_VALUE_GENERIC_TYPE extends SynchronizedMap KEY_VALUE_GENERIC_TYPE implements SORTED_MAP KEY_VALUE_GENERIC_TYPE { + SORTED_MAP KEY_VALUE_GENERIC_TYPE map; + + SynchronizedSortedMap(SORTED_MAP KEY_VALUE_GENERIC_TYPE map) { + super(map); + this.map = map; + } + + SynchronizedSortedMap(SORTED_MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { + super(map, mutex); + this.map = map; + } + + @Override + public COMPARATOR KEY_GENERIC_TYPE comparator() { synchronized(mutex) { return map.comparator(); } } + @Override + public SORTED_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, KEY_TYPE toKey) { synchronized(mutex) { return MAPS.synchronize(map.subMap(fromKey, toKey), mutex); } } + @Override + public SORTED_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey) { synchronized(mutex) { return MAPS.synchronize(map.headMap(toKey), mutex); } } + @Override + public SORTED_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey) { synchronized(mutex) { return MAPS.synchronize(map.tailMap(fromKey), mutex); } } + @Override + public SORTED_SET KEY_GENERIC_TYPE keySet() { synchronized(mutex) { return SETS.synchronize(map.keySet(), mutex); } } + @Override + public KEY_TYPE FIRST_ENTRY_KEY() { synchronized(mutex) { return map.FIRST_ENTRY_KEY(); } } + @Override + public KEY_TYPE POLL_FIRST_ENTRY_KEY() { synchronized(mutex) { return map.POLL_FIRST_ENTRY_KEY(); } } + @Override + public KEY_TYPE LAST_ENTRY_KEY() { synchronized(mutex) { return map.LAST_ENTRY_KEY(); } } + @Override + public KEY_TYPE POLL_LAST_ENTRY_KEY() { synchronized(mutex) { return map.POLL_LAST_ENTRY_KEY(); } } + @Override + public VALUE_TYPE FIRST_ENTRY_VALUE() { synchronized(mutex) { return map.FIRST_ENTRY_VALUE(); } } + @Override + public VALUE_TYPE LAST_ENTRY_VALUE() { synchronized(mutex) { return map.LAST_ENTRY_VALUE(); } } + @Override + public SORTED_MAP KEY_VALUE_GENERIC_TYPE copy() { synchronized(mutex) { return map.copy(); } } +#if !TYPE_OBJECT + @Override + @Deprecated + public CLASS_TYPE firstKey() { synchronized(mutex) { return map.firstKey(); } } + @Override + @Deprecated + public CLASS_TYPE lastKey() { synchronized(mutex) { return map.lastKey(); } } + @Override + @Deprecated + public SORTED_MAP KEY_VALUE_GENERIC_TYPE subMap(CLASS_TYPE fromKey, CLASS_TYPE toKey) { synchronized(mutex) { return MAPS.synchronize(map.subMap(fromKey, toKey), mutex); } } + @Override + @Deprecated + public SORTED_MAP KEY_VALUE_GENERIC_TYPE headMap(CLASS_TYPE toKey) { synchronized(mutex) { return MAPS.synchronize(map.headMap(toKey), mutex); } } + @Override + @Deprecated + public SORTED_MAP KEY_VALUE_GENERIC_TYPE tailMap(CLASS_TYPE fromKey) { synchronized(mutex) { return MAPS.synchronize(map.tailMap(fromKey), mutex); } } +#endif + } + +#endif + /** + * The Synchronized Map implementation used by the synchronizedMap helper function + * @Type(T) + * @ValueType(V) + */ + public static class SynchronizedMap KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements MAP KEY_VALUE_GENERIC_TYPE { + MAP KEY_VALUE_GENERIC_TYPE map; + VALUE_COLLECTION VALUE_GENERIC_TYPE values; + SET KEY_GENERIC_TYPE keys; + ObjectSet entrySet; + + protected Object mutex; + + SynchronizedMap(MAP KEY_VALUE_GENERIC_TYPE map) { + this.map = map; + mutex = this; + } + + SynchronizedMap(MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { + this.map = map; + this.mutex = mutex; + } + + @Override + public VALUE_TYPE getDefaultReturnValue() { synchronized(mutex) { return map.getDefaultReturnValue(); } } + @Override + public ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE setDefaultReturnValue(VALUE_TYPE v) { + synchronized(mutex) { + map.setDefaultReturnValue(v); + return this; + } + } + @Override + public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.put(key, value); } } + @Override + public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.putIfAbsent(key, value); } } + public void putAllIfAbsent(MAP KEY_VALUE_GENERIC_TYPE m) { synchronized(mutex) { map.putAllIfAbsent(m); } } +#if VALUE_PRIMITIVES + @Override + public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.addTo(key, value); } } + @Override + public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.subFrom(key, value); } } + public void addToAll(MAP KEY_VALUE_GENERIC_TYPE m) { synchronized(mutex) { map.addToAll(m); } } +#endif + @Override + public void putAll(MAP KEY_VALUE_GENERIC_TYPE m) { synchronized(mutex) { map.putAll(m); } } + @Override + public void putAll(Map m) { synchronized(mutex) { map.putAll(m); } } + @Override + public void putAll(KEY_TYPE[] keys, VALUE_TYPE[] values, int offset, int size) { synchronized(mutex) { map.putAll(keys, values, offset, size); } } + +#if !TYPE_OBJECT + @Override + public boolean containsKey(KEY_TYPE key) { synchronized(mutex) { return map.containsKey(key); } } +#endif +#if !VALUE_OBJECT + @Override + public boolean containsValue(VALUE_TYPE value) { synchronized(mutex) { return map.containsValue(value); } } +#endif + @Override + public VALUE_TYPE GET_VALUE(KEY_TYPE key) { synchronized(mutex) { return map.GET_VALUE(key); } } + @Override + public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { synchronized(mutex) { return map.REMOVE_VALUE(key); } } + @Override + public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { synchronized(mutex) { return map.REMOVE_VALUEOrDefault(key, defaultValue); } } +#if !TYPE_OBJECT || !VALUE_OBJECT + @Override + public boolean remove(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.remove(key, value); } } +#endif + @Override + public boolean replace(KEY_TYPE key, VALUE_TYPE oldValue, VALUE_TYPE newValue) { synchronized(mutex) { return map.replace(key, oldValue, newValue); } } + @Override + public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.replace(key, value); } } + @Override + public void REPLACE_VALUES(MAP KEY_VALUE_GENERIC_TYPE m) { synchronized(mutex) { map.REPLACE_VALUES(m); } } + @Override + public void REPLACE_VALUES(UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { synchronized(mutex) { map.REPLACE_VALUES(mappingFunction); } } + @Override + public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { synchronized(mutex) { return map.COMPUTE(key, mappingFunction); } } + @Override + public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) { synchronized(mutex) { return map.COMPUTE_IF_ABSENT(key, mappingFunction); } } + @Override + public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { synchronized(mutex) { return map.COMPUTE_IF_PRESENT(key, mappingFunction); } } + @Override + public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) { synchronized(mutex) { return map.SUPPLY_IF_ABSENT(key, valueProvider); } } + @Override + public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { synchronized(mutex) { return map.MERGE(key, value, mappingFunction); } } + @Override + public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { synchronized(mutex) { map.BULK_MERGE(m, mappingFunction); } } +#if !TYPE_OBJECT || !VALUE_OBJECT + @Override + public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { synchronized(mutex) { return map.getOrDefault(key, defaultValue); } } +#endif + @Override + public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { synchronized(mutex) { map.forEach(action); } } + @Override + public int size() { synchronized(mutex) { return map.size(); } } + @Override + public MAP KEY_VALUE_GENERIC_TYPE copy() { synchronized(mutex) { return map.copy(); } } + @Override + public SET KEY_GENERIC_TYPE keySet() { + if(keys == null) keys = SETS.synchronize(map.keySet(), mutex); + return keys; + } + + @Override + public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { + if(values == null) values = VALUE_COLLECTIONS.synchronize(map.values(), mutex); + return values; + } + + @Override + public ObjectSet ENTRY_SET() { + if(entrySet == null) entrySet = ObjectSets.synchronize(map.ENTRY_SET(), mutex); + return entrySet; + } + +#if !TYPE_OBJECT + @Override + @Deprecated + public CLASS_VALUE_TYPE get(Object key) { synchronized(mutex) { return map.get(key); } } + @Override + @Deprecated + public CLASS_VALUE_TYPE getOrDefault(Object key, CLASS_VALUE_TYPE defaultValue) { synchronized(mutex) { return map.getOrDefault(key, defaultValue); } } + @Override + @Deprecated + public boolean containsValue(Object value) { synchronized(mutex) { return map.containsValue(value); } } + @Override + @Deprecated + public boolean containsKey(Object key) { synchronized(mutex) { return map.containsKey(key); } } + @Override + @Deprecated + public CLASS_VALUE_TYPE put(CLASS_TYPE key, CLASS_VALUE_TYPE value) { synchronized(mutex) { return map.put(key, value); } } + @Override + @Deprecated + public CLASS_VALUE_TYPE remove(Object key) { synchronized(mutex) { return map.remove(key); } } + @Override + @Deprecated + public void clear() { synchronized(mutex) { map.clear(); } } + @Override + @Deprecated + public CLASS_VALUE_TYPE putIfAbsent(CLASS_TYPE key, CLASS_VALUE_TYPE value) { synchronized(mutex) { return map.putIfAbsent(key, value); } } + @Override + @Deprecated + public boolean remove(Object key, Object value) { synchronized(mutex) { return map.remove(key, value); } } + @Override + @Deprecated + public boolean replace(CLASS_TYPE key, CLASS_VALUE_TYPE oldValue, CLASS_VALUE_TYPE newValue) { synchronized(mutex) { return map.replace(key, oldValue, newValue); } } + @Override + @Deprecated + public CLASS_VALUE_TYPE replace(CLASS_TYPE key, CLASS_VALUE_TYPE value) { synchronized(mutex) { return map.replace(key, value); } } + @Override + @Deprecated + public void replaceAll(BiFunction mappingFunction) { synchronized(mutex) { map.replaceAll(mappingFunction); } } + @Override + @Deprecated + public CLASS_VALUE_TYPE compute(CLASS_TYPE key, BiFunction mappingFunction) { synchronized(mutex) { return map.compute(key, mappingFunction); } } + @Override + @Deprecated + public CLASS_VALUE_TYPE computeIfAbsent(CLASS_TYPE key, Function mappingFunction) { synchronized(mutex) { return map.computeIfAbsent(key, mappingFunction); } } + @Override + @Deprecated + public CLASS_VALUE_TYPE computeIfPresent(CLASS_TYPE key, BiFunction mappingFunction) { synchronized(mutex) { return computeIfPresent(key, mappingFunction); } } + @Override + @Deprecated + public CLASS_VALUE_TYPE merge(CLASS_TYPE key, CLASS_VALUE_TYPE value, BiFunction mappingFunction) { synchronized(mutex) { return map.merge(key, value, mappingFunction); } } + @Override + @Deprecated + public void forEach(BiConsumer action) { synchronized(mutex) { map.forEach(action); } } +#endif + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/builder/DequeueTestSuiteBuilder.template b/src/builder/resources/speiger/assets/testers/templates/builder/DequeueTestSuiteBuilder.template index 5f843f1..de49f37 100644 --- a/src/builder/resources/speiger/assets/testers/templates/builder/DequeueTestSuiteBuilder.template +++ b/src/builder/resources/speiger/assets/testers/templates/builder/DequeueTestSuiteBuilder.template @@ -1,28 +1,28 @@ -package speiger.src.testers.PACKAGE.builder; - -import java.util.List; - -import com.google.common.collect.testing.AbstractTester; - -import speiger.src.testers.PACKAGE.generators.TEST_QUEUE_GENERATOR; -import speiger.src.testers.PACKAGE.tests.queue.FILE_KEY_TYPEDequeueDequeueTester; -import speiger.src.testers.PACKAGE.tests.queue.FILE_KEY_TYPEDequeueEnqueueTester; -import speiger.src.testers.PACKAGE.tests.queue.FILE_KEY_TYPEDequeueLastTester; - -@SuppressWarnings("javadoc") -public class DEQUEUE_TEST_BUILDER KEY_GENERIC_TYPE extends QUEUE_TEST_BUILDER KEY_GENERIC_TYPE -{ - public static GENERIC_KEY_BRACES DEQUEUE_TEST_BUILDER KEY_GENERIC_TYPE using(TEST_QUEUE_GENERATOR KEY_GENERIC_TYPE builder) { - return (DEQUEUE_TEST_BUILDER KEY_GENERIC_TYPE)new DEQUEUE_TEST_BUILDER KEY_GENERIC_TYPE().usingGenerator(builder); - } - - @Override - @SuppressWarnings("rawtypes") - protected List> getTesters() { - List> tester = super.getTesters(); - tester.add(FILE_KEY_TYPEDequeueDequeueTester.class); - tester.add(FILE_KEY_TYPEDequeueEnqueueTester.class); - tester.add(FILE_KEY_TYPEDequeueLastTester.class); - return tester; - } -} +package speiger.src.testers.PACKAGE.builder; + +import java.util.List; + +import com.google.common.collect.testing.AbstractTester; + +import speiger.src.testers.PACKAGE.generators.TEST_QUEUE_GENERATOR; +import speiger.src.testers.PACKAGE.tests.queue.FILE_KEY_TYPEDequeueDequeueTester; +import speiger.src.testers.PACKAGE.tests.queue.FILE_KEY_TYPEDequeueEnqueueTester; +import speiger.src.testers.PACKAGE.tests.queue.FILE_KEY_TYPEDequeueLastTester; + +@SuppressWarnings("javadoc") +public class DEQUEUE_TEST_BUILDER KEY_GENERIC_TYPE extends QUEUE_TEST_BUILDER KEY_GENERIC_TYPE +{ + public static GENERIC_KEY_BRACES DEQUEUE_TEST_BUILDER KEY_GENERIC_TYPE using(TEST_QUEUE_GENERATOR KEY_GENERIC_TYPE builder) { + return (DEQUEUE_TEST_BUILDER KEY_GENERIC_TYPE)new DEQUEUE_TEST_BUILDER KEY_GENERIC_TYPE().usingGenerator(builder); + } + + @Override + @SuppressWarnings("rawtypes") + protected List> getTesters() { + List> tester = super.getTesters(); + tester.add(FILE_KEY_TYPEDequeueDequeueTester.class); + tester.add(FILE_KEY_TYPEDequeueEnqueueTester.class); + tester.add(FILE_KEY_TYPEDequeueLastTester.class); + return tester; + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/builder/ListTestSuiteBuilder.template b/src/builder/resources/speiger/assets/testers/templates/builder/ListTestSuiteBuilder.template index d4fac2e..0c89b3f 100644 --- a/src/builder/resources/speiger/assets/testers/templates/builder/ListTestSuiteBuilder.template +++ b/src/builder/resources/speiger/assets/testers/templates/builder/ListTestSuiteBuilder.template @@ -1,384 +1,384 @@ -package speiger.src.testers.PACKAGE.builder; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; -import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE; -import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS; -#endignore - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import com.google.common.collect.testing.AbstractTester; -import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder; -import com.google.common.collect.testing.Helpers; -import com.google.common.collect.testing.ListTestSuiteBuilder; -import com.google.common.collect.testing.OneSizeTestContainerGenerator; -import com.google.common.collect.testing.SampleElements; -import com.google.common.collect.testing.TestListGenerator; -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.Feature; -import com.google.common.collect.testing.testers.CollectionSerializationEqualTester; -import com.google.common.collect.testing.testers.ListAddAllAtIndexTester; -import com.google.common.collect.testing.testers.ListAddAllTester; -import com.google.common.collect.testing.testers.ListAddAtIndexTester; -import com.google.common.collect.testing.testers.ListAddTester; -import com.google.common.collect.testing.testers.ListCreationTester; -import com.google.common.collect.testing.testers.ListEqualsTester; -import com.google.common.collect.testing.testers.ListGetTester; -import com.google.common.collect.testing.testers.ListHashCodeTester; -import com.google.common.collect.testing.testers.ListIndexOfTester; -import com.google.common.collect.testing.testers.ListLastIndexOfTester; -import com.google.common.collect.testing.testers.ListRemoveAllTester; -import com.google.common.collect.testing.testers.ListRemoveAtIndexTester; -import com.google.common.collect.testing.testers.ListRemoveTester; -import com.google.common.collect.testing.testers.ListReplaceAllTester; -import com.google.common.collect.testing.testers.ListRetainAllTester; -import com.google.common.collect.testing.testers.ListSetTester; -import com.google.common.collect.testing.testers.ListSubListTester; -import com.google.common.collect.testing.testers.ListToArrayTester; -import com.google.common.testing.SerializableTester; - -import junit.framework.TestSuite; -import speiger.src.collections.PACKAGE.collections.ITERABLE; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.testers.base.tests.list.JavaListListIteratorTester; -import speiger.src.testers.PACKAGE.generators.TEST_LIST_GENERATOR; -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListAbsentTester; -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListAddAllArrayAtIndexTester; -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListAddAllAtIndexTester; -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListAddAllListAtIndexTester; -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListAddAllTester; -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListAddAtIndexTester; -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListAddTester; -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListCreationTester; -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListEqualsTester; -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListExtractElementsTester; -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListGetElementsTester; -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListGetTester; -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListIndexOfTester; -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListLastIndexOfTester; -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListListIteratorTester; -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListPresentTester; -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListRemoveAllTester; -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListRemoveAtIndexTester; -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListRemoveElementsTester; -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListRemoveTester; -#if !TYPE_BOOLEAN -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListSortTester; -#if !TYPE_OBJECT -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListFillBufferTester; -#endif -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListReplaceAllTester; -#endif -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListRetainAllTester; -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListSetTester; -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListSubListTester; -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListSwapRemoveAtIndexTester; -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListSwapRemoveTester; -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListToArrayTester; -import speiger.src.testers.PACKAGE.utils.SAMPLE_ELEMENTS; -#if !TYPE_BOOLEAN -import speiger.src.testers.utils.SpecialFeature; -#endif - -@SuppressWarnings("javadoc") -public class LIST_TEST_BUILDER KEY_GENERIC_TYPE extends COLLECTION_TEST_BUILDER KEY_GENERIC_TYPE { - -#if TYPE_OBJECT - KEY_TYPE[] prefixes; - KEY_TYPE[] suffixes; -#else - KEY_TYPE[] prefixes = createPrefixes(); - KEY_TYPE[] suffixes = createSuffixes(); -#endif - - public static GENERIC_KEY_BRACES LIST_TEST_BUILDER KEY_GENERIC_TYPE using(TEST_LIST_GENERATOR KEY_GENERIC_TYPE generator) { - return (LIST_TEST_BUILDER KEY_GENERIC_TYPE) new LIST_TEST_BUILDER KEY_GENERIC_TYPE().usingGenerator(generator); - } - - public LIST_TEST_BUILDER KEY_GENERIC_TYPE setPrefixes(KEY_TYPE[] prefixes) { - this.prefixes = prefixes; - return this; - } - - public LIST_TEST_BUILDER KEY_GENERIC_TYPE setSuffixes(KEY_TYPE[] suffixes) { - this.suffixes = suffixes; - return this; - } - -#if !TYPE_OBJECT - public KEY_TYPE[] createPrefixes() { -#if TYPE_BOOLEAN - return new KEY_TYPE[]{false, false, false}; -#else if TYPE_BYTE - return new KEY_TYPE[]{(byte)-3, (byte)-2, (byte)-1}; -#else if TYPE_SHORT - return new KEY_TYPE[]{(short)-3, (short)-2, (short)-1}; -#else if TYPE_CHAR - return new KEY_TYPE[]{'^', '_', '`'}; -#else - return new KEY_TYPE[]{-3, -2, -1}; -#endif - } - - public KEY_TYPE[] createSuffixes() { -#if TYPE_BOOLEAN - return new KEY_TYPE[]{true, true, true}; -#else if TYPE_BYTE - return new KEY_TYPE[]{(byte)5, (byte)6, (byte)7}; -#else if TYPE_SHORT - return new KEY_TYPE[]{(short)5, (short)6, (short)7}; -#else if TYPE_CHAR - return new KEY_TYPE[]{'f', 'g', 'h'}; -#else - return new KEY_TYPE[]{5, 6, 7}; -#endif - } - -#endif - @Override - @SuppressWarnings("rawtypes") - protected List> getTesters() { - List> testers = Helpers.copyToList(super.getTesters()); - - testers.add(CollectionSerializationEqualTester.class); - testers.add(ListAddAllAtIndexTester.class); - testers.add(ListAddAllTester.class); - testers.add(ListAddAtIndexTester.class); - testers.add(ListAddTester.class); - testers.add(ListCreationTester.class); - testers.add(ListEqualsTester.class); - testers.add(ListGetTester.class); - testers.add(ListHashCodeTester.class); - testers.add(ListIndexOfTester.class); - testers.add(ListLastIndexOfTester.class); - testers.add(JavaListListIteratorTester.class); - testers.add(ListRemoveAllTester.class); - testers.add(ListRemoveAtIndexTester.class); - testers.add(ListRemoveTester.class); - testers.add(ListReplaceAllTester.class); - testers.add(ListRetainAllTester.class); - testers.add(ListSetTester.class); - testers.add(ListSubListTester.class); - testers.add(ListToArrayTester.class); - - testers.add(FILE_KEY_TYPEListAddAllAtIndexTester.class); - testers.add(FILE_KEY_TYPEListAddAllListAtIndexTester.class); - testers.add(FILE_KEY_TYPEListAddAllArrayAtIndexTester.class); - testers.add(FILE_KEY_TYPEListAddAllTester.class); - testers.add(FILE_KEY_TYPEListAddAtIndexTester.class); - testers.add(FILE_KEY_TYPEListAddTester.class); - testers.add(FILE_KEY_TYPEListAbsentTester.class); - testers.add(FILE_KEY_TYPEListPresentTester.class); - testers.add(FILE_KEY_TYPEListCreationTester.class); - testers.add(FILE_KEY_TYPEListEqualsTester.class); - testers.add(FILE_KEY_TYPEListGetTester.class); - testers.add(FILE_KEY_TYPEListGetElementsTester.class); - testers.add(FILE_KEY_TYPEListExtractElementsTester.class); - testers.add(FILE_KEY_TYPEListIndexOfTester.class); - testers.add(FILE_KEY_TYPEListLastIndexOfTester.class); - testers.add(FILE_KEY_TYPEListListIteratorTester.class); - testers.add(FILE_KEY_TYPEListRemoveAllTester.class); - testers.add(FILE_KEY_TYPEListRemoveAtIndexTester.class); - testers.add(FILE_KEY_TYPEListRemoveTester.class); - testers.add(FILE_KEY_TYPEListRemoveElementsTester.class); - testers.add(FILE_KEY_TYPEListSwapRemoveAtIndexTester.class); - testers.add(FILE_KEY_TYPEListSwapRemoveTester.class); -#if !TYPE_BOOLEAN - testers.add(FILE_KEY_TYPEListSortTester.class); -#if !TYPE_OBJECT - testers.add(FILE_KEY_TYPEListFillBufferTester.class); -#endif - testers.add(FILE_KEY_TYPEListReplaceAllTester.class); -#endif - testers.add(FILE_KEY_TYPEListRetainAllTester.class); - testers.add(FILE_KEY_TYPEListSetTester.class); - testers.add(FILE_KEY_TYPEListSubListTester.class); - testers.add(FILE_KEY_TYPEListToArrayTester.class); - return testers; - } - - @Override - public TestSuite createTestSuite() { -#ignore - withFeatures(KNOWN_ORDER); -#endignore - return super.createTestSuite(); - } - - @Override - protected List createDerivedSuites(FeatureSpecificTestSuiteBuilder, CLASS_TYPE>> parentBuilder) { - List derivedSuites = new ArrayList<>(super.createDerivedSuites(parentBuilder)); -#ignore - if (parentBuilder.getFeatures().contains(SERIALIZABLE)) { -#endignore - derivedSuites.add(ListTestSuiteBuilder.using(new ReserializedListGenerator(parentBuilder.getSubjectGenerator())) - .named(getName() + " reserialized") - .withFeatures(computeReserializedCollectionFeatures(parentBuilder.getFeatures())) - .suppressing(parentBuilder.getSuppressedTests()).withSetUp(parentBuilder.getSetUp()) - .withTearDown(parentBuilder.getTearDown()).createTestSuite()); - } -#ignore - if(!parentBuilder.getFeatures().contains(CollectionFeature.SUBSET_VIEW)) { -#endignore -#if !TYPE_BOOLEAN - if(prefixes != null) { - derivedSuites.add(LIST_TEST_BUILDER.using(new SubListListGeneratorBRACES(parentBuilder.getSubjectGenerator(), prefixes, null)) - .named(getName() + " subSet_prefix") - .withFeatures(computeSubListFeatures(parentBuilder.getFeatures())) - .suppressing(parentBuilder.getSuppressedTests()).withSetUp(parentBuilder.getSetUp()) - .withTearDown(parentBuilder.getTearDown()).createTestSuite()); - } - if(suffixes != null) { - derivedSuites.add(LIST_TEST_BUILDER.using(new SubListListGeneratorBRACES(parentBuilder.getSubjectGenerator(), null, suffixes)) - .named(getName() + " subSet_suffixes") - .withFeatures(computeSubListFeatures(parentBuilder.getFeatures())) - .suppressing(parentBuilder.getSuppressedTests()).withSetUp(parentBuilder.getSetUp()) - .withTearDown(parentBuilder.getTearDown()).createTestSuite()); - } - if(prefixes != null && suffixes != null) { - derivedSuites.add(LIST_TEST_BUILDER.using(new SubListListGeneratorBRACES(parentBuilder.getSubjectGenerator(), prefixes, suffixes)) - .named(getName() + " subSet") - .withFeatures(computeSubListFeatures(parentBuilder.getFeatures())) - .suppressing(parentBuilder.getSuppressedTests()).withSetUp(parentBuilder.getSetUp()) - .withTearDown(parentBuilder.getTearDown()).createTestSuite()); - } -#endif - } - return derivedSuites; - } - - static class SubListListGenerator KEY_GENERIC_TYPE implements TEST_LIST_GENERATOR KEY_GENERIC_TYPE { - TEST_LIST_GENERATOR KEY_GENERIC_TYPE generator; - KEY_TYPE[] prefix; - KEY_TYPE[] suffix; - - public SubListListGenerator(OneSizeTestContainerGenerator, CLASS_TYPE> gen, KEY_TYPE[] prefix, KEY_TYPE[] suffix) { - generator = (TEST_LIST_GENERATOR KEY_GENERIC_TYPE)gen.getInnerGenerator(); - this.prefix = prefix; - this.suffix = suffix; - } - - @Override - public SampleElements samples() { - return generator.samples(); - } - - @Override - public CLASS_TYPE[] createArray(int length) { - return generator.createArray(length); - } - - @Override - public Iterable order(List insertionOrder) { - return generator.order(insertionOrder); - } - - @Override - public SAMPLE_ELEMENTS KEY_GENERIC_TYPE getSamples() { - return generator.getSamples(); - } - - @Override - public ITERABLE KEY_GENERIC_TYPE order(LIST KEY_GENERIC_TYPE insertionOrder) { - return generator.order(insertionOrder); - } - -#if !TYPE_OBJECT - @Override - public LIST KEY_GENERIC_TYPE create(Object... elements) { - KEY_TYPE[] array = NEW_KEY_ARRAY(elements.length); - int i = 0; - for (Object e : elements) { - array[i++] = CLASS_TO_KEY(e); - } - return create(array); - } - - @Override - public LIST KEY_GENERIC_TYPE create(KEY_TYPE... elements) { - int length = getLength(prefix); - return generator.create(merge(elements)).subList(length, length+elements.length); - } - -#else - @Override - public LIST KEY_GENERIC_TYPE create(Object... elements) { - KEY_TYPE[] array = NEW_KEY_ARRAY(elements.length); - int i = 0; - for (Object e : elements) { - array[i++] = CLASS_TO_KEY(e); - } - int length = getLength(prefix); - return generator.create(merge(array)).subList(length, length+elements.length); - } - -#endif - private int getLength(KEY_TYPE[] keys) { - return keys == null ? 0 : keys.length; - } - - private KEY_TYPE[] merge(KEY_TYPE[] input) { - int prefixLength = getLength(prefix); - int suffixLength = getLength(suffix); - KEY_TYPE[] result = NEW_KEY_ARRAY(input.length+prefixLength+suffixLength); - if(prefixLength != 0) System.arraycopy(prefix, 0, result, 0, prefixLength); - System.arraycopy(input, 0, result, prefixLength, input.length); - if(suffixLength != 0) System.arraycopy(suffix, 0, result, prefixLength+input.length, suffixLength); - return result; - } - } - - static class ReserializedListGenerator implements TestListGenerator { - final OneSizeTestContainerGenerator, E> gen; - - private ReserializedListGenerator(OneSizeTestContainerGenerator, E> gen) { - this.gen = gen; - } - - @Override - public SampleElements samples() { - return gen.samples(); - } - - @Override - public List create(Object... elements) { - return (List) SerializableTester.reserialize(gen.create(elements)); - } - - @Override - public E[] createArray(int length) { - return gen.createArray(length); - } - - @Override - public Iterable order(List insertionOrder) { - return gen.order(insertionOrder); - } - } - -#if !TYPE_BOOLEAN - private static Set> computeSubListFeatures(Set> features) { - Set> derivedFeatures = new HashSet<>(features); -#ignore - derivedFeatures.add(CollectionFeature.SUBSET_VIEW); - derivedFeatures.remove(SpecialFeature.COPYING); - derivedFeatures.remove(SpecialFeature.CHILDREN_COPY); -#endignore - return derivedFeatures; - } - -#endif - private static Set> computeReserializedCollectionFeatures(Set> features) { - Set> derivedFeatures = new HashSet<>(features); -#ignore - derivedFeatures.remove(SERIALIZABLE); - derivedFeatures.remove(SERIALIZABLE_INCLUDING_VIEWS); -#endignore - return derivedFeatures; - } -} +package speiger.src.testers.PACKAGE.builder; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; +import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE; +import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS; +#endignore + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import com.google.common.collect.testing.AbstractTester; +import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder; +import com.google.common.collect.testing.Helpers; +import com.google.common.collect.testing.ListTestSuiteBuilder; +import com.google.common.collect.testing.OneSizeTestContainerGenerator; +import com.google.common.collect.testing.SampleElements; +import com.google.common.collect.testing.TestListGenerator; +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.Feature; +import com.google.common.collect.testing.testers.CollectionSerializationEqualTester; +import com.google.common.collect.testing.testers.ListAddAllAtIndexTester; +import com.google.common.collect.testing.testers.ListAddAllTester; +import com.google.common.collect.testing.testers.ListAddAtIndexTester; +import com.google.common.collect.testing.testers.ListAddTester; +import com.google.common.collect.testing.testers.ListCreationTester; +import com.google.common.collect.testing.testers.ListEqualsTester; +import com.google.common.collect.testing.testers.ListGetTester; +import com.google.common.collect.testing.testers.ListHashCodeTester; +import com.google.common.collect.testing.testers.ListIndexOfTester; +import com.google.common.collect.testing.testers.ListLastIndexOfTester; +import com.google.common.collect.testing.testers.ListRemoveAllTester; +import com.google.common.collect.testing.testers.ListRemoveAtIndexTester; +import com.google.common.collect.testing.testers.ListRemoveTester; +import com.google.common.collect.testing.testers.ListReplaceAllTester; +import com.google.common.collect.testing.testers.ListRetainAllTester; +import com.google.common.collect.testing.testers.ListSetTester; +import com.google.common.collect.testing.testers.ListSubListTester; +import com.google.common.collect.testing.testers.ListToArrayTester; +import com.google.common.testing.SerializableTester; + +import junit.framework.TestSuite; +import speiger.src.collections.PACKAGE.collections.ITERABLE; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.testers.base.tests.list.JavaListListIteratorTester; +import speiger.src.testers.PACKAGE.generators.TEST_LIST_GENERATOR; +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListAbsentTester; +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListAddAllArrayAtIndexTester; +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListAddAllAtIndexTester; +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListAddAllListAtIndexTester; +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListAddAllTester; +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListAddAtIndexTester; +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListAddTester; +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListCreationTester; +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListEqualsTester; +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListExtractElementsTester; +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListGetElementsTester; +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListGetTester; +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListIndexOfTester; +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListLastIndexOfTester; +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListListIteratorTester; +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListPresentTester; +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListRemoveAllTester; +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListRemoveAtIndexTester; +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListRemoveElementsTester; +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListRemoveTester; +#if !TYPE_BOOLEAN +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListSortTester; +#if !TYPE_OBJECT +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListFillBufferTester; +#endif +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListReplaceAllTester; +#endif +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListRetainAllTester; +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListSetTester; +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListSubListTester; +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListSwapRemoveAtIndexTester; +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListSwapRemoveTester; +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListToArrayTester; +import speiger.src.testers.PACKAGE.utils.SAMPLE_ELEMENTS; +#if !TYPE_BOOLEAN +import speiger.src.testers.utils.SpecialFeature; +#endif + +@SuppressWarnings("javadoc") +public class LIST_TEST_BUILDER KEY_GENERIC_TYPE extends COLLECTION_TEST_BUILDER KEY_GENERIC_TYPE { + +#if TYPE_OBJECT + KEY_TYPE[] prefixes; + KEY_TYPE[] suffixes; +#else + KEY_TYPE[] prefixes = createPrefixes(); + KEY_TYPE[] suffixes = createSuffixes(); +#endif + + public static GENERIC_KEY_BRACES LIST_TEST_BUILDER KEY_GENERIC_TYPE using(TEST_LIST_GENERATOR KEY_GENERIC_TYPE generator) { + return (LIST_TEST_BUILDER KEY_GENERIC_TYPE) new LIST_TEST_BUILDER KEY_GENERIC_TYPE().usingGenerator(generator); + } + + public LIST_TEST_BUILDER KEY_GENERIC_TYPE setPrefixes(KEY_TYPE[] prefixes) { + this.prefixes = prefixes; + return this; + } + + public LIST_TEST_BUILDER KEY_GENERIC_TYPE setSuffixes(KEY_TYPE[] suffixes) { + this.suffixes = suffixes; + return this; + } + +#if !TYPE_OBJECT + public KEY_TYPE[] createPrefixes() { +#if TYPE_BOOLEAN + return new KEY_TYPE[]{false, false, false}; +#else if TYPE_BYTE + return new KEY_TYPE[]{(byte)-3, (byte)-2, (byte)-1}; +#else if TYPE_SHORT + return new KEY_TYPE[]{(short)-3, (short)-2, (short)-1}; +#else if TYPE_CHAR + return new KEY_TYPE[]{'^', '_', '`'}; +#else + return new KEY_TYPE[]{-3, -2, -1}; +#endif + } + + public KEY_TYPE[] createSuffixes() { +#if TYPE_BOOLEAN + return new KEY_TYPE[]{true, true, true}; +#else if TYPE_BYTE + return new KEY_TYPE[]{(byte)5, (byte)6, (byte)7}; +#else if TYPE_SHORT + return new KEY_TYPE[]{(short)5, (short)6, (short)7}; +#else if TYPE_CHAR + return new KEY_TYPE[]{'f', 'g', 'h'}; +#else + return new KEY_TYPE[]{5, 6, 7}; +#endif + } + +#endif + @Override + @SuppressWarnings("rawtypes") + protected List> getTesters() { + List> testers = Helpers.copyToList(super.getTesters()); + + testers.add(CollectionSerializationEqualTester.class); + testers.add(ListAddAllAtIndexTester.class); + testers.add(ListAddAllTester.class); + testers.add(ListAddAtIndexTester.class); + testers.add(ListAddTester.class); + testers.add(ListCreationTester.class); + testers.add(ListEqualsTester.class); + testers.add(ListGetTester.class); + testers.add(ListHashCodeTester.class); + testers.add(ListIndexOfTester.class); + testers.add(ListLastIndexOfTester.class); + testers.add(JavaListListIteratorTester.class); + testers.add(ListRemoveAllTester.class); + testers.add(ListRemoveAtIndexTester.class); + testers.add(ListRemoveTester.class); + testers.add(ListReplaceAllTester.class); + testers.add(ListRetainAllTester.class); + testers.add(ListSetTester.class); + testers.add(ListSubListTester.class); + testers.add(ListToArrayTester.class); + + testers.add(FILE_KEY_TYPEListAddAllAtIndexTester.class); + testers.add(FILE_KEY_TYPEListAddAllListAtIndexTester.class); + testers.add(FILE_KEY_TYPEListAddAllArrayAtIndexTester.class); + testers.add(FILE_KEY_TYPEListAddAllTester.class); + testers.add(FILE_KEY_TYPEListAddAtIndexTester.class); + testers.add(FILE_KEY_TYPEListAddTester.class); + testers.add(FILE_KEY_TYPEListAbsentTester.class); + testers.add(FILE_KEY_TYPEListPresentTester.class); + testers.add(FILE_KEY_TYPEListCreationTester.class); + testers.add(FILE_KEY_TYPEListEqualsTester.class); + testers.add(FILE_KEY_TYPEListGetTester.class); + testers.add(FILE_KEY_TYPEListGetElementsTester.class); + testers.add(FILE_KEY_TYPEListExtractElementsTester.class); + testers.add(FILE_KEY_TYPEListIndexOfTester.class); + testers.add(FILE_KEY_TYPEListLastIndexOfTester.class); + testers.add(FILE_KEY_TYPEListListIteratorTester.class); + testers.add(FILE_KEY_TYPEListRemoveAllTester.class); + testers.add(FILE_KEY_TYPEListRemoveAtIndexTester.class); + testers.add(FILE_KEY_TYPEListRemoveTester.class); + testers.add(FILE_KEY_TYPEListRemoveElementsTester.class); + testers.add(FILE_KEY_TYPEListSwapRemoveAtIndexTester.class); + testers.add(FILE_KEY_TYPEListSwapRemoveTester.class); +#if !TYPE_BOOLEAN + testers.add(FILE_KEY_TYPEListSortTester.class); +#if !TYPE_OBJECT + testers.add(FILE_KEY_TYPEListFillBufferTester.class); +#endif + testers.add(FILE_KEY_TYPEListReplaceAllTester.class); +#endif + testers.add(FILE_KEY_TYPEListRetainAllTester.class); + testers.add(FILE_KEY_TYPEListSetTester.class); + testers.add(FILE_KEY_TYPEListSubListTester.class); + testers.add(FILE_KEY_TYPEListToArrayTester.class); + return testers; + } + + @Override + public TestSuite createTestSuite() { +#ignore + withFeatures(KNOWN_ORDER); +#endignore + return super.createTestSuite(); + } + + @Override + protected List createDerivedSuites(FeatureSpecificTestSuiteBuilder, CLASS_TYPE>> parentBuilder) { + List derivedSuites = new ArrayList<>(super.createDerivedSuites(parentBuilder)); +#ignore + if (parentBuilder.getFeatures().contains(SERIALIZABLE)) { +#endignore + derivedSuites.add(ListTestSuiteBuilder.using(new ReserializedListGenerator(parentBuilder.getSubjectGenerator())) + .named(getName() + " reserialized") + .withFeatures(computeReserializedCollectionFeatures(parentBuilder.getFeatures())) + .suppressing(parentBuilder.getSuppressedTests()).withSetUp(parentBuilder.getSetUp()) + .withTearDown(parentBuilder.getTearDown()).createTestSuite()); + } +#ignore + if(!parentBuilder.getFeatures().contains(CollectionFeature.SUBSET_VIEW)) { +#endignore +#if !TYPE_BOOLEAN + if(prefixes != null) { + derivedSuites.add(LIST_TEST_BUILDER.using(new SubListListGeneratorBRACES(parentBuilder.getSubjectGenerator(), prefixes, null)) + .named(getName() + " subSet_prefix") + .withFeatures(computeSubListFeatures(parentBuilder.getFeatures())) + .suppressing(parentBuilder.getSuppressedTests()).withSetUp(parentBuilder.getSetUp()) + .withTearDown(parentBuilder.getTearDown()).createTestSuite()); + } + if(suffixes != null) { + derivedSuites.add(LIST_TEST_BUILDER.using(new SubListListGeneratorBRACES(parentBuilder.getSubjectGenerator(), null, suffixes)) + .named(getName() + " subSet_suffixes") + .withFeatures(computeSubListFeatures(parentBuilder.getFeatures())) + .suppressing(parentBuilder.getSuppressedTests()).withSetUp(parentBuilder.getSetUp()) + .withTearDown(parentBuilder.getTearDown()).createTestSuite()); + } + if(prefixes != null && suffixes != null) { + derivedSuites.add(LIST_TEST_BUILDER.using(new SubListListGeneratorBRACES(parentBuilder.getSubjectGenerator(), prefixes, suffixes)) + .named(getName() + " subSet") + .withFeatures(computeSubListFeatures(parentBuilder.getFeatures())) + .suppressing(parentBuilder.getSuppressedTests()).withSetUp(parentBuilder.getSetUp()) + .withTearDown(parentBuilder.getTearDown()).createTestSuite()); + } +#endif + } + return derivedSuites; + } + + static class SubListListGenerator KEY_GENERIC_TYPE implements TEST_LIST_GENERATOR KEY_GENERIC_TYPE { + TEST_LIST_GENERATOR KEY_GENERIC_TYPE generator; + KEY_TYPE[] prefix; + KEY_TYPE[] suffix; + + public SubListListGenerator(OneSizeTestContainerGenerator, CLASS_TYPE> gen, KEY_TYPE[] prefix, KEY_TYPE[] suffix) { + generator = (TEST_LIST_GENERATOR KEY_GENERIC_TYPE)gen.getInnerGenerator(); + this.prefix = prefix; + this.suffix = suffix; + } + + @Override + public SampleElements samples() { + return generator.samples(); + } + + @Override + public CLASS_TYPE[] createArray(int length) { + return generator.createArray(length); + } + + @Override + public Iterable order(List insertionOrder) { + return generator.order(insertionOrder); + } + + @Override + public SAMPLE_ELEMENTS KEY_GENERIC_TYPE getSamples() { + return generator.getSamples(); + } + + @Override + public ITERABLE KEY_GENERIC_TYPE order(LIST KEY_GENERIC_TYPE insertionOrder) { + return generator.order(insertionOrder); + } + +#if !TYPE_OBJECT + @Override + public LIST KEY_GENERIC_TYPE create(Object... elements) { + KEY_TYPE[] array = NEW_KEY_ARRAY(elements.length); + int i = 0; + for (Object e : elements) { + array[i++] = CLASS_TO_KEY(e); + } + return create(array); + } + + @Override + public LIST KEY_GENERIC_TYPE create(KEY_TYPE... elements) { + int length = getLength(prefix); + return generator.create(merge(elements)).subList(length, length+elements.length); + } + +#else + @Override + public LIST KEY_GENERIC_TYPE create(Object... elements) { + KEY_TYPE[] array = NEW_KEY_ARRAY(elements.length); + int i = 0; + for (Object e : elements) { + array[i++] = CLASS_TO_KEY(e); + } + int length = getLength(prefix); + return generator.create(merge(array)).subList(length, length+elements.length); + } + +#endif + private int getLength(KEY_TYPE[] keys) { + return keys == null ? 0 : keys.length; + } + + private KEY_TYPE[] merge(KEY_TYPE[] input) { + int prefixLength = getLength(prefix); + int suffixLength = getLength(suffix); + KEY_TYPE[] result = NEW_KEY_ARRAY(input.length+prefixLength+suffixLength); + if(prefixLength != 0) System.arraycopy(prefix, 0, result, 0, prefixLength); + System.arraycopy(input, 0, result, prefixLength, input.length); + if(suffixLength != 0) System.arraycopy(suffix, 0, result, prefixLength+input.length, suffixLength); + return result; + } + } + + static class ReserializedListGenerator implements TestListGenerator { + final OneSizeTestContainerGenerator, E> gen; + + private ReserializedListGenerator(OneSizeTestContainerGenerator, E> gen) { + this.gen = gen; + } + + @Override + public SampleElements samples() { + return gen.samples(); + } + + @Override + public List create(Object... elements) { + return (List) SerializableTester.reserialize(gen.create(elements)); + } + + @Override + public E[] createArray(int length) { + return gen.createArray(length); + } + + @Override + public Iterable order(List insertionOrder) { + return gen.order(insertionOrder); + } + } + +#if !TYPE_BOOLEAN + private static Set> computeSubListFeatures(Set> features) { + Set> derivedFeatures = new HashSet<>(features); +#ignore + derivedFeatures.add(CollectionFeature.SUBSET_VIEW); + derivedFeatures.remove(SpecialFeature.COPYING); + derivedFeatures.remove(SpecialFeature.CHILDREN_COPY); +#endignore + return derivedFeatures; + } + +#endif + private static Set> computeReserializedCollectionFeatures(Set> features) { + Set> derivedFeatures = new HashSet<>(features); +#ignore + derivedFeatures.remove(SERIALIZABLE); + derivedFeatures.remove(SERIALIZABLE_INCLUDING_VIEWS); +#endignore + return derivedFeatures; + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/builder/NavigableSetTestSuiteBuilder.template b/src/builder/resources/speiger/assets/testers/templates/builder/NavigableSetTestSuiteBuilder.template index 0c66f40..bd4b426 100644 --- a/src/builder/resources/speiger/assets/testers/templates/builder/NavigableSetTestSuiteBuilder.template +++ b/src/builder/resources/speiger/assets/testers/templates/builder/NavigableSetTestSuiteBuilder.template @@ -1,140 +1,140 @@ -package speiger.src.testers.PACKAGE.builder; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.DESCENDING_VIEW; -import static com.google.common.collect.testing.features.CollectionFeature.SUBSET_VIEW; -#endignore - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import com.google.common.collect.testing.AbstractTester; -import com.google.common.collect.testing.DerivedCollectionGenerators.Bound; -import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder; -import com.google.common.collect.testing.Helpers; -import com.google.common.collect.testing.OneSizeTestContainerGenerator; -import com.google.common.collect.testing.SampleElements; -import com.google.common.collect.testing.features.Feature; -import com.google.common.collect.testing.testers.NavigableSetNavigationTester; - -import junit.framework.TestSuite; -import speiger.src.collections.PACKAGE.collections.ITERABLE; -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET; -import speiger.src.collections.PACKAGE.utils.LISTS; -import speiger.src.testers.PACKAGE.generators.TEST_NAVIGABLE_SET_GENERATOR; -import speiger.src.testers.PACKAGE.generators.TEST_SORTED_SET_GENERATOR; -import speiger.src.testers.PACKAGE.impl.SUB_SORTED_SET_CLASS_GENERATOR.SUB_NAVIGABLE_SET_CLASS_GENERATOR; -import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPENavigableSetNavigationTester; -import speiger.src.testers.PACKAGE.utils.SAMPLE_ELEMENTS; -import speiger.src.testers.utils.SpecialFeature; - -@SuppressWarnings("javadoc") -public class NAVIGABLE_SET_TEST_BUILDER KEY_GENERIC_TYPE extends SORTED_SET_TEST_BUILDER KEY_GENERIC_TYPE { - public static GENERIC_KEY_BRACES NAVIGABLE_SET_TEST_BUILDER KEY_GENERIC_TYPE using(TEST_NAVIGABLE_SET_GENERATOR KEY_GENERIC_TYPE generator) { - return (NAVIGABLE_SET_TEST_BUILDER KEY_GENERIC_TYPE) new NAVIGABLE_SET_TEST_BUILDER KEY_GENERIC_TYPE().usingGenerator(generator); - } - - @Override - @SuppressWarnings("rawtypes") - protected List> getTesters() { - List> testers = Helpers.copyToList(super.getTesters()); - testers.add(NavigableSetNavigationTester.class); - testers.add(FILE_KEY_TYPENavigableSetNavigationTester.class); - return testers; - } - - @Override - protected List createDerivedSuites(FeatureSpecificTestSuiteBuilder, CLASS_TYPE>> parentBuilder) { - List derivedSuites = new ArrayList<>(super.createDerivedSuites(parentBuilder)); - -#ignore - if (!parentBuilder.getFeatures().contains(SUBSET_VIEW)) { -#endignore - // Other combinations are inherited from SortedSetTestSuiteBuilder. - derivedSuites.add(createSubsetSuite(parentBuilder, Bound.NO_BOUND, Bound.INCLUSIVE)); - derivedSuites.add(createSubsetSuite(parentBuilder, Bound.EXCLUSIVE, Bound.NO_BOUND)); - derivedSuites.add(createSubsetSuite(parentBuilder, Bound.EXCLUSIVE, Bound.EXCLUSIVE)); - derivedSuites.add(createSubsetSuite(parentBuilder, Bound.EXCLUSIVE, Bound.INCLUSIVE)); - derivedSuites.add(createSubsetSuite(parentBuilder, Bound.INCLUSIVE, Bound.INCLUSIVE)); - } -#ignore - if (!parentBuilder.getFeatures().contains(DESCENDING_VIEW)) { -#endignore - derivedSuites.add(createDescendingSuite(parentBuilder)); - } - return derivedSuites; - } - - @Override - SORTED_SET_TEST_BUILDER KEY_GENERIC_TYPE newBuilderUsing(TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE delegate, Bound to, Bound from) { - return NAVIGABLE_SET_TEST_BUILDER.using(new SUB_NAVIGABLE_SET_CLASS_GENERATORBRACES(delegate, to, from)); - } - - private TestSuite createDescendingSuite(FeatureSpecificTestSuiteBuilder, CLASS_TYPE>> parentBuilder) { - TEST_NAVIGABLE_SET_GENERATOR KEY_GENERIC_TYPE delegate = (TEST_NAVIGABLE_SET_GENERATOR KEY_GENERIC_TYPE) parentBuilder.getSubjectGenerator().getInnerGenerator(); - - List> features = new ArrayList<>(); -#ignore - features.add(DESCENDING_VIEW); - features.addAll(parentBuilder.getFeatures()); - features.remove(SpecialFeature.COPYING); - features.remove(SpecialFeature.CHILDREN_COPY); -#endignore - - return NAVIGABLE_SET_TEST_BUILDER.using(new TEST_NAVIGABLE_SET_GENERATOR KEY_GENERIC_TYPE() { - - @Override - public SampleElements samples() { - return delegate.samples(); - } - - @Override - public SAMPLE_ELEMENTS KEY_GENERIC_TYPE getSamples() { - return delegate.getSamples(); - } - - @Override - public ITERABLE KEY_GENERIC_TYPE order(LIST KEY_GENERIC_TYPE insertionOrder) { - LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); - delegate.order(insertionOrder).forEach(list::add); - LISTS.reverse(list); - return list; - } - - @Override - public Iterable order(List insertionOrder) { - LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); - for(CLASS_TYPE entry : delegate.order(insertionOrder)) - { - list.add(OBJ_TO_KEY(entry)); - } - LISTS.reverse(list); - return list; - } - @Override - public KEY_TYPE belowSamplesLesser() { return delegate.aboveSamplesGreater(); } - @Override - public KEY_TYPE belowSamplesGreater() { return delegate.aboveSamplesLesser(); } - @Override - public KEY_TYPE aboveSamplesLesser() { return delegate.belowSamplesGreater(); } - @Override - public KEY_TYPE aboveSamplesGreater() { return delegate.belowSamplesLesser(); } - -#if !TYPE_OBJECT - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE create(KEY_TYPE... elements) { - return delegate.create(elements).descendingSet(); - } - -#endif - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE create(Object... elements) { - return delegate.create(elements).descendingSet(); - } - }).named(parentBuilder.getName() + " descending").withFeatures(features) - .suppressing(parentBuilder.getSuppressedTests()).createTestSuite(); - } -} +package speiger.src.testers.PACKAGE.builder; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.DESCENDING_VIEW; +import static com.google.common.collect.testing.features.CollectionFeature.SUBSET_VIEW; +#endignore + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import com.google.common.collect.testing.AbstractTester; +import com.google.common.collect.testing.DerivedCollectionGenerators.Bound; +import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder; +import com.google.common.collect.testing.Helpers; +import com.google.common.collect.testing.OneSizeTestContainerGenerator; +import com.google.common.collect.testing.SampleElements; +import com.google.common.collect.testing.features.Feature; +import com.google.common.collect.testing.testers.NavigableSetNavigationTester; + +import junit.framework.TestSuite; +import speiger.src.collections.PACKAGE.collections.ITERABLE; +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET; +import speiger.src.collections.PACKAGE.utils.LISTS; +import speiger.src.testers.PACKAGE.generators.TEST_NAVIGABLE_SET_GENERATOR; +import speiger.src.testers.PACKAGE.generators.TEST_SORTED_SET_GENERATOR; +import speiger.src.testers.PACKAGE.impl.SUB_SORTED_SET_CLASS_GENERATOR.SUB_NAVIGABLE_SET_CLASS_GENERATOR; +import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPENavigableSetNavigationTester; +import speiger.src.testers.PACKAGE.utils.SAMPLE_ELEMENTS; +import speiger.src.testers.utils.SpecialFeature; + +@SuppressWarnings("javadoc") +public class NAVIGABLE_SET_TEST_BUILDER KEY_GENERIC_TYPE extends SORTED_SET_TEST_BUILDER KEY_GENERIC_TYPE { + public static GENERIC_KEY_BRACES NAVIGABLE_SET_TEST_BUILDER KEY_GENERIC_TYPE using(TEST_NAVIGABLE_SET_GENERATOR KEY_GENERIC_TYPE generator) { + return (NAVIGABLE_SET_TEST_BUILDER KEY_GENERIC_TYPE) new NAVIGABLE_SET_TEST_BUILDER KEY_GENERIC_TYPE().usingGenerator(generator); + } + + @Override + @SuppressWarnings("rawtypes") + protected List> getTesters() { + List> testers = Helpers.copyToList(super.getTesters()); + testers.add(NavigableSetNavigationTester.class); + testers.add(FILE_KEY_TYPENavigableSetNavigationTester.class); + return testers; + } + + @Override + protected List createDerivedSuites(FeatureSpecificTestSuiteBuilder, CLASS_TYPE>> parentBuilder) { + List derivedSuites = new ArrayList<>(super.createDerivedSuites(parentBuilder)); + +#ignore + if (!parentBuilder.getFeatures().contains(SUBSET_VIEW)) { +#endignore + // Other combinations are inherited from SortedSetTestSuiteBuilder. + derivedSuites.add(createSubsetSuite(parentBuilder, Bound.NO_BOUND, Bound.INCLUSIVE)); + derivedSuites.add(createSubsetSuite(parentBuilder, Bound.EXCLUSIVE, Bound.NO_BOUND)); + derivedSuites.add(createSubsetSuite(parentBuilder, Bound.EXCLUSIVE, Bound.EXCLUSIVE)); + derivedSuites.add(createSubsetSuite(parentBuilder, Bound.EXCLUSIVE, Bound.INCLUSIVE)); + derivedSuites.add(createSubsetSuite(parentBuilder, Bound.INCLUSIVE, Bound.INCLUSIVE)); + } +#ignore + if (!parentBuilder.getFeatures().contains(DESCENDING_VIEW)) { +#endignore + derivedSuites.add(createDescendingSuite(parentBuilder)); + } + return derivedSuites; + } + + @Override + SORTED_SET_TEST_BUILDER KEY_GENERIC_TYPE newBuilderUsing(TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE delegate, Bound to, Bound from) { + return NAVIGABLE_SET_TEST_BUILDER.using(new SUB_NAVIGABLE_SET_CLASS_GENERATORBRACES(delegate, to, from)); + } + + private TestSuite createDescendingSuite(FeatureSpecificTestSuiteBuilder, CLASS_TYPE>> parentBuilder) { + TEST_NAVIGABLE_SET_GENERATOR KEY_GENERIC_TYPE delegate = (TEST_NAVIGABLE_SET_GENERATOR KEY_GENERIC_TYPE) parentBuilder.getSubjectGenerator().getInnerGenerator(); + + List> features = new ArrayList<>(); +#ignore + features.add(DESCENDING_VIEW); + features.addAll(parentBuilder.getFeatures()); + features.remove(SpecialFeature.COPYING); + features.remove(SpecialFeature.CHILDREN_COPY); +#endignore + + return NAVIGABLE_SET_TEST_BUILDER.using(new TEST_NAVIGABLE_SET_GENERATOR KEY_GENERIC_TYPE() { + + @Override + public SampleElements samples() { + return delegate.samples(); + } + + @Override + public SAMPLE_ELEMENTS KEY_GENERIC_TYPE getSamples() { + return delegate.getSamples(); + } + + @Override + public ITERABLE KEY_GENERIC_TYPE order(LIST KEY_GENERIC_TYPE insertionOrder) { + LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); + delegate.order(insertionOrder).forEach(list::add); + LISTS.reverse(list); + return list; + } + + @Override + public Iterable order(List insertionOrder) { + LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); + for(CLASS_TYPE entry : delegate.order(insertionOrder)) + { + list.add(OBJ_TO_KEY(entry)); + } + LISTS.reverse(list); + return list; + } + @Override + public KEY_TYPE belowSamplesLesser() { return delegate.aboveSamplesGreater(); } + @Override + public KEY_TYPE belowSamplesGreater() { return delegate.aboveSamplesLesser(); } + @Override + public KEY_TYPE aboveSamplesLesser() { return delegate.belowSamplesGreater(); } + @Override + public KEY_TYPE aboveSamplesGreater() { return delegate.belowSamplesLesser(); } + +#if !TYPE_OBJECT + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE create(KEY_TYPE... elements) { + return delegate.create(elements).descendingSet(); + } + +#endif + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE create(Object... elements) { + return delegate.create(elements).descendingSet(); + } + }).named(parentBuilder.getName() + " descending").withFeatures(features) + .suppressing(parentBuilder.getSuppressedTests()).createTestSuite(); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/builder/OrderedSetTestSuiteBuilder.template b/src/builder/resources/speiger/assets/testers/templates/builder/OrderedSetTestSuiteBuilder.template index 2c4818e..247eba5 100644 --- a/src/builder/resources/speiger/assets/testers/templates/builder/OrderedSetTestSuiteBuilder.template +++ b/src/builder/resources/speiger/assets/testers/templates/builder/OrderedSetTestSuiteBuilder.template @@ -1,38 +1,38 @@ -package speiger.src.testers.PACKAGE.builder; - -import java.util.List; - -import com.google.common.collect.testing.AbstractTester; -import com.google.common.collect.testing.Helpers; -import com.google.common.collect.testing.features.CollectionFeature; - -import junit.framework.TestSuite; -import speiger.src.testers.PACKAGE.generators.TEST_ORDERED_SET_GENERATOR; -import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPEOrderedSetMoveTester; -import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPEOrderedSetIterationTester; -import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPEOrderedSetNavigationTester; - -@SuppressWarnings("javadoc") -public class ORDERED_SET_TEST_BUILDER KEY_GENERIC_TYPE extends SET_TEST_BUILDER KEY_GENERIC_TYPE { - public static GENERIC_KEY_BRACES ORDERED_SET_TEST_BUILDER KEY_GENERIC_TYPE using(TEST_ORDERED_SET_GENERATOR KEY_GENERIC_TYPE generator) { - return (ORDERED_SET_TEST_BUILDER KEY_GENERIC_TYPE) new ORDERED_SET_TEST_BUILDER KEY_GENERIC_TYPE().usingGenerator(generator); - } - - @Override - @SuppressWarnings("rawtypes") - protected List> getTesters() { - List> testers = Helpers.copyToList(super.getTesters()); - testers.add(FILE_KEY_TYPEOrderedSetNavigationTester.class); - testers.add(FILE_KEY_TYPEOrderedSetMoveTester.class); - testers.add(FILE_KEY_TYPEOrderedSetIterationTester.class); - return testers; - } - - @Override - public TestSuite createTestSuite() { -#ignore - withFeatures(CollectionFeature.KNOWN_ORDER); -#endignore - return super.createTestSuite(); - } -} +package speiger.src.testers.PACKAGE.builder; + +import java.util.List; + +import com.google.common.collect.testing.AbstractTester; +import com.google.common.collect.testing.Helpers; +import com.google.common.collect.testing.features.CollectionFeature; + +import junit.framework.TestSuite; +import speiger.src.testers.PACKAGE.generators.TEST_ORDERED_SET_GENERATOR; +import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPEOrderedSetMoveTester; +import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPEOrderedSetIterationTester; +import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPEOrderedSetNavigationTester; + +@SuppressWarnings("javadoc") +public class ORDERED_SET_TEST_BUILDER KEY_GENERIC_TYPE extends SET_TEST_BUILDER KEY_GENERIC_TYPE { + public static GENERIC_KEY_BRACES ORDERED_SET_TEST_BUILDER KEY_GENERIC_TYPE using(TEST_ORDERED_SET_GENERATOR KEY_GENERIC_TYPE generator) { + return (ORDERED_SET_TEST_BUILDER KEY_GENERIC_TYPE) new ORDERED_SET_TEST_BUILDER KEY_GENERIC_TYPE().usingGenerator(generator); + } + + @Override + @SuppressWarnings("rawtypes") + protected List> getTesters() { + List> testers = Helpers.copyToList(super.getTesters()); + testers.add(FILE_KEY_TYPEOrderedSetNavigationTester.class); + testers.add(FILE_KEY_TYPEOrderedSetMoveTester.class); + testers.add(FILE_KEY_TYPEOrderedSetIterationTester.class); + return testers; + } + + @Override + public TestSuite createTestSuite() { +#ignore + withFeatures(CollectionFeature.KNOWN_ORDER); +#endignore + return super.createTestSuite(); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/builder/QueueTestSuiteBuilder.template b/src/builder/resources/speiger/assets/testers/templates/builder/QueueTestSuiteBuilder.template index a7e7228..3acbe83 100644 --- a/src/builder/resources/speiger/assets/testers/templates/builder/QueueTestSuiteBuilder.template +++ b/src/builder/resources/speiger/assets/testers/templates/builder/QueueTestSuiteBuilder.template @@ -1,60 +1,60 @@ -package speiger.src.testers.PACKAGE.builder; - -import java.util.ArrayList; -import java.util.List; - -import com.google.common.collect.testing.AbstractTester; -import com.google.common.collect.testing.PerCollectionSizeTestSuiteBuilder; - -import speiger.src.collections.PACKAGE.queues.PRIORITY_QUEUE; -import speiger.src.testers.PACKAGE.generators.TEST_QUEUE_GENERATOR; -import speiger.src.testers.PACKAGE.tests.queue.FILE_KEY_TYPEQueueDequeueTester; -import speiger.src.testers.PACKAGE.tests.queue.FILE_KEY_TYPEQueueEnqueueTester; -import speiger.src.testers.PACKAGE.tests.queue.FILE_KEY_TYPEQueueFirstTester; -import speiger.src.testers.PACKAGE.tests.queue.FILE_KEY_TYPEQueueRemoveTester; -import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueCountTester; -import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueDistinctTester; -import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueFilterTester; -import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueFindFirstTester; -import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueLimitTester; -import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueMapTester; -import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueMatchesTester; -import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueuePeekTester; -import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueForEachTester; -import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueReduceTester; -import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueSortedTester; - -@SuppressWarnings("javadoc") -public class QUEUE_TEST_BUILDER KEY_GENERIC_TYPE extends PerCollectionSizeTestSuiteBuilder -{ - public static GENERIC_KEY_BRACES QUEUE_TEST_BUILDER KEY_GENERIC_TYPE using(TEST_QUEUE_GENERATOR KEY_GENERIC_TYPE builder) { - return new QUEUE_TEST_BUILDER KEY_GENERIC_TYPE().usingGenerator(builder); - } - - @Override - @SuppressWarnings("rawtypes") - protected List> getTesters() - { - List> testers = new ArrayList<>(); - testers.add(FILE_KEY_TYPEQueueEnqueueTester.class); - testers.add(FILE_KEY_TYPEQueueDequeueTester.class); - testers.add(FILE_KEY_TYPEQueueFirstTester.class); - testers.add(FILE_KEY_TYPEQueueRemoveTester.class); - testers.add(FILE_KEY_TYPEQueueCountTester.class); - testers.add(FILE_KEY_TYPEQueueCountTester.class); - testers.add(FILE_KEY_TYPEQueueDequeueTester.class); - testers.add(FILE_KEY_TYPEQueueDistinctTester.class); - testers.add(FILE_KEY_TYPEQueueFilterTester.class); - testers.add(FILE_KEY_TYPEQueueFindFirstTester.class); - testers.add(FILE_KEY_TYPEQueueFirstTester.class); - testers.add(FILE_KEY_TYPEQueueLimitTester.class); - testers.add(FILE_KEY_TYPEQueueMapTester.class); - testers.add(FILE_KEY_TYPEQueueMatchesTester.class); - testers.add(FILE_KEY_TYPEQueuePeekTester.class); - testers.add(FILE_KEY_TYPEQueueForEachTester.class); - testers.add(FILE_KEY_TYPEQueueReduceTester.class); - testers.add(FILE_KEY_TYPEQueueSortedTester.class); - return testers; - } - -} +package speiger.src.testers.PACKAGE.builder; + +import java.util.ArrayList; +import java.util.List; + +import com.google.common.collect.testing.AbstractTester; +import com.google.common.collect.testing.PerCollectionSizeTestSuiteBuilder; + +import speiger.src.collections.PACKAGE.queues.PRIORITY_QUEUE; +import speiger.src.testers.PACKAGE.generators.TEST_QUEUE_GENERATOR; +import speiger.src.testers.PACKAGE.tests.queue.FILE_KEY_TYPEQueueDequeueTester; +import speiger.src.testers.PACKAGE.tests.queue.FILE_KEY_TYPEQueueEnqueueTester; +import speiger.src.testers.PACKAGE.tests.queue.FILE_KEY_TYPEQueueFirstTester; +import speiger.src.testers.PACKAGE.tests.queue.FILE_KEY_TYPEQueueRemoveTester; +import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueCountTester; +import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueDistinctTester; +import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueFilterTester; +import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueFindFirstTester; +import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueLimitTester; +import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueMapTester; +import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueMatchesTester; +import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueuePeekTester; +import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueForEachTester; +import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueReduceTester; +import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueSortedTester; + +@SuppressWarnings("javadoc") +public class QUEUE_TEST_BUILDER KEY_GENERIC_TYPE extends PerCollectionSizeTestSuiteBuilder +{ + public static GENERIC_KEY_BRACES QUEUE_TEST_BUILDER KEY_GENERIC_TYPE using(TEST_QUEUE_GENERATOR KEY_GENERIC_TYPE builder) { + return new QUEUE_TEST_BUILDER KEY_GENERIC_TYPE().usingGenerator(builder); + } + + @Override + @SuppressWarnings("rawtypes") + protected List> getTesters() + { + List> testers = new ArrayList<>(); + testers.add(FILE_KEY_TYPEQueueEnqueueTester.class); + testers.add(FILE_KEY_TYPEQueueDequeueTester.class); + testers.add(FILE_KEY_TYPEQueueFirstTester.class); + testers.add(FILE_KEY_TYPEQueueRemoveTester.class); + testers.add(FILE_KEY_TYPEQueueCountTester.class); + testers.add(FILE_KEY_TYPEQueueCountTester.class); + testers.add(FILE_KEY_TYPEQueueDequeueTester.class); + testers.add(FILE_KEY_TYPEQueueDistinctTester.class); + testers.add(FILE_KEY_TYPEQueueFilterTester.class); + testers.add(FILE_KEY_TYPEQueueFindFirstTester.class); + testers.add(FILE_KEY_TYPEQueueFirstTester.class); + testers.add(FILE_KEY_TYPEQueueLimitTester.class); + testers.add(FILE_KEY_TYPEQueueMapTester.class); + testers.add(FILE_KEY_TYPEQueueMatchesTester.class); + testers.add(FILE_KEY_TYPEQueuePeekTester.class); + testers.add(FILE_KEY_TYPEQueueForEachTester.class); + testers.add(FILE_KEY_TYPEQueueReduceTester.class); + testers.add(FILE_KEY_TYPEQueueSortedTester.class); + return testers; + } + +} diff --git a/src/builder/resources/speiger/assets/testers/templates/builder/SetTestSuiteBuilder.template b/src/builder/resources/speiger/assets/testers/templates/builder/SetTestSuiteBuilder.template index afe82bf..1548da0 100644 --- a/src/builder/resources/speiger/assets/testers/templates/builder/SetTestSuiteBuilder.template +++ b/src/builder/resources/speiger/assets/testers/templates/builder/SetTestSuiteBuilder.template @@ -1,116 +1,116 @@ -package speiger.src.testers.PACKAGE.builder; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE; -import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS; -#endignore - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import com.google.common.collect.testing.AbstractTester; -import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder; -import com.google.common.collect.testing.Helpers; -import com.google.common.collect.testing.OneSizeTestContainerGenerator; -import com.google.common.collect.testing.SampleElements; -import com.google.common.collect.testing.SetTestSuiteBuilder; -import com.google.common.collect.testing.TestSetGenerator; -import com.google.common.collect.testing.features.Feature; -import com.google.common.collect.testing.testers.CollectionSerializationEqualTester; -import com.google.common.collect.testing.testers.SetAddAllTester; -import com.google.common.collect.testing.testers.SetAddTester; -import com.google.common.collect.testing.testers.SetCreationTester; -import com.google.common.collect.testing.testers.SetEqualsTester; -import com.google.common.collect.testing.testers.SetHashCodeTester; -import com.google.common.collect.testing.testers.SetRemoveTester; -import com.google.common.testing.SerializableTester; - -import junit.framework.TestSuite; -import speiger.src.testers.PACKAGE.generators.TEST_SET_GENERATOR; -import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPESetAddAllTester; -import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPESetAddTester; -import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPESetCreationTester; -import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPESetEqualsTester; -import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPESetRemoveTester; - -@SuppressWarnings("javadoc") -public class SET_TEST_BUILDER KEY_GENERIC_TYPE extends COLLECTION_TEST_BUILDER KEY_GENERIC_TYPE { - public static GENERIC_KEY_BRACES SET_TEST_BUILDER KEY_GENERIC_TYPE using(TEST_SET_GENERATOR KEY_GENERIC_TYPE generator) { - return (SET_TEST_BUILDER KEY_GENERIC_TYPE) new SET_TEST_BUILDER KEY_GENERIC_TYPE().usingGenerator(generator); - } - - @Override - @SuppressWarnings("rawtypes") - protected List> getTesters() { - List> testers = Helpers.copyToList(super.getTesters()); - testers.add(CollectionSerializationEqualTester.class); - testers.add(SetAddAllTester.class); - testers.add(SetAddTester.class); - testers.add(SetCreationTester.class); - testers.add(SetHashCodeTester.class); - testers.add(SetEqualsTester.class); - testers.add(SetRemoveTester.class); - - testers.add(FILE_KEY_TYPESetAddAllTester.class); - testers.add(FILE_KEY_TYPESetAddTester.class); - testers.add(FILE_KEY_TYPESetCreationTester.class); - testers.add(FILE_KEY_TYPESetEqualsTester.class); - testers.add(FILE_KEY_TYPESetRemoveTester.class); - return testers; - } - - @Override - protected List createDerivedSuites( - FeatureSpecificTestSuiteBuilder, CLASS_TYPE>> parentBuilder) { - List derivedSuites = new ArrayList<>(super.createDerivedSuites(parentBuilder)); - - if (parentBuilder.getFeatures().contains(SERIALIZABLE)) { - derivedSuites.add(SetTestSuiteBuilder.using(new ReserializedSetGenerator(parentBuilder.getSubjectGenerator())) - .named(getName() + " reserialized") - .withFeatures(computeReserializedCollectionFeatures(parentBuilder.getFeatures())) - .suppressing(parentBuilder.getSuppressedTests()).withSetUp(parentBuilder.getSetUp()) - .withTearDown(parentBuilder.getTearDown()).createTestSuite()); - } - return derivedSuites; - } - - static class ReserializedSetGenerator implements TestSetGenerator { - final OneSizeTestContainerGenerator, E> gen; - - private ReserializedSetGenerator(OneSizeTestContainerGenerator, E> gen) { - this.gen = gen; - } - - @Override - public SampleElements samples() { - return gen.samples(); - } - - @Override - public Set create(Object... elements) { - return (Set) SerializableTester.reserialize(gen.create(elements)); - } - - @Override - public E[] createArray(int length) { - return gen.createArray(length); - } - - @Override - public Iterable order(List insertionOrder) { - return gen.order(insertionOrder); - } - } - - private static Set> computeReserializedCollectionFeatures(Set> features) { - Set> derivedFeatures = new HashSet<>(features); -#ignore - derivedFeatures.remove(SERIALIZABLE); - derivedFeatures.remove(SERIALIZABLE_INCLUDING_VIEWS); -#endignore - return derivedFeatures; - } -} +package speiger.src.testers.PACKAGE.builder; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE; +import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS; +#endignore + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import com.google.common.collect.testing.AbstractTester; +import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder; +import com.google.common.collect.testing.Helpers; +import com.google.common.collect.testing.OneSizeTestContainerGenerator; +import com.google.common.collect.testing.SampleElements; +import com.google.common.collect.testing.SetTestSuiteBuilder; +import com.google.common.collect.testing.TestSetGenerator; +import com.google.common.collect.testing.features.Feature; +import com.google.common.collect.testing.testers.CollectionSerializationEqualTester; +import com.google.common.collect.testing.testers.SetAddAllTester; +import com.google.common.collect.testing.testers.SetAddTester; +import com.google.common.collect.testing.testers.SetCreationTester; +import com.google.common.collect.testing.testers.SetEqualsTester; +import com.google.common.collect.testing.testers.SetHashCodeTester; +import com.google.common.collect.testing.testers.SetRemoveTester; +import com.google.common.testing.SerializableTester; + +import junit.framework.TestSuite; +import speiger.src.testers.PACKAGE.generators.TEST_SET_GENERATOR; +import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPESetAddAllTester; +import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPESetAddTester; +import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPESetCreationTester; +import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPESetEqualsTester; +import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPESetRemoveTester; + +@SuppressWarnings("javadoc") +public class SET_TEST_BUILDER KEY_GENERIC_TYPE extends COLLECTION_TEST_BUILDER KEY_GENERIC_TYPE { + public static GENERIC_KEY_BRACES SET_TEST_BUILDER KEY_GENERIC_TYPE using(TEST_SET_GENERATOR KEY_GENERIC_TYPE generator) { + return (SET_TEST_BUILDER KEY_GENERIC_TYPE) new SET_TEST_BUILDER KEY_GENERIC_TYPE().usingGenerator(generator); + } + + @Override + @SuppressWarnings("rawtypes") + protected List> getTesters() { + List> testers = Helpers.copyToList(super.getTesters()); + testers.add(CollectionSerializationEqualTester.class); + testers.add(SetAddAllTester.class); + testers.add(SetAddTester.class); + testers.add(SetCreationTester.class); + testers.add(SetHashCodeTester.class); + testers.add(SetEqualsTester.class); + testers.add(SetRemoveTester.class); + + testers.add(FILE_KEY_TYPESetAddAllTester.class); + testers.add(FILE_KEY_TYPESetAddTester.class); + testers.add(FILE_KEY_TYPESetCreationTester.class); + testers.add(FILE_KEY_TYPESetEqualsTester.class); + testers.add(FILE_KEY_TYPESetRemoveTester.class); + return testers; + } + + @Override + protected List createDerivedSuites( + FeatureSpecificTestSuiteBuilder, CLASS_TYPE>> parentBuilder) { + List derivedSuites = new ArrayList<>(super.createDerivedSuites(parentBuilder)); + + if (parentBuilder.getFeatures().contains(SERIALIZABLE)) { + derivedSuites.add(SetTestSuiteBuilder.using(new ReserializedSetGenerator(parentBuilder.getSubjectGenerator())) + .named(getName() + " reserialized") + .withFeatures(computeReserializedCollectionFeatures(parentBuilder.getFeatures())) + .suppressing(parentBuilder.getSuppressedTests()).withSetUp(parentBuilder.getSetUp()) + .withTearDown(parentBuilder.getTearDown()).createTestSuite()); + } + return derivedSuites; + } + + static class ReserializedSetGenerator implements TestSetGenerator { + final OneSizeTestContainerGenerator, E> gen; + + private ReserializedSetGenerator(OneSizeTestContainerGenerator, E> gen) { + this.gen = gen; + } + + @Override + public SampleElements samples() { + return gen.samples(); + } + + @Override + public Set create(Object... elements) { + return (Set) SerializableTester.reserialize(gen.create(elements)); + } + + @Override + public E[] createArray(int length) { + return gen.createArray(length); + } + + @Override + public Iterable order(List insertionOrder) { + return gen.order(insertionOrder); + } + } + + private static Set> computeReserializedCollectionFeatures(Set> features) { + Set> derivedFeatures = new HashSet<>(features); +#ignore + derivedFeatures.remove(SERIALIZABLE); + derivedFeatures.remove(SERIALIZABLE_INCLUDING_VIEWS); +#endignore + return derivedFeatures; + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/builder/SortedSetTestSuiteBuilder.template b/src/builder/resources/speiger/assets/testers/templates/builder/SortedSetTestSuiteBuilder.template index c13e409..7f1b0ef 100644 --- a/src/builder/resources/speiger/assets/testers/templates/builder/SortedSetTestSuiteBuilder.template +++ b/src/builder/resources/speiger/assets/testers/templates/builder/SortedSetTestSuiteBuilder.template @@ -1,88 +1,88 @@ -package speiger.src.testers.PACKAGE.builder; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import com.google.common.collect.testing.AbstractTester; -import com.google.common.collect.testing.DerivedCollectionGenerators.Bound; -import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder; -import com.google.common.collect.testing.Helpers; -import com.google.common.collect.testing.OneSizeTestContainerGenerator; -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.Feature; -import com.google.common.collect.testing.testers.SortedSetNavigationTester; - -import junit.framework.TestSuite; -import speiger.src.testers.PACKAGE.generators.TEST_SORTED_SET_GENERATOR; -import speiger.src.testers.PACKAGE.impl.SUB_SORTED_SET_CLASS_GENERATOR; -import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPESortedSetIterationTester; -import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPESortedSetNaviationTester; -import speiger.src.testers.utils.SpecialFeature; - -@SuppressWarnings("javadoc") -public class SORTED_SET_TEST_BUILDER KEY_GENERIC_TYPE extends SET_TEST_BUILDER KEY_GENERIC_TYPE { - public static GENERIC_KEY_BRACES SORTED_SET_TEST_BUILDER KEY_GENERIC_TYPE using(TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE generator) { - return (SORTED_SET_TEST_BUILDER KEY_GENERIC_TYPE) new SORTED_SET_TEST_BUILDER KEY_GENERIC_TYPE().usingGenerator(generator); - } - - @Override - @SuppressWarnings("rawtypes") - protected List> getTesters() { - List> testers = Helpers.copyToList(super.getTesters()); - testers.add(SortedSetNavigationTester.class); - testers.add(FILE_KEY_TYPESortedSetIterationTester.class); - testers.add(FILE_KEY_TYPESortedSetNaviationTester.class); - return testers; - } - - @Override - public TestSuite createTestSuite() { - if (!getFeatures().contains(CollectionFeature.KNOWN_ORDER)) { - List> features = Helpers.copyToList(getFeatures()); -#ignore - features.add(CollectionFeature.KNOWN_ORDER); -#endignore - withFeatures(features); - } - return super.createTestSuite(); - } - - @Override - protected List createDerivedSuites( - FeatureSpecificTestSuiteBuilder, CLASS_TYPE>> parentBuilder) { - List derivedSuites = super.createDerivedSuites(parentBuilder); - -#ignore - if (!parentBuilder.getFeatures().contains(CollectionFeature.SUBSET_VIEW)) { -#endignore - derivedSuites.add(createSubsetSuite(parentBuilder, Bound.NO_BOUND, Bound.EXCLUSIVE)); - derivedSuites.add(createSubsetSuite(parentBuilder, Bound.INCLUSIVE, Bound.NO_BOUND)); - derivedSuites.add(createSubsetSuite(parentBuilder, Bound.INCLUSIVE, Bound.EXCLUSIVE)); - } - - return derivedSuites; - } - - final TestSuite createSubsetSuite( - FeatureSpecificTestSuiteBuilder, CLASS_TYPE>> parentBuilder, - Bound from, Bound to) { - TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE delegate = (TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE) parentBuilder.getSubjectGenerator().getInnerGenerator(); - - List> features = new ArrayList<>(parentBuilder.getFeatures()); -#ignore - features.remove(CollectionFeature.ALLOWS_NULL_VALUES); - features.add(CollectionFeature.SUBSET_VIEW); - features.remove(SpecialFeature.COPYING); - features.remove(SpecialFeature.CHILDREN_COPY); -#endignore - - return newBuilderUsing(delegate, to, from).named(parentBuilder.getName() + " subSet " + from + "-" + to) - .withFeatures(features).suppressing(parentBuilder.getSuppressedTests()) - .withSetUp(parentBuilder.getSetUp()).withTearDown(parentBuilder.getTearDown()).createTestSuite(); - } - - SORTED_SET_TEST_BUILDER KEY_GENERIC_TYPE newBuilderUsing(TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE delegate, Bound to, Bound from) { - return using(new SUB_SORTED_SET_CLASS_GENERATORBRACES(delegate, to, from)); - } -} +package speiger.src.testers.PACKAGE.builder; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import com.google.common.collect.testing.AbstractTester; +import com.google.common.collect.testing.DerivedCollectionGenerators.Bound; +import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder; +import com.google.common.collect.testing.Helpers; +import com.google.common.collect.testing.OneSizeTestContainerGenerator; +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.Feature; +import com.google.common.collect.testing.testers.SortedSetNavigationTester; + +import junit.framework.TestSuite; +import speiger.src.testers.PACKAGE.generators.TEST_SORTED_SET_GENERATOR; +import speiger.src.testers.PACKAGE.impl.SUB_SORTED_SET_CLASS_GENERATOR; +import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPESortedSetIterationTester; +import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPESortedSetNaviationTester; +import speiger.src.testers.utils.SpecialFeature; + +@SuppressWarnings("javadoc") +public class SORTED_SET_TEST_BUILDER KEY_GENERIC_TYPE extends SET_TEST_BUILDER KEY_GENERIC_TYPE { + public static GENERIC_KEY_BRACES SORTED_SET_TEST_BUILDER KEY_GENERIC_TYPE using(TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE generator) { + return (SORTED_SET_TEST_BUILDER KEY_GENERIC_TYPE) new SORTED_SET_TEST_BUILDER KEY_GENERIC_TYPE().usingGenerator(generator); + } + + @Override + @SuppressWarnings("rawtypes") + protected List> getTesters() { + List> testers = Helpers.copyToList(super.getTesters()); + testers.add(SortedSetNavigationTester.class); + testers.add(FILE_KEY_TYPESortedSetIterationTester.class); + testers.add(FILE_KEY_TYPESortedSetNaviationTester.class); + return testers; + } + + @Override + public TestSuite createTestSuite() { + if (!getFeatures().contains(CollectionFeature.KNOWN_ORDER)) { + List> features = Helpers.copyToList(getFeatures()); +#ignore + features.add(CollectionFeature.KNOWN_ORDER); +#endignore + withFeatures(features); + } + return super.createTestSuite(); + } + + @Override + protected List createDerivedSuites( + FeatureSpecificTestSuiteBuilder, CLASS_TYPE>> parentBuilder) { + List derivedSuites = super.createDerivedSuites(parentBuilder); + +#ignore + if (!parentBuilder.getFeatures().contains(CollectionFeature.SUBSET_VIEW)) { +#endignore + derivedSuites.add(createSubsetSuite(parentBuilder, Bound.NO_BOUND, Bound.EXCLUSIVE)); + derivedSuites.add(createSubsetSuite(parentBuilder, Bound.INCLUSIVE, Bound.NO_BOUND)); + derivedSuites.add(createSubsetSuite(parentBuilder, Bound.INCLUSIVE, Bound.EXCLUSIVE)); + } + + return derivedSuites; + } + + final TestSuite createSubsetSuite( + FeatureSpecificTestSuiteBuilder, CLASS_TYPE>> parentBuilder, + Bound from, Bound to) { + TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE delegate = (TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE) parentBuilder.getSubjectGenerator().getInnerGenerator(); + + List> features = new ArrayList<>(parentBuilder.getFeatures()); +#ignore + features.remove(CollectionFeature.ALLOWS_NULL_VALUES); + features.add(CollectionFeature.SUBSET_VIEW); + features.remove(SpecialFeature.COPYING); + features.remove(SpecialFeature.CHILDREN_COPY); +#endignore + + return newBuilderUsing(delegate, to, from).named(parentBuilder.getName() + " subSet " + from + "-" + to) + .withFeatures(features).suppressing(parentBuilder.getSuppressedTests()) + .withSetUp(parentBuilder.getSetUp()).withTearDown(parentBuilder.getTearDown()).createTestSuite(); + } + + SORTED_SET_TEST_BUILDER KEY_GENERIC_TYPE newBuilderUsing(TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE delegate, Bound to, Bound from) { + return using(new SUB_SORTED_SET_CLASS_GENERATORBRACES(delegate, to, from)); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/builder/maps/MapTestSuiteBuilder.template b/src/builder/resources/speiger/assets/testers/templates/builder/maps/MapTestSuiteBuilder.template index 9d609b0..557b92a 100644 --- a/src/builder/resources/speiger/assets/testers/templates/builder/maps/MapTestSuiteBuilder.template +++ b/src/builder/resources/speiger/assets/testers/templates/builder/maps/MapTestSuiteBuilder.template @@ -1,304 +1,304 @@ -package speiger.src.testers.PACKAGE.builder.maps; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.google.common.collect.testing.AbstractTester; -import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder; -import com.google.common.collect.testing.MapTestSuiteBuilder; -import com.google.common.collect.testing.OneSizeTestContainerGenerator; -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.Feature; -import com.google.common.collect.testing.features.MapFeature; -import com.google.common.collect.testing.testers.CollectionIteratorTester; -#if VALUE_BOOLEAN -import com.google.common.collect.testing.testers.CollectionRemoveTester; -import com.google.common.collect.testing.testers.CollectionRetainAllTester; -#endif - -import junit.framework.TestSuite; -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.testers.VALUE_PACKAGE.builder.VALUE_COLLECTION_TEST_BUILDER; -import speiger.src.testers.VALUE_PACKAGE.generators.VALUE_TEST_COLLECTION_GENERATOR; -#if !TYPE_OBJECT -import speiger.src.testers.PACKAGE.builder.SET_TEST_BUILDER; -import speiger.src.testers.PACKAGE.generators.TEST_SET_GENERATOR; -#endif -import speiger.src.testers.PACKAGE.generators.maps.TEST_MAP_GENERATOR; -import speiger.src.testers.PACKAGE.impl.maps.DERIVED_MAP_GENERATORS; -#if TYPE_CHAR || TYPE_FLOAT || TYPE_DOUBLE -import speiger.src.testers.PACKAGE.tests.collection.FILE_KEY_TYPECollectionIteratorTester; -#if !SAME_TYPE && !VALUE_OBJECT -import speiger.src.testers.VALUE_PACKAGE.tests.collection.FILE_VALUE_TYPECollectionIteratorTester; -#endif -#else if TYPE_OBJECT && !VALUE_OBJECT -import speiger.src.testers.VALUE_PACKAGE.tests.collection.FILE_VALUE_TYPECollectionIteratorTester; -#endif -#if VALUE_PRIMITIVES -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapAddToTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapSubFromTester; -#endif -#if VALUE_BOOLEAN -#if !TYPE_CHAR && !TYPE_FLOAT && !TYPE_DOUBLE && !TYPE_OBJECT -import speiger.src.testers.VALUE_PACKAGE.tests.collection.FILE_VALUE_TYPECollectionIteratorTester; -#endif -import speiger.src.testers.VALUE_PACKAGE.tests.collection.FILE_VALUE_TYPECollectionRemoveAllTester; -import speiger.src.testers.VALUE_PACKAGE.tests.collection.FILE_VALUE_TYPECollectionRetainAllTester; -#endif - -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapClearTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeIfAbsentTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeIfPresentTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapCopyTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapContainsTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapContainsKeyTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapContainsValueTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapEntrySetTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapEqualsTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapForEachTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapGetOrDefaultTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapGetTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapHashCodeTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapIsEmptyTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapMergeTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapMergeBulkTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutAllArrayTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutAllTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutIfAbsentTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapRemoveEntryTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapRemoveOrDefaultTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapRemoveTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapReplaceAllTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapReplaceEntryTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapReplaceTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapSizeTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapSupplyIfAbsentTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapToStringTester; -import speiger.src.testers.objects.builder.ObjectSetTestSuiteBuilder; -import speiger.src.testers.objects.generators.TestObjectSetGenerator; -import speiger.src.testers.objects.tests.collection.ObjectCollectionIteratorTester; -import speiger.src.testers.objects.tests.collection.ObjectCollectionRemoveAllTester; -import speiger.src.testers.objects.tests.collection.ObjectCollectionRetainAllTester; -import speiger.src.testers.utils.SpecialFeature; -import speiger.src.testers.utils.TestUtils; - -@SuppressWarnings("javadoc") -public class MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE extends MapTestSuiteBuilder { - boolean shouldBlockKeys; - - public static GENERIC_KEY_VALUE_BRACES MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE using(TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE generator) { - return (MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE) new MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE().usingGenerator(generator); - } - - public MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE shouldBlockKeys(boolean value) { - shouldBlockKeys = value; - return this; - } - - @Override - @SuppressWarnings("rawtypes") - protected List> getTesters() { - List> testers = new ArrayList<>(); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapClearTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeIfAbsentTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeIfPresentTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapSupplyIfAbsentTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapCopyTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapContainsTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapContainsKeyTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapContainsValueTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapEntrySetTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapEqualsTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapForEachTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapGetTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapGetOrDefaultTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapHashCodeTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapIsEmptyTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapMergeTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapMergeBulkTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutTester.class); -#if VALUE_PRIMITIVES - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapAddToTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapSubFromTester.class); -#endif - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutAllTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutAllArrayTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutIfAbsentTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapRemoveTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapRemoveEntryTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapRemoveOrDefaultTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapReplaceTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapReplaceAllTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapReplaceEntryTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapSizeTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapToStringTester.class); - return testers; - } - - @Override - protected List createDerivedSuites(FeatureSpecificTestSuiteBuilder, Map.Entry>> parentBuilder) { - List derivedSuites = new ArrayList<>(); - derivedSuites.add(createDerivedEntrySetSuite( - DERIVED_MAP_GENERATORS.entrySetGenerator(parentBuilder.getSubjectGenerator())) - .withFeatures(computeEntrySetFeatures(parentBuilder.getFeatures())) - .named(parentBuilder.getName() + " entrySet") - .suppressing(getEntrySetSuppressing(parentBuilder.getSuppressedTests())).suppressing(getSuppressing(1)) - .withSetUp(parentBuilder.getSetUp()).withTearDown(parentBuilder.getTearDown()) - .createTestSuite()); - - derivedSuites.add(createDerivedKeySetSuite( - DERIVED_MAP_GENERATORS.keySetGenerator(parentBuilder.getSubjectGenerator())) - .withFeatures(computeKeySetFeatures(parentBuilder.getFeatures())) - .named(parentBuilder.getName() + " keys").suppressing(parentBuilder.getSuppressedTests()).suppressing(getSuppressing(0)) - .withSetUp(parentBuilder.getSetUp()).withTearDown(parentBuilder.getTearDown()) - .createTestSuite()); -#if !TYPE_CHAR && !TYPE_OBJECT && !TYPE_FLOAT && !TYPE_DOUBLE || !VALUE_BOOLEAN - derivedSuites.add(createDerivedValueCollectionSuite( - new DERIVED_MAP_GENERATORS.MapValueCollectionGeneratorKV_BRACES(parentBuilder.getSubjectGenerator())) - .named(parentBuilder.getName() + " values") - .withFeatures(computeValuesCollectionFeatures(parentBuilder.getFeatures())) - .suppressing(parentBuilder.getSuppressedTests()).suppressing(getSuppressing(2)).withSetUp(parentBuilder.getSetUp()) - .withTearDown(parentBuilder.getTearDown()).createTestSuite()); -#endif - return derivedSuites; - } - - protected ObjectSetTestSuiteBuilder createDerivedEntrySetSuite(TestObjectSetGenerator entrySetGenerator) { - return ObjectSetTestSuiteBuilder.using(entrySetGenerator); - } - - protected SET_TEST_BUILDER KEY_GENERIC_TYPE createDerivedKeySetSuite(TEST_SET_GENERATOR KEY_GENERIC_TYPE generator) { - return SET_TEST_BUILDER.using(generator); - } - - protected VALUE_COLLECTION_TEST_BUILDER VALUE_GENERIC_TYPE createDerivedValueCollectionSuite(VALUE_TEST_COLLECTION_GENERATOR VALUE_GENERIC_TYPE generator) { - return VALUE_COLLECTION_TEST_BUILDER.using(generator); - } - - private Method[] getSuppressing(int type) { -#if TYPE_CHAR || TYPE_OBJECT || TYPE_FLOAT || TYPE_DOUBLE - if(shouldBlockKeys) { - switch(type) { - case 0: return TestUtils.getSurpession(FILE_KEY_TYPECollectionIteratorTester.class, "testIterator_unknownOrderRemoveSupported"); - case 1: return TestUtils.getSurpession(ObjectCollectionIteratorTester.class, "testIterator_unknownOrderRemoveSupported"); - case 2: { - List result = new ArrayList<>(); - TestUtils.getSurpession(result, FILE_VALUE_TYPECollectionIteratorTester.class, "testIterator_unknownOrderRemoveSupported"); -#if VALUE_BOOLEAN - TestUtils.getSurpession(result, CollectionRemoveTester.class, "testRemove_present"); - TestUtils.getSurpession(result, CollectionRetainAllTester.class); - TestUtils.getSurpession(result, FILE_VALUE_TYPECollectionIteratorTester.class, "testIterator_removeAffectsBackingCollection"); - TestUtils.getSurpession(result, FILE_VALUE_TYPECollectionRemoveAllTester.class, "testRemoveAll_someFetchRemovedElements"); - TestUtils.getSurpession(result, FILE_VALUE_TYPECollectionRetainAllTester.class); -#endif - return result.toArray(new Method[result.size()]); - } - } - } - return new Method[0]; -#else if VALUE_BOOLEAN - if(type == 2) { - List result = new ArrayList<>(); - TestUtils.getSurpession(result, FILE_VALUE_TYPECollectionIteratorTester.class, "testIterator_unknownOrderRemoveSupported"); -#if VALUE_BOOLEAN - TestUtils.getSurpession(result, CollectionRemoveTester.class, "testRemove_present"); - TestUtils.getSurpession(result, CollectionRetainAllTester.class); - TestUtils.getSurpession(result, FILE_VALUE_TYPECollectionIteratorTester.class, "testIterator_removeAffectsBackingCollection"); - TestUtils.getSurpession(result, FILE_VALUE_TYPECollectionRemoveAllTester.class, "testRemoveAll_someFetchRemovedElements"); - TestUtils.getSurpession(result, FILE_VALUE_TYPECollectionRetainAllTester.class); -#endif - return result.toArray(new Method[result.size()]); - } - return new Method[0]; -#else - return new Method[0]; -#endif - } - - private static Set> computeEntrySetFeatures(Set> mapFeatures) { - Set> entrySetFeatures = MapTestSuiteBuilder.computeCommonDerivedCollectionFeatures(mapFeatures); -#ignore - if (mapFeatures.contains(MapFeature.ALLOWS_NULL_ENTRY_QUERIES)) { - entrySetFeatures.add(CollectionFeature.ALLOWS_NULL_QUERIES); - } - if(mapFeatures.contains(SpecialFeature.CHILDREN_COPY)) { - entrySetFeatures.add(SpecialFeature.COPYING); - } - else { - entrySetFeatures.remove(SpecialFeature.COPYING); - } - if(mapFeatures.contains(SpecialFeature.MODIFIABLE)) { - entrySetFeatures.add(SpecialFeature.MODIFIABLE); - } - else { - entrySetFeatures.remove(SpecialFeature.MODIFIABLE); - } - entrySetFeatures.add(SpecialFeature.MAP_ENTRY); -#endignore - return entrySetFeatures; - } - - private static Set> computeKeySetFeatures(Set> mapFeatures) { - Set> keySetFeatures = MapTestSuiteBuilder.computeCommonDerivedCollectionFeatures(mapFeatures); -#ignore - keySetFeatures.add(CollectionFeature.SUBSET_VIEW); - if (mapFeatures.contains(MapFeature.ALLOWS_NULL_KEYS)) { - keySetFeatures.add(CollectionFeature.ALLOWS_NULL_VALUES); - } else if (mapFeatures.contains(MapFeature.ALLOWS_NULL_KEY_QUERIES)) { - keySetFeatures.add(CollectionFeature.ALLOWS_NULL_QUERIES); - } - if(mapFeatures.contains(SpecialFeature.CHILDREN_COPY)) { - keySetFeatures.add(SpecialFeature.COPYING); - } - else { - keySetFeatures.remove(SpecialFeature.COPYING); - } - if(mapFeatures.contains(SpecialFeature.MODIFIABLE)) { - keySetFeatures.add(SpecialFeature.MODIFIABLE); - } - else { - keySetFeatures.remove(SpecialFeature.MODIFIABLE); - } -#endignore - return keySetFeatures; - } - -#if !TYPE_CHAR && !TYPE_OBJECT && !TYPE_FLOAT && !TYPE_DOUBLE || !VALUE_BOOLEAN - private static Set> computeValuesCollectionFeatures(Set> mapFeatures) { - Set> valuesCollectionFeatures = MapTestSuiteBuilder.computeCommonDerivedCollectionFeatures(mapFeatures); -#ignore - if (mapFeatures.contains(MapFeature.ALLOWS_NULL_VALUE_QUERIES)) { - valuesCollectionFeatures.add(CollectionFeature.ALLOWS_NULL_QUERIES); - } - if (mapFeatures.contains(MapFeature.ALLOWS_NULL_VALUES)) { - valuesCollectionFeatures.add(CollectionFeature.ALLOWS_NULL_VALUES); - } - if(mapFeatures.contains(SpecialFeature.CHILDREN_COPY)) { - valuesCollectionFeatures.add(SpecialFeature.COPYING); - } - else { - valuesCollectionFeatures.remove(SpecialFeature.COPYING); - } -#endignore - return valuesCollectionFeatures; - } - -#endif - private static Set getEntrySetSuppressing(Set suppressing) { - TestUtils.getSurpession(suppressing, CollectionIteratorTester.class, "testIterator_removeAffectsBackingCollection"); - TestUtils.getSurpession(suppressing, ObjectCollectionIteratorTester.class, "testIterator_removeAffectsBackingCollection"); - TestUtils.getSurpession(suppressing, ObjectCollectionRemoveAllTester.class, "testRemoveAll_someFetchRemovedElements"); - TestUtils.getSurpession(suppressing, ObjectCollectionRetainAllTester.class, "testRetainAllExtra_disjointPreviouslyNonEmpty", "testRetainAllExtra_containsDuplicatesSizeSeveral", "testRetainAllExtra_subset", "testRetainAllExtra_partialOverlap"); -#if TYPE_DOUBLE || TYPE_FLOAT - TestUtils.getSurpession(suppressing, CollectionIteratorTester.class, "testIterator_unknownOrderRemoveSupported"); - TestUtils.getSurpession(suppressing, ObjectCollectionIteratorTester.class, "testIterator_unknownOrderRemoveSupported"); -#endif - return suppressing; - } +package speiger.src.testers.PACKAGE.builder.maps; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.common.collect.testing.AbstractTester; +import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder; +import com.google.common.collect.testing.MapTestSuiteBuilder; +import com.google.common.collect.testing.OneSizeTestContainerGenerator; +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.Feature; +import com.google.common.collect.testing.features.MapFeature; +import com.google.common.collect.testing.testers.CollectionIteratorTester; +#if VALUE_BOOLEAN +import com.google.common.collect.testing.testers.CollectionRemoveTester; +import com.google.common.collect.testing.testers.CollectionRetainAllTester; +#endif + +import junit.framework.TestSuite; +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.testers.VALUE_PACKAGE.builder.VALUE_COLLECTION_TEST_BUILDER; +import speiger.src.testers.VALUE_PACKAGE.generators.VALUE_TEST_COLLECTION_GENERATOR; +#if !TYPE_OBJECT +import speiger.src.testers.PACKAGE.builder.SET_TEST_BUILDER; +import speiger.src.testers.PACKAGE.generators.TEST_SET_GENERATOR; +#endif +import speiger.src.testers.PACKAGE.generators.maps.TEST_MAP_GENERATOR; +import speiger.src.testers.PACKAGE.impl.maps.DERIVED_MAP_GENERATORS; +#if TYPE_CHAR || TYPE_FLOAT || TYPE_DOUBLE +import speiger.src.testers.PACKAGE.tests.collection.FILE_KEY_TYPECollectionIteratorTester; +#if !SAME_TYPE && !VALUE_OBJECT +import speiger.src.testers.VALUE_PACKAGE.tests.collection.FILE_VALUE_TYPECollectionIteratorTester; +#endif +#else if TYPE_OBJECT && !VALUE_OBJECT +import speiger.src.testers.VALUE_PACKAGE.tests.collection.FILE_VALUE_TYPECollectionIteratorTester; +#endif +#if VALUE_PRIMITIVES +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapAddToTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapSubFromTester; +#endif +#if VALUE_BOOLEAN +#if !TYPE_CHAR && !TYPE_FLOAT && !TYPE_DOUBLE && !TYPE_OBJECT +import speiger.src.testers.VALUE_PACKAGE.tests.collection.FILE_VALUE_TYPECollectionIteratorTester; +#endif +import speiger.src.testers.VALUE_PACKAGE.tests.collection.FILE_VALUE_TYPECollectionRemoveAllTester; +import speiger.src.testers.VALUE_PACKAGE.tests.collection.FILE_VALUE_TYPECollectionRetainAllTester; +#endif + +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapClearTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeIfAbsentTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeIfPresentTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapCopyTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapContainsTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapContainsKeyTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapContainsValueTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapEntrySetTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapEqualsTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapForEachTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapGetOrDefaultTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapGetTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapHashCodeTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapIsEmptyTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapMergeTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapMergeBulkTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutAllArrayTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutAllTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutIfAbsentTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapRemoveEntryTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapRemoveOrDefaultTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapRemoveTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapReplaceAllTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapReplaceEntryTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapReplaceTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapSizeTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapSupplyIfAbsentTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapToStringTester; +import speiger.src.testers.objects.builder.ObjectSetTestSuiteBuilder; +import speiger.src.testers.objects.generators.TestObjectSetGenerator; +import speiger.src.testers.objects.tests.collection.ObjectCollectionIteratorTester; +import speiger.src.testers.objects.tests.collection.ObjectCollectionRemoveAllTester; +import speiger.src.testers.objects.tests.collection.ObjectCollectionRetainAllTester; +import speiger.src.testers.utils.SpecialFeature; +import speiger.src.testers.utils.TestUtils; + +@SuppressWarnings("javadoc") +public class MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE extends MapTestSuiteBuilder { + boolean shouldBlockKeys; + + public static GENERIC_KEY_VALUE_BRACES MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE using(TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE generator) { + return (MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE) new MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE().usingGenerator(generator); + } + + public MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE shouldBlockKeys(boolean value) { + shouldBlockKeys = value; + return this; + } + + @Override + @SuppressWarnings("rawtypes") + protected List> getTesters() { + List> testers = new ArrayList<>(); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapClearTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeIfAbsentTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeIfPresentTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapSupplyIfAbsentTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapCopyTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapContainsTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapContainsKeyTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapContainsValueTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapEntrySetTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapEqualsTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapForEachTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapGetTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapGetOrDefaultTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapHashCodeTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapIsEmptyTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapMergeTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapMergeBulkTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutTester.class); +#if VALUE_PRIMITIVES + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapAddToTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapSubFromTester.class); +#endif + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutAllTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutAllArrayTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutIfAbsentTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapRemoveTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapRemoveEntryTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapRemoveOrDefaultTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapReplaceTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapReplaceAllTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapReplaceEntryTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapSizeTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEMapToStringTester.class); + return testers; + } + + @Override + protected List createDerivedSuites(FeatureSpecificTestSuiteBuilder, Map.Entry>> parentBuilder) { + List derivedSuites = new ArrayList<>(); + derivedSuites.add(createDerivedEntrySetSuite( + DERIVED_MAP_GENERATORS.entrySetGenerator(parentBuilder.getSubjectGenerator())) + .withFeatures(computeEntrySetFeatures(parentBuilder.getFeatures())) + .named(parentBuilder.getName() + " entrySet") + .suppressing(getEntrySetSuppressing(parentBuilder.getSuppressedTests())).suppressing(getSuppressing(1)) + .withSetUp(parentBuilder.getSetUp()).withTearDown(parentBuilder.getTearDown()) + .createTestSuite()); + + derivedSuites.add(createDerivedKeySetSuite( + DERIVED_MAP_GENERATORS.keySetGenerator(parentBuilder.getSubjectGenerator())) + .withFeatures(computeKeySetFeatures(parentBuilder.getFeatures())) + .named(parentBuilder.getName() + " keys").suppressing(parentBuilder.getSuppressedTests()).suppressing(getSuppressing(0)) + .withSetUp(parentBuilder.getSetUp()).withTearDown(parentBuilder.getTearDown()) + .createTestSuite()); +#if !TYPE_CHAR && !TYPE_OBJECT && !TYPE_FLOAT && !TYPE_DOUBLE || !VALUE_BOOLEAN + derivedSuites.add(createDerivedValueCollectionSuite( + new DERIVED_MAP_GENERATORS.MapValueCollectionGeneratorKV_BRACES(parentBuilder.getSubjectGenerator())) + .named(parentBuilder.getName() + " values") + .withFeatures(computeValuesCollectionFeatures(parentBuilder.getFeatures())) + .suppressing(parentBuilder.getSuppressedTests()).suppressing(getSuppressing(2)).withSetUp(parentBuilder.getSetUp()) + .withTearDown(parentBuilder.getTearDown()).createTestSuite()); +#endif + return derivedSuites; + } + + protected ObjectSetTestSuiteBuilder createDerivedEntrySetSuite(TestObjectSetGenerator entrySetGenerator) { + return ObjectSetTestSuiteBuilder.using(entrySetGenerator); + } + + protected SET_TEST_BUILDER KEY_GENERIC_TYPE createDerivedKeySetSuite(TEST_SET_GENERATOR KEY_GENERIC_TYPE generator) { + return SET_TEST_BUILDER.using(generator); + } + + protected VALUE_COLLECTION_TEST_BUILDER VALUE_GENERIC_TYPE createDerivedValueCollectionSuite(VALUE_TEST_COLLECTION_GENERATOR VALUE_GENERIC_TYPE generator) { + return VALUE_COLLECTION_TEST_BUILDER.using(generator); + } + + private Method[] getSuppressing(int type) { +#if TYPE_CHAR || TYPE_OBJECT || TYPE_FLOAT || TYPE_DOUBLE + if(shouldBlockKeys) { + switch(type) { + case 0: return TestUtils.getSurpession(FILE_KEY_TYPECollectionIteratorTester.class, "testIterator_unknownOrderRemoveSupported"); + case 1: return TestUtils.getSurpession(ObjectCollectionIteratorTester.class, "testIterator_unknownOrderRemoveSupported"); + case 2: { + List result = new ArrayList<>(); + TestUtils.getSurpession(result, FILE_VALUE_TYPECollectionIteratorTester.class, "testIterator_unknownOrderRemoveSupported"); +#if VALUE_BOOLEAN + TestUtils.getSurpession(result, CollectionRemoveTester.class, "testRemove_present"); + TestUtils.getSurpession(result, CollectionRetainAllTester.class); + TestUtils.getSurpession(result, FILE_VALUE_TYPECollectionIteratorTester.class, "testIterator_removeAffectsBackingCollection"); + TestUtils.getSurpession(result, FILE_VALUE_TYPECollectionRemoveAllTester.class, "testRemoveAll_someFetchRemovedElements"); + TestUtils.getSurpession(result, FILE_VALUE_TYPECollectionRetainAllTester.class); +#endif + return result.toArray(new Method[result.size()]); + } + } + } + return new Method[0]; +#else if VALUE_BOOLEAN + if(type == 2) { + List result = new ArrayList<>(); + TestUtils.getSurpession(result, FILE_VALUE_TYPECollectionIteratorTester.class, "testIterator_unknownOrderRemoveSupported"); +#if VALUE_BOOLEAN + TestUtils.getSurpession(result, CollectionRemoveTester.class, "testRemove_present"); + TestUtils.getSurpession(result, CollectionRetainAllTester.class); + TestUtils.getSurpession(result, FILE_VALUE_TYPECollectionIteratorTester.class, "testIterator_removeAffectsBackingCollection"); + TestUtils.getSurpession(result, FILE_VALUE_TYPECollectionRemoveAllTester.class, "testRemoveAll_someFetchRemovedElements"); + TestUtils.getSurpession(result, FILE_VALUE_TYPECollectionRetainAllTester.class); +#endif + return result.toArray(new Method[result.size()]); + } + return new Method[0]; +#else + return new Method[0]; +#endif + } + + private static Set> computeEntrySetFeatures(Set> mapFeatures) { + Set> entrySetFeatures = MapTestSuiteBuilder.computeCommonDerivedCollectionFeatures(mapFeatures); +#ignore + if (mapFeatures.contains(MapFeature.ALLOWS_NULL_ENTRY_QUERIES)) { + entrySetFeatures.add(CollectionFeature.ALLOWS_NULL_QUERIES); + } + if(mapFeatures.contains(SpecialFeature.CHILDREN_COPY)) { + entrySetFeatures.add(SpecialFeature.COPYING); + } + else { + entrySetFeatures.remove(SpecialFeature.COPYING); + } + if(mapFeatures.contains(SpecialFeature.MODIFIABLE)) { + entrySetFeatures.add(SpecialFeature.MODIFIABLE); + } + else { + entrySetFeatures.remove(SpecialFeature.MODIFIABLE); + } + entrySetFeatures.add(SpecialFeature.MAP_ENTRY); +#endignore + return entrySetFeatures; + } + + private static Set> computeKeySetFeatures(Set> mapFeatures) { + Set> keySetFeatures = MapTestSuiteBuilder.computeCommonDerivedCollectionFeatures(mapFeatures); +#ignore + keySetFeatures.add(CollectionFeature.SUBSET_VIEW); + if (mapFeatures.contains(MapFeature.ALLOWS_NULL_KEYS)) { + keySetFeatures.add(CollectionFeature.ALLOWS_NULL_VALUES); + } else if (mapFeatures.contains(MapFeature.ALLOWS_NULL_KEY_QUERIES)) { + keySetFeatures.add(CollectionFeature.ALLOWS_NULL_QUERIES); + } + if(mapFeatures.contains(SpecialFeature.CHILDREN_COPY)) { + keySetFeatures.add(SpecialFeature.COPYING); + } + else { + keySetFeatures.remove(SpecialFeature.COPYING); + } + if(mapFeatures.contains(SpecialFeature.MODIFIABLE)) { + keySetFeatures.add(SpecialFeature.MODIFIABLE); + } + else { + keySetFeatures.remove(SpecialFeature.MODIFIABLE); + } +#endignore + return keySetFeatures; + } + +#if !TYPE_CHAR && !TYPE_OBJECT && !TYPE_FLOAT && !TYPE_DOUBLE || !VALUE_BOOLEAN + private static Set> computeValuesCollectionFeatures(Set> mapFeatures) { + Set> valuesCollectionFeatures = MapTestSuiteBuilder.computeCommonDerivedCollectionFeatures(mapFeatures); +#ignore + if (mapFeatures.contains(MapFeature.ALLOWS_NULL_VALUE_QUERIES)) { + valuesCollectionFeatures.add(CollectionFeature.ALLOWS_NULL_QUERIES); + } + if (mapFeatures.contains(MapFeature.ALLOWS_NULL_VALUES)) { + valuesCollectionFeatures.add(CollectionFeature.ALLOWS_NULL_VALUES); + } + if(mapFeatures.contains(SpecialFeature.CHILDREN_COPY)) { + valuesCollectionFeatures.add(SpecialFeature.COPYING); + } + else { + valuesCollectionFeatures.remove(SpecialFeature.COPYING); + } +#endignore + return valuesCollectionFeatures; + } + +#endif + private static Set getEntrySetSuppressing(Set suppressing) { + TestUtils.getSurpession(suppressing, CollectionIteratorTester.class, "testIterator_removeAffectsBackingCollection"); + TestUtils.getSurpession(suppressing, ObjectCollectionIteratorTester.class, "testIterator_removeAffectsBackingCollection"); + TestUtils.getSurpession(suppressing, ObjectCollectionRemoveAllTester.class, "testRemoveAll_someFetchRemovedElements"); + TestUtils.getSurpession(suppressing, ObjectCollectionRetainAllTester.class, "testRetainAllExtra_disjointPreviouslyNonEmpty", "testRetainAllExtra_containsDuplicatesSizeSeveral", "testRetainAllExtra_subset", "testRetainAllExtra_partialOverlap"); +#if TYPE_DOUBLE || TYPE_FLOAT + TestUtils.getSurpession(suppressing, CollectionIteratorTester.class, "testIterator_unknownOrderRemoveSupported"); + TestUtils.getSurpession(suppressing, ObjectCollectionIteratorTester.class, "testIterator_unknownOrderRemoveSupported"); +#endif + return suppressing; + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/builder/maps/NavigableMapTestSuiteBuilder.template b/src/builder/resources/speiger/assets/testers/templates/builder/maps/NavigableMapTestSuiteBuilder.template index 9a759d7..9a61543 100644 --- a/src/builder/resources/speiger/assets/testers/templates/builder/maps/NavigableMapTestSuiteBuilder.template +++ b/src/builder/resources/speiger/assets/testers/templates/builder/maps/NavigableMapTestSuiteBuilder.template @@ -1,79 +1,79 @@ -package speiger.src.testers.PACKAGE.builder.maps; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import com.google.common.collect.testing.AbstractTester; -import com.google.common.collect.testing.DerivedCollectionGenerators.Bound; -import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder; -import com.google.common.collect.testing.OneSizeTestContainerGenerator; -import com.google.common.collect.testing.features.Feature; - -import junit.framework.TestSuite; -import speiger.src.testers.PACKAGE.builder.NAVIGABLE_SET_TEST_BUILDER; -import speiger.src.testers.PACKAGE.generators.TEST_SET_GENERATOR; -import speiger.src.testers.PACKAGE.generators.TEST_NAVIGABLE_SET_GENERATOR; -import speiger.src.testers.PACKAGE.generators.maps.TEST_SORTED_MAP_GENERATOR; -import speiger.src.testers.PACKAGE.impl.maps.DERIVED_MAP_GENERATORS; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPENavigableMapNavigationTester; -import speiger.src.testers.utils.SpecialFeature; - -@SuppressWarnings("javadoc") -public class NAVIGABLE_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE extends SORTED_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE -{ - public static GENERIC_KEY_VALUE_BRACES NAVIGABLE_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE using(TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE generator) { - return (NAVIGABLE_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE)new NAVIGABLE_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE().usingGenerator(generator); - } - - @Override - @SuppressWarnings("rawtypes") - protected List> getTesters() { - List> testers = super.getTesters(); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPENavigableMapNavigationTester.class); - return testers; - } - - @Override - protected List createDerivedSuites(FeatureSpecificTestSuiteBuilder, Map.Entry>> parentBuilder) { - List derivedSuites = super.createDerivedSuites(parentBuilder); -#ignore - if (!parentBuilder.getFeatures().contains(SpecialFeature.DESCENDING)) { - derivedSuites.add(createDescendingSuite(parentBuilder)); - } - if (!parentBuilder.getFeatures().contains(SpecialFeature.SUBMAP)) { - derivedSuites.add(createSubmapSuite(parentBuilder, Bound.NO_BOUND, Bound.INCLUSIVE)); - derivedSuites.add(createSubmapSuite(parentBuilder, Bound.EXCLUSIVE, Bound.NO_BOUND)); - derivedSuites.add(createSubmapSuite(parentBuilder, Bound.EXCLUSIVE, Bound.EXCLUSIVE)); - derivedSuites.add(createSubmapSuite(parentBuilder, Bound.EXCLUSIVE, Bound.INCLUSIVE)); - derivedSuites.add(createSubmapSuite(parentBuilder, Bound.INCLUSIVE, Bound.INCLUSIVE)); - } -#endignore - return derivedSuites; - } - - @Override - NAVIGABLE_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE newBuilderUsing(TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE delegate, Bound to, Bound from) { - return NAVIGABLE_MAP_TEST_BUILDER.using(new DERIVED_MAP_GENERATORS.NavigableMapGeneratorKV_BRACES(delegate, to, from)); - } - - private TestSuite createDescendingSuite(FeatureSpecificTestSuiteBuilder, Map.Entry>> parentBuilder) { - TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE delegate = (TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE) parentBuilder.getSubjectGenerator().getInnerGenerator(); - - List> features = new ArrayList<>(); -#ignore - features.add(SpecialFeature.DESCENDING); - features.addAll(parentBuilder.getFeatures()); - features.remove(SpecialFeature.COPYING); - features.remove(SpecialFeature.CHILDREN_COPY); -#endignore - return NAVIGABLE_MAP_TEST_BUILDER.using(new DERIVED_MAP_GENERATORS.DescendingTestMapGeneratorKV_BRACES(delegate)) - .named(parentBuilder.getName() + " descending").withFeatures(features) - .suppressing(parentBuilder.getSuppressedTests()).createTestSuite(); - } - - @Override - protected NAVIGABLE_SET_TEST_BUILDER KEY_GENERIC_TYPE createDerivedKeySetSuite(TEST_SET_GENERATOR KEY_GENERIC_TYPE keySetGenerator) { - return NAVIGABLE_SET_TEST_BUILDER.using((TEST_NAVIGABLE_SET_GENERATOR KEY_GENERIC_TYPE) keySetGenerator); - } -} +package speiger.src.testers.PACKAGE.builder.maps; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import com.google.common.collect.testing.AbstractTester; +import com.google.common.collect.testing.DerivedCollectionGenerators.Bound; +import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder; +import com.google.common.collect.testing.OneSizeTestContainerGenerator; +import com.google.common.collect.testing.features.Feature; + +import junit.framework.TestSuite; +import speiger.src.testers.PACKAGE.builder.NAVIGABLE_SET_TEST_BUILDER; +import speiger.src.testers.PACKAGE.generators.TEST_SET_GENERATOR; +import speiger.src.testers.PACKAGE.generators.TEST_NAVIGABLE_SET_GENERATOR; +import speiger.src.testers.PACKAGE.generators.maps.TEST_SORTED_MAP_GENERATOR; +import speiger.src.testers.PACKAGE.impl.maps.DERIVED_MAP_GENERATORS; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPENavigableMapNavigationTester; +import speiger.src.testers.utils.SpecialFeature; + +@SuppressWarnings("javadoc") +public class NAVIGABLE_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE extends SORTED_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE +{ + public static GENERIC_KEY_VALUE_BRACES NAVIGABLE_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE using(TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE generator) { + return (NAVIGABLE_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE)new NAVIGABLE_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE().usingGenerator(generator); + } + + @Override + @SuppressWarnings("rawtypes") + protected List> getTesters() { + List> testers = super.getTesters(); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPENavigableMapNavigationTester.class); + return testers; + } + + @Override + protected List createDerivedSuites(FeatureSpecificTestSuiteBuilder, Map.Entry>> parentBuilder) { + List derivedSuites = super.createDerivedSuites(parentBuilder); +#ignore + if (!parentBuilder.getFeatures().contains(SpecialFeature.DESCENDING)) { + derivedSuites.add(createDescendingSuite(parentBuilder)); + } + if (!parentBuilder.getFeatures().contains(SpecialFeature.SUBMAP)) { + derivedSuites.add(createSubmapSuite(parentBuilder, Bound.NO_BOUND, Bound.INCLUSIVE)); + derivedSuites.add(createSubmapSuite(parentBuilder, Bound.EXCLUSIVE, Bound.NO_BOUND)); + derivedSuites.add(createSubmapSuite(parentBuilder, Bound.EXCLUSIVE, Bound.EXCLUSIVE)); + derivedSuites.add(createSubmapSuite(parentBuilder, Bound.EXCLUSIVE, Bound.INCLUSIVE)); + derivedSuites.add(createSubmapSuite(parentBuilder, Bound.INCLUSIVE, Bound.INCLUSIVE)); + } +#endignore + return derivedSuites; + } + + @Override + NAVIGABLE_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE newBuilderUsing(TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE delegate, Bound to, Bound from) { + return NAVIGABLE_MAP_TEST_BUILDER.using(new DERIVED_MAP_GENERATORS.NavigableMapGeneratorKV_BRACES(delegate, to, from)); + } + + private TestSuite createDescendingSuite(FeatureSpecificTestSuiteBuilder, Map.Entry>> parentBuilder) { + TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE delegate = (TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE) parentBuilder.getSubjectGenerator().getInnerGenerator(); + + List> features = new ArrayList<>(); +#ignore + features.add(SpecialFeature.DESCENDING); + features.addAll(parentBuilder.getFeatures()); + features.remove(SpecialFeature.COPYING); + features.remove(SpecialFeature.CHILDREN_COPY); +#endignore + return NAVIGABLE_MAP_TEST_BUILDER.using(new DERIVED_MAP_GENERATORS.DescendingTestMapGeneratorKV_BRACES(delegate)) + .named(parentBuilder.getName() + " descending").withFeatures(features) + .suppressing(parentBuilder.getSuppressedTests()).createTestSuite(); + } + + @Override + protected NAVIGABLE_SET_TEST_BUILDER KEY_GENERIC_TYPE createDerivedKeySetSuite(TEST_SET_GENERATOR KEY_GENERIC_TYPE keySetGenerator) { + return NAVIGABLE_SET_TEST_BUILDER.using((TEST_NAVIGABLE_SET_GENERATOR KEY_GENERIC_TYPE) keySetGenerator); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/builder/maps/OrderedMapTestSuiteBuilder.template b/src/builder/resources/speiger/assets/testers/templates/builder/maps/OrderedMapTestSuiteBuilder.template index 8aeb1ce..f47fbf2 100644 --- a/src/builder/resources/speiger/assets/testers/templates/builder/maps/OrderedMapTestSuiteBuilder.template +++ b/src/builder/resources/speiger/assets/testers/templates/builder/maps/OrderedMapTestSuiteBuilder.template @@ -1,55 +1,55 @@ -package speiger.src.testers.PACKAGE.builder.maps; - -import java.util.List; - -import com.google.common.collect.testing.AbstractTester; -import com.google.common.collect.testing.features.CollectionFeature; - -import junit.framework.TestSuite; -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.testers.PACKAGE.builder.ORDERED_SET_TEST_BUILDER; -import speiger.src.testers.PACKAGE.builder.SET_TEST_BUILDER; -import speiger.src.testers.PACKAGE.generators.TEST_ORDERED_SET_GENERATOR; -import speiger.src.testers.PACKAGE.generators.TEST_SET_GENERATOR; -import speiger.src.testers.PACKAGE.generators.maps.TEST_ORDERED_MAP_GENERATOR; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEOrderedMapMoveTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEOrderedMapNavigationTester; -#if !TYPE_OBJECT -import speiger.src.testers.objects.builder.ObjectSetTestSuiteBuilder; -import speiger.src.testers.objects.generators.TestObjectSetGenerator; -import speiger.src.testers.objects.builder.ObjectOrderedSetTestSuiteBuilder; -import speiger.src.testers.objects.generators.TestObjectOrderedSetGenerator; -#endif - -@SuppressWarnings("javadoc") -public class ORDERED_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE extends MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE -{ - public static GENERIC_KEY_VALUE_BRACES ORDERED_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE using(TEST_ORDERED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE generator) { - return (ORDERED_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE) new ORDERED_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE().usingGenerator(generator); - } - - @Override - @SuppressWarnings("rawtypes") - protected List> getTesters() { - List> testers = super.getTesters(); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEOrderedMapMoveTester.class); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEOrderedMapNavigationTester.class); - return testers; - } - - @Override - public TestSuite createTestSuite() { -#ignore - withFeatures(CollectionFeature.KNOWN_ORDER); -#endignore - return super.createTestSuite(); - } - - protected ObjectSetTestSuiteBuilder createDerivedEntrySetSuite(TestObjectSetGenerator entrySetGenerator) { - return ObjectOrderedSetTestSuiteBuilder.using((TestObjectOrderedSetGenerator)entrySetGenerator); - } - - protected SET_TEST_BUILDER KEY_GENERIC_TYPE createDerivedKeySetSuite(TEST_SET_GENERATOR KEY_GENERIC_TYPE generator) { - return ORDERED_SET_TEST_BUILDER.using((TEST_ORDERED_SET_GENERATOR KEY_GENERIC_TYPE)generator); - } -} +package speiger.src.testers.PACKAGE.builder.maps; + +import java.util.List; + +import com.google.common.collect.testing.AbstractTester; +import com.google.common.collect.testing.features.CollectionFeature; + +import junit.framework.TestSuite; +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.testers.PACKAGE.builder.ORDERED_SET_TEST_BUILDER; +import speiger.src.testers.PACKAGE.builder.SET_TEST_BUILDER; +import speiger.src.testers.PACKAGE.generators.TEST_ORDERED_SET_GENERATOR; +import speiger.src.testers.PACKAGE.generators.TEST_SET_GENERATOR; +import speiger.src.testers.PACKAGE.generators.maps.TEST_ORDERED_MAP_GENERATOR; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEOrderedMapMoveTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEOrderedMapNavigationTester; +#if !TYPE_OBJECT +import speiger.src.testers.objects.builder.ObjectSetTestSuiteBuilder; +import speiger.src.testers.objects.generators.TestObjectSetGenerator; +import speiger.src.testers.objects.builder.ObjectOrderedSetTestSuiteBuilder; +import speiger.src.testers.objects.generators.TestObjectOrderedSetGenerator; +#endif + +@SuppressWarnings("javadoc") +public class ORDERED_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE extends MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE +{ + public static GENERIC_KEY_VALUE_BRACES ORDERED_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE using(TEST_ORDERED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE generator) { + return (ORDERED_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE) new ORDERED_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE().usingGenerator(generator); + } + + @Override + @SuppressWarnings("rawtypes") + protected List> getTesters() { + List> testers = super.getTesters(); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEOrderedMapMoveTester.class); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEOrderedMapNavigationTester.class); + return testers; + } + + @Override + public TestSuite createTestSuite() { +#ignore + withFeatures(CollectionFeature.KNOWN_ORDER); +#endignore + return super.createTestSuite(); + } + + protected ObjectSetTestSuiteBuilder createDerivedEntrySetSuite(TestObjectSetGenerator entrySetGenerator) { + return ObjectOrderedSetTestSuiteBuilder.using((TestObjectOrderedSetGenerator)entrySetGenerator); + } + + protected SET_TEST_BUILDER KEY_GENERIC_TYPE createDerivedKeySetSuite(TEST_SET_GENERATOR KEY_GENERIC_TYPE generator) { + return ORDERED_SET_TEST_BUILDER.using((TEST_ORDERED_SET_GENERATOR KEY_GENERIC_TYPE)generator); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/builder/maps/SortedMapTestSuiteBuilder.template b/src/builder/resources/speiger/assets/testers/templates/builder/maps/SortedMapTestSuiteBuilder.template index 83b5bf8..e05f557 100644 --- a/src/builder/resources/speiger/assets/testers/templates/builder/maps/SortedMapTestSuiteBuilder.template +++ b/src/builder/resources/speiger/assets/testers/templates/builder/maps/SortedMapTestSuiteBuilder.template @@ -1,90 +1,90 @@ -package speiger.src.testers.PACKAGE.builder.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; -#endignore - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import com.google.common.collect.testing.AbstractTester; -import com.google.common.collect.testing.DerivedCollectionGenerators.Bound; -import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder; -import com.google.common.collect.testing.Helpers; -import com.google.common.collect.testing.OneSizeTestContainerGenerator; -import com.google.common.collect.testing.features.Feature; - -import junit.framework.TestSuite; -import speiger.src.testers.PACKAGE.generators.maps.TEST_SORTED_MAP_GENERATOR; -import speiger.src.testers.PACKAGE.impl.maps.DERIVED_MAP_GENERATORS; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPESortedMapNavigationTester; -import speiger.src.testers.PACKAGE.builder.SET_TEST_BUILDER; -import speiger.src.testers.PACKAGE.builder.SORTED_SET_TEST_BUILDER; -import speiger.src.testers.PACKAGE.generators.TEST_SET_GENERATOR; -import speiger.src.testers.PACKAGE.generators.TEST_SORTED_SET_GENERATOR; -import speiger.src.testers.utils.SpecialFeature; - -@SuppressWarnings("javadoc") -public class SORTED_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE extends MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE { - public static GENERIC_KEY_VALUE_BRACES SORTED_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE using(TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE generator) { - return (SORTED_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE) new SORTED_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE().usingGenerator(generator); - } - - @Override - @SuppressWarnings("rawtypes") - protected List> getTesters() { - List> testers = super.getTesters(); - testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPESortedMapNavigationTester.class); - return testers; - } - - @Override - public TestSuite createTestSuite() { -#ignore - if (!getFeatures().contains(KNOWN_ORDER)) { - List> features = Helpers.copyToList(getFeatures()); - features.add(KNOWN_ORDER); - withFeatures(features); - } -#endignore - return super.createTestSuite(); - } - - @Override - protected List createDerivedSuites(FeatureSpecificTestSuiteBuilder, Map.Entry>> parentBuilder) { - List derivedSuites = super.createDerivedSuites(parentBuilder); -#ignore - if (!parentBuilder.getFeatures().contains(SpecialFeature.SUBMAP)) { - derivedSuites.add(createSubmapSuite(parentBuilder, Bound.NO_BOUND, Bound.EXCLUSIVE)); - derivedSuites.add(createSubmapSuite(parentBuilder, Bound.INCLUSIVE, Bound.NO_BOUND)); - derivedSuites.add(createSubmapSuite(parentBuilder, Bound.INCLUSIVE, Bound.EXCLUSIVE)); - } -#endignore - return derivedSuites; - } - - @Override - protected SET_TEST_BUILDER KEY_GENERIC_TYPE createDerivedKeySetSuite(TEST_SET_GENERATOR KEY_GENERIC_TYPE keySetGenerator) { - return keySetGenerator instanceof TEST_SORTED_SET_GENERATOR ? SORTED_SET_TEST_BUILDER.using((TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE) keySetGenerator) : SET_TEST_BUILDER.using(keySetGenerator); - } - - TestSuite createSubmapSuite(FeatureSpecificTestSuiteBuilder, Map.Entry>> parentBuilder, Bound from, Bound to) { - TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE delegate = (TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE) parentBuilder.getSubjectGenerator().getInnerGenerator(); - List> features = new ArrayList<>(); -#ignore - features.add(SpecialFeature.SUBMAP); - features.addAll(parentBuilder.getFeatures()); - features.remove(SpecialFeature.COPYING); - features.remove(SpecialFeature.CHILDREN_COPY); -#endignore - - return newBuilderUsing(delegate, to, from).named(parentBuilder.getName() + " subMap " + from + "-" + to) - .withFeatures(features).suppressing(parentBuilder.getSuppressedTests()) - .withSetUp(parentBuilder.getSetUp()).withTearDown(parentBuilder.getTearDown()).createTestSuite(); - } - - SORTED_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE newBuilderUsing(TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE delegate, Bound to, Bound from) { - return using(new DERIVED_MAP_GENERATORS.SortedMapGeneratorKV_BRACES(delegate, to, from)); - } -} +package speiger.src.testers.PACKAGE.builder.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; +#endignore + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import com.google.common.collect.testing.AbstractTester; +import com.google.common.collect.testing.DerivedCollectionGenerators.Bound; +import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder; +import com.google.common.collect.testing.Helpers; +import com.google.common.collect.testing.OneSizeTestContainerGenerator; +import com.google.common.collect.testing.features.Feature; + +import junit.framework.TestSuite; +import speiger.src.testers.PACKAGE.generators.maps.TEST_SORTED_MAP_GENERATOR; +import speiger.src.testers.PACKAGE.impl.maps.DERIVED_MAP_GENERATORS; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPESortedMapNavigationTester; +import speiger.src.testers.PACKAGE.builder.SET_TEST_BUILDER; +import speiger.src.testers.PACKAGE.builder.SORTED_SET_TEST_BUILDER; +import speiger.src.testers.PACKAGE.generators.TEST_SET_GENERATOR; +import speiger.src.testers.PACKAGE.generators.TEST_SORTED_SET_GENERATOR; +import speiger.src.testers.utils.SpecialFeature; + +@SuppressWarnings("javadoc") +public class SORTED_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE extends MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE { + public static GENERIC_KEY_VALUE_BRACES SORTED_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE using(TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE generator) { + return (SORTED_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE) new SORTED_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE().usingGenerator(generator); + } + + @Override + @SuppressWarnings("rawtypes") + protected List> getTesters() { + List> testers = super.getTesters(); + testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPESortedMapNavigationTester.class); + return testers; + } + + @Override + public TestSuite createTestSuite() { +#ignore + if (!getFeatures().contains(KNOWN_ORDER)) { + List> features = Helpers.copyToList(getFeatures()); + features.add(KNOWN_ORDER); + withFeatures(features); + } +#endignore + return super.createTestSuite(); + } + + @Override + protected List createDerivedSuites(FeatureSpecificTestSuiteBuilder, Map.Entry>> parentBuilder) { + List derivedSuites = super.createDerivedSuites(parentBuilder); +#ignore + if (!parentBuilder.getFeatures().contains(SpecialFeature.SUBMAP)) { + derivedSuites.add(createSubmapSuite(parentBuilder, Bound.NO_BOUND, Bound.EXCLUSIVE)); + derivedSuites.add(createSubmapSuite(parentBuilder, Bound.INCLUSIVE, Bound.NO_BOUND)); + derivedSuites.add(createSubmapSuite(parentBuilder, Bound.INCLUSIVE, Bound.EXCLUSIVE)); + } +#endignore + return derivedSuites; + } + + @Override + protected SET_TEST_BUILDER KEY_GENERIC_TYPE createDerivedKeySetSuite(TEST_SET_GENERATOR KEY_GENERIC_TYPE keySetGenerator) { + return keySetGenerator instanceof TEST_SORTED_SET_GENERATOR ? SORTED_SET_TEST_BUILDER.using((TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE) keySetGenerator) : SET_TEST_BUILDER.using(keySetGenerator); + } + + TestSuite createSubmapSuite(FeatureSpecificTestSuiteBuilder, Map.Entry>> parentBuilder, Bound from, Bound to) { + TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE delegate = (TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE) parentBuilder.getSubjectGenerator().getInnerGenerator(); + List> features = new ArrayList<>(); +#ignore + features.add(SpecialFeature.SUBMAP); + features.addAll(parentBuilder.getFeatures()); + features.remove(SpecialFeature.COPYING); + features.remove(SpecialFeature.CHILDREN_COPY); +#endignore + + return newBuilderUsing(delegate, to, from).named(parentBuilder.getName() + " subMap " + from + "-" + to) + .withFeatures(features).suppressing(parentBuilder.getSuppressedTests()) + .withSetUp(parentBuilder.getSetUp()).withTearDown(parentBuilder.getTearDown()).createTestSuite(); + } + + SORTED_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE newBuilderUsing(TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE delegate, Bound to, Bound from) { + return using(new DERIVED_MAP_GENERATORS.SortedMapGeneratorKV_BRACES(delegate, to, from)); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/generators/TestCollectionGenerator.template b/src/builder/resources/speiger/assets/testers/templates/generators/TestCollectionGenerator.template index 09234fe..891a5bf 100644 --- a/src/builder/resources/speiger/assets/testers/templates/generators/TestCollectionGenerator.template +++ b/src/builder/resources/speiger/assets/testers/templates/generators/TestCollectionGenerator.template @@ -1,30 +1,30 @@ -package speiger.src.testers.PACKAGE.generators; - -import java.util.List; - -import com.google.common.collect.testing.SampleElements; -import com.google.common.collect.testing.TestCollectionGenerator; - -import speiger.src.collections.PACKAGE.collections.COLLECTION; -import speiger.src.collections.PACKAGE.collections.ITERABLE; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.testers.PACKAGE.utils.SAMPLE_ELEMENTS; - -@SuppressWarnings("javadoc") -public interface TEST_COLLECTION_GENERATOR KEY_GENERIC_TYPE extends TestCollectionGenerator -{ - public SAMPLE_ELEMENTS KEY_GENERIC_TYPE getSamples(); -#if !TYPE_OBJECT - public COLLECTION KEY_GENERIC_TYPE create(KEY_TYPE...elements); -#endif - public ITERABLE KEY_GENERIC_TYPE order(LIST KEY_GENERIC_TYPE insertionOrder); - - @Override - public default SampleElements samples() {return getSamples().toSamples();} - @Override - public COLLECTION KEY_GENERIC_TYPE create(Object... elements); - @Override - public default CLASS_TYPE[] createArray(int length) { return NEW_CLASS_ARRAY(length); } - @Override - public Iterable order(List insertionOrder); -} +package speiger.src.testers.PACKAGE.generators; + +import java.util.List; + +import com.google.common.collect.testing.SampleElements; +import com.google.common.collect.testing.TestCollectionGenerator; + +import speiger.src.collections.PACKAGE.collections.COLLECTION; +import speiger.src.collections.PACKAGE.collections.ITERABLE; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.testers.PACKAGE.utils.SAMPLE_ELEMENTS; + +@SuppressWarnings("javadoc") +public interface TEST_COLLECTION_GENERATOR KEY_GENERIC_TYPE extends TestCollectionGenerator +{ + public SAMPLE_ELEMENTS KEY_GENERIC_TYPE getSamples(); +#if !TYPE_OBJECT + public COLLECTION KEY_GENERIC_TYPE create(KEY_TYPE...elements); +#endif + public ITERABLE KEY_GENERIC_TYPE order(LIST KEY_GENERIC_TYPE insertionOrder); + + @Override + public default SampleElements samples() {return getSamples().toSamples();} + @Override + public COLLECTION KEY_GENERIC_TYPE create(Object... elements); + @Override + public default CLASS_TYPE[] createArray(int length) { return NEW_CLASS_ARRAY(length); } + @Override + public Iterable order(List insertionOrder); +} diff --git a/src/builder/resources/speiger/assets/testers/templates/generators/TestListGenerator.template b/src/builder/resources/speiger/assets/testers/templates/generators/TestListGenerator.template index 37731ab..9588a6f 100644 --- a/src/builder/resources/speiger/assets/testers/templates/generators/TestListGenerator.template +++ b/src/builder/resources/speiger/assets/testers/templates/generators/TestListGenerator.template @@ -1,16 +1,16 @@ -package speiger.src.testers.PACKAGE.generators; - -import com.google.common.collect.testing.TestListGenerator; - -import speiger.src.collections.PACKAGE.lists.LIST; - -@SuppressWarnings("javadoc") -public interface TEST_LIST_GENERATOR KEY_GENERIC_TYPE extends TestListGenerator, TEST_COLLECTION_GENERATOR KEY_GENERIC_TYPE -{ - @Override - LIST KEY_GENERIC_TYPE create(Object... elements); -#if !TYPE_OBJECT - @Override - LIST KEY_GENERIC_TYPE create(KEY_TYPE... elements); -#endif -} +package speiger.src.testers.PACKAGE.generators; + +import com.google.common.collect.testing.TestListGenerator; + +import speiger.src.collections.PACKAGE.lists.LIST; + +@SuppressWarnings("javadoc") +public interface TEST_LIST_GENERATOR KEY_GENERIC_TYPE extends TestListGenerator, TEST_COLLECTION_GENERATOR KEY_GENERIC_TYPE +{ + @Override + LIST KEY_GENERIC_TYPE create(Object... elements); +#if !TYPE_OBJECT + @Override + LIST KEY_GENERIC_TYPE create(KEY_TYPE... elements); +#endif +} diff --git a/src/builder/resources/speiger/assets/testers/templates/generators/TestNavigableSetGenerator.template b/src/builder/resources/speiger/assets/testers/templates/generators/TestNavigableSetGenerator.template index 26ce02f..c51a7a2 100644 --- a/src/builder/resources/speiger/assets/testers/templates/generators/TestNavigableSetGenerator.template +++ b/src/builder/resources/speiger/assets/testers/templates/generators/TestNavigableSetGenerator.template @@ -1,13 +1,13 @@ -package speiger.src.testers.PACKAGE.generators; - -import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET; - -@SuppressWarnings("javadoc") -public interface TEST_NAVIGABLE_SET_GENERATOR KEY_GENERIC_TYPE extends TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE { -#if !TYPE_OBJECT - @Override - NAVIGABLE_SET KEY_GENERIC_TYPE create(KEY_TYPE... elements); -#endif - @Override - NAVIGABLE_SET KEY_GENERIC_TYPE create(Object... elements); -} +package speiger.src.testers.PACKAGE.generators; + +import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET; + +@SuppressWarnings("javadoc") +public interface TEST_NAVIGABLE_SET_GENERATOR KEY_GENERIC_TYPE extends TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE { +#if !TYPE_OBJECT + @Override + NAVIGABLE_SET KEY_GENERIC_TYPE create(KEY_TYPE... elements); +#endif + @Override + NAVIGABLE_SET KEY_GENERIC_TYPE create(Object... elements); +} diff --git a/src/builder/resources/speiger/assets/testers/templates/generators/TestOrderedSetGenerator.template b/src/builder/resources/speiger/assets/testers/templates/generators/TestOrderedSetGenerator.template index 30a7c0e..235a9d4 100644 --- a/src/builder/resources/speiger/assets/testers/templates/generators/TestOrderedSetGenerator.template +++ b/src/builder/resources/speiger/assets/testers/templates/generators/TestOrderedSetGenerator.template @@ -1,13 +1,13 @@ -package speiger.src.testers.PACKAGE.generators; - -import speiger.src.collections.PACKAGE.sets.ORDERED_SET; - -@SuppressWarnings("javadoc") -public interface TEST_ORDERED_SET_GENERATOR KEY_GENERIC_TYPE extends TEST_SET_GENERATOR KEY_GENERIC_TYPE { -#if !TYPE_OBJECT - @Override - ORDERED_SET KEY_GENERIC_TYPE create(KEY_TYPE... elements); -#endif - @Override - ORDERED_SET KEY_GENERIC_TYPE create(Object... elements); -} +package speiger.src.testers.PACKAGE.generators; + +import speiger.src.collections.PACKAGE.sets.ORDERED_SET; + +@SuppressWarnings("javadoc") +public interface TEST_ORDERED_SET_GENERATOR KEY_GENERIC_TYPE extends TEST_SET_GENERATOR KEY_GENERIC_TYPE { +#if !TYPE_OBJECT + @Override + ORDERED_SET KEY_GENERIC_TYPE create(KEY_TYPE... elements); +#endif + @Override + ORDERED_SET KEY_GENERIC_TYPE create(Object... elements); +} diff --git a/src/builder/resources/speiger/assets/testers/templates/generators/TestQueueGenerator.template b/src/builder/resources/speiger/assets/testers/templates/generators/TestQueueGenerator.template index 5aabec2..d4897a7 100644 --- a/src/builder/resources/speiger/assets/testers/templates/generators/TestQueueGenerator.template +++ b/src/builder/resources/speiger/assets/testers/templates/generators/TestQueueGenerator.template @@ -1,30 +1,30 @@ -package speiger.src.testers.PACKAGE.generators; - -import java.util.List; - -import com.google.common.collect.testing.SampleElements; -import com.google.common.collect.testing.TestContainerGenerator; - -import speiger.src.collections.PACKAGE.queues.PRIORITY_QUEUE; -import speiger.src.collections.PACKAGE.collections.ITERABLE; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.testers.PACKAGE.utils.SAMPLE_ELEMENTS; - -@SuppressWarnings("javadoc") -public interface TEST_QUEUE_GENERATOR KEY_GENERIC_TYPE extends TestContainerGenerator -{ - public SAMPLE_ELEMENTS KEY_GENERIC_TYPE getSamples(); -#if !TYPE_OBJECT - public PRIORITY_QUEUE KEY_GENERIC_TYPE create(KEY_TYPE...elements); -#endif - public ITERABLE KEY_GENERIC_TYPE order(LIST KEY_GENERIC_TYPE insertionOrder); - - @Override - public default SampleElements samples() {return getSamples().toSamples();} - @Override - public PRIORITY_QUEUE KEY_GENERIC_TYPE create(Object... elements); - @Override - public default CLASS_TYPE[] createArray(int length) { return NEW_CLASS_ARRAY(length); } - @Override - public Iterable order(List insertionOrder); -} +package speiger.src.testers.PACKAGE.generators; + +import java.util.List; + +import com.google.common.collect.testing.SampleElements; +import com.google.common.collect.testing.TestContainerGenerator; + +import speiger.src.collections.PACKAGE.queues.PRIORITY_QUEUE; +import speiger.src.collections.PACKAGE.collections.ITERABLE; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.testers.PACKAGE.utils.SAMPLE_ELEMENTS; + +@SuppressWarnings("javadoc") +public interface TEST_QUEUE_GENERATOR KEY_GENERIC_TYPE extends TestContainerGenerator +{ + public SAMPLE_ELEMENTS KEY_GENERIC_TYPE getSamples(); +#if !TYPE_OBJECT + public PRIORITY_QUEUE KEY_GENERIC_TYPE create(KEY_TYPE...elements); +#endif + public ITERABLE KEY_GENERIC_TYPE order(LIST KEY_GENERIC_TYPE insertionOrder); + + @Override + public default SampleElements samples() {return getSamples().toSamples();} + @Override + public PRIORITY_QUEUE KEY_GENERIC_TYPE create(Object... elements); + @Override + public default CLASS_TYPE[] createArray(int length) { return NEW_CLASS_ARRAY(length); } + @Override + public Iterable order(List insertionOrder); +} diff --git a/src/builder/resources/speiger/assets/testers/templates/generators/TestSetGenerator.template b/src/builder/resources/speiger/assets/testers/templates/generators/TestSetGenerator.template index 5b96586..a10d3bb 100644 --- a/src/builder/resources/speiger/assets/testers/templates/generators/TestSetGenerator.template +++ b/src/builder/resources/speiger/assets/testers/templates/generators/TestSetGenerator.template @@ -1,15 +1,15 @@ -package speiger.src.testers.PACKAGE.generators; - -import com.google.common.collect.testing.TestSetGenerator; - -import speiger.src.collections.PACKAGE.sets.SET; - -@SuppressWarnings("javadoc") -public interface TEST_SET_GENERATOR KEY_GENERIC_TYPE extends TEST_COLLECTION_GENERATOR KEY_GENERIC_TYPE, TestSetGenerator { -#if !TYPE_OBJECT - @Override - SET KEY_GENERIC_TYPE create(KEY_TYPE...elements); -#endif - @Override - SET KEY_GENERIC_TYPE create(Object...elements); -} +package speiger.src.testers.PACKAGE.generators; + +import com.google.common.collect.testing.TestSetGenerator; + +import speiger.src.collections.PACKAGE.sets.SET; + +@SuppressWarnings("javadoc") +public interface TEST_SET_GENERATOR KEY_GENERIC_TYPE extends TEST_COLLECTION_GENERATOR KEY_GENERIC_TYPE, TestSetGenerator { +#if !TYPE_OBJECT + @Override + SET KEY_GENERIC_TYPE create(KEY_TYPE...elements); +#endif + @Override + SET KEY_GENERIC_TYPE create(Object...elements); +} diff --git a/src/builder/resources/speiger/assets/testers/templates/generators/TestSortedSetGenerator.template b/src/builder/resources/speiger/assets/testers/templates/generators/TestSortedSetGenerator.template index c380bee..d342514 100644 --- a/src/builder/resources/speiger/assets/testers/templates/generators/TestSortedSetGenerator.template +++ b/src/builder/resources/speiger/assets/testers/templates/generators/TestSortedSetGenerator.template @@ -1,38 +1,38 @@ -package speiger.src.testers.PACKAGE.generators; - -import speiger.src.collections.PACKAGE.sets.SORTED_SET; - -@SuppressWarnings("javadoc") -public interface TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE extends TEST_SET_GENERATOR KEY_GENERIC_TYPE { -#if !TYPE_OBJECT - @Override - SORTED_SET KEY_GENERIC_TYPE create(KEY_TYPE... elements); -#endif - @Override - SORTED_SET KEY_GENERIC_TYPE create(Object... elements); - - - /** - * Returns an element less than the {@link #samples()} and less than {@link - * #belowSamplesGreater()}. - */ - KEY_TYPE belowSamplesLesser(); - - /** - * Returns an element less than the {@link #samples()} but greater than {@link - * #belowSamplesLesser()}. - */ - KEY_TYPE belowSamplesGreater(); - - /** - * Returns an element greater than the {@link #samples()} but less than {@link - * #aboveSamplesGreater()}. - */ - KEY_TYPE aboveSamplesLesser(); - - /** - * Returns an element greater than the {@link #samples()} and greater than {@link - * #aboveSamplesLesser()}. - */ - KEY_TYPE aboveSamplesGreater(); -} +package speiger.src.testers.PACKAGE.generators; + +import speiger.src.collections.PACKAGE.sets.SORTED_SET; + +@SuppressWarnings("javadoc") +public interface TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE extends TEST_SET_GENERATOR KEY_GENERIC_TYPE { +#if !TYPE_OBJECT + @Override + SORTED_SET KEY_GENERIC_TYPE create(KEY_TYPE... elements); +#endif + @Override + SORTED_SET KEY_GENERIC_TYPE create(Object... elements); + + + /** + * Returns an element less than the {@link #samples()} and less than {@link + * #belowSamplesGreater()}. + */ + KEY_TYPE belowSamplesLesser(); + + /** + * Returns an element less than the {@link #samples()} but greater than {@link + * #belowSamplesLesser()}. + */ + KEY_TYPE belowSamplesGreater(); + + /** + * Returns an element greater than the {@link #samples()} but less than {@link + * #aboveSamplesGreater()}. + */ + KEY_TYPE aboveSamplesLesser(); + + /** + * Returns an element greater than the {@link #samples()} and greater than {@link + * #aboveSamplesLesser()}. + */ + KEY_TYPE aboveSamplesGreater(); +} diff --git a/src/builder/resources/speiger/assets/testers/templates/generators/maps/TestMapGenerator.template b/src/builder/resources/speiger/assets/testers/templates/generators/maps/TestMapGenerator.template index 3afe254..e4bab86 100644 --- a/src/builder/resources/speiger/assets/testers/templates/generators/maps/TestMapGenerator.template +++ b/src/builder/resources/speiger/assets/testers/templates/generators/maps/TestMapGenerator.template @@ -1,46 +1,46 @@ -package speiger.src.testers.PACKAGE.generators.maps; - -import java.util.Map; - -import com.google.common.collect.testing.Helpers; -import com.google.common.collect.testing.SampleElements; -import com.google.common.collect.testing.TestMapGenerator; - -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.collections.objects.collections.ObjectIterable; -import speiger.src.collections.objects.lists.ObjectList; -import speiger.src.testers.objects.utils.ObjectSamples; - -@SuppressWarnings("javadoc") -public interface TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE extends TestMapGenerator { - public ObjectSamples getSamples(); - public ObjectIterable order(ObjectList insertionOrder); - public MAP KEY_VALUE_GENERIC_TYPE create(MAP.Entry KEY_VALUE_GENERIC_TYPE... elements); - @Override - default MAP KEY_VALUE_GENERIC_TYPE create(Object... elements) { - MAP.Entry KEY_VALUE_GENERIC_TYPE[] result = new MAP.Entry[elements.length]; - for(int i = 0;i> samples() { - ObjectSamples samples = getSamples(); - return new SampleElements<>( - Helpers.mapEntry(samples.e0().ENTRY_KEY(), samples.e0().ENTRY_VALUE()), - Helpers.mapEntry(samples.e1().ENTRY_KEY(), samples.e1().ENTRY_VALUE()), - Helpers.mapEntry(samples.e2().ENTRY_KEY(), samples.e2().ENTRY_VALUE()), - Helpers.mapEntry(samples.e3().ENTRY_KEY(), samples.e3().ENTRY_VALUE()), - Helpers.mapEntry(samples.e4().ENTRY_KEY(), samples.e4().ENTRY_VALUE()) - ); - } -} +package speiger.src.testers.PACKAGE.generators.maps; + +import java.util.Map; + +import com.google.common.collect.testing.Helpers; +import com.google.common.collect.testing.SampleElements; +import com.google.common.collect.testing.TestMapGenerator; + +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.collections.objects.collections.ObjectIterable; +import speiger.src.collections.objects.lists.ObjectList; +import speiger.src.testers.objects.utils.ObjectSamples; + +@SuppressWarnings("javadoc") +public interface TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE extends TestMapGenerator { + public ObjectSamples getSamples(); + public ObjectIterable order(ObjectList insertionOrder); + public MAP KEY_VALUE_GENERIC_TYPE create(MAP.Entry KEY_VALUE_GENERIC_TYPE... elements); + @Override + default MAP KEY_VALUE_GENERIC_TYPE create(Object... elements) { + MAP.Entry KEY_VALUE_GENERIC_TYPE[] result = new MAP.Entry[elements.length]; + for(int i = 0;i> samples() { + ObjectSamples samples = getSamples(); + return new SampleElements<>( + Helpers.mapEntry(samples.e0().ENTRY_KEY(), samples.e0().ENTRY_VALUE()), + Helpers.mapEntry(samples.e1().ENTRY_KEY(), samples.e1().ENTRY_VALUE()), + Helpers.mapEntry(samples.e2().ENTRY_KEY(), samples.e2().ENTRY_VALUE()), + Helpers.mapEntry(samples.e3().ENTRY_KEY(), samples.e3().ENTRY_VALUE()), + Helpers.mapEntry(samples.e4().ENTRY_KEY(), samples.e4().ENTRY_VALUE()) + ); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/generators/maps/TestOrderedMapGenerator.template b/src/builder/resources/speiger/assets/testers/templates/generators/maps/TestOrderedMapGenerator.template index 629517f..38c103a 100644 --- a/src/builder/resources/speiger/assets/testers/templates/generators/maps/TestOrderedMapGenerator.template +++ b/src/builder/resources/speiger/assets/testers/templates/generators/maps/TestOrderedMapGenerator.template @@ -1,13 +1,13 @@ -package speiger.src.testers.PACKAGE.generators.maps; - -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP; - -@SuppressWarnings("javadoc") -public interface TEST_ORDERED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE extends TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE -{ - @Override - default ORDERED_MAP KEY_VALUE_GENERIC_TYPE create(Object... elements) { return (ORDERED_MAP KEY_VALUE_GENERIC_TYPE) TEST_MAP_GENERATOR.super.create(elements); } - @Override - ORDERED_MAP KEY_VALUE_GENERIC_TYPE create(MAP.Entry KEY_VALUE_GENERIC_TYPE... elements); -} +package speiger.src.testers.PACKAGE.generators.maps; + +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP; + +@SuppressWarnings("javadoc") +public interface TEST_ORDERED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE extends TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE +{ + @Override + default ORDERED_MAP KEY_VALUE_GENERIC_TYPE create(Object... elements) { return (ORDERED_MAP KEY_VALUE_GENERIC_TYPE) TEST_MAP_GENERATOR.super.create(elements); } + @Override + ORDERED_MAP KEY_VALUE_GENERIC_TYPE create(MAP.Entry KEY_VALUE_GENERIC_TYPE... elements); +} diff --git a/src/builder/resources/speiger/assets/testers/templates/generators/maps/TestSortedMapGenerator.template b/src/builder/resources/speiger/assets/testers/templates/generators/maps/TestSortedMapGenerator.template index a757e24..74ef8ec 100644 --- a/src/builder/resources/speiger/assets/testers/templates/generators/maps/TestSortedMapGenerator.template +++ b/src/builder/resources/speiger/assets/testers/templates/generators/maps/TestSortedMapGenerator.template @@ -1,25 +1,25 @@ -package speiger.src.testers.PACKAGE.generators.maps; - -import com.google.common.collect.testing.TestSortedMapGenerator; - -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.MAP.Entry; -import speiger.src.collections.PACKAGE.maps.interfaces.SORTED_MAP; - -@SuppressWarnings("javadoc") -public interface TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE extends TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE, TestSortedMapGenerator -{ - @Override - default SORTED_MAP KEY_VALUE_GENERIC_TYPE create(Object... elements) { return (SORTED_MAP KEY_VALUE_GENERIC_TYPE) TEST_MAP_GENERATOR.super.create(elements); } - @Override - SORTED_MAP KEY_VALUE_GENERIC_TYPE create(MAP.Entry KEY_VALUE_GENERIC_TYPE... elements); - - @Override - Entry KEY_VALUE_GENERIC_TYPE belowSamplesLesser(); - @Override - Entry KEY_VALUE_GENERIC_TYPE belowSamplesGreater(); - @Override - Entry KEY_VALUE_GENERIC_TYPE aboveSamplesLesser(); - @Override - Entry KEY_VALUE_GENERIC_TYPE aboveSamplesGreater(); -} +package speiger.src.testers.PACKAGE.generators.maps; + +import com.google.common.collect.testing.TestSortedMapGenerator; + +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.MAP.Entry; +import speiger.src.collections.PACKAGE.maps.interfaces.SORTED_MAP; + +@SuppressWarnings("javadoc") +public interface TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE extends TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE, TestSortedMapGenerator +{ + @Override + default SORTED_MAP KEY_VALUE_GENERIC_TYPE create(Object... elements) { return (SORTED_MAP KEY_VALUE_GENERIC_TYPE) TEST_MAP_GENERATOR.super.create(elements); } + @Override + SORTED_MAP KEY_VALUE_GENERIC_TYPE create(MAP.Entry KEY_VALUE_GENERIC_TYPE... elements); + + @Override + Entry KEY_VALUE_GENERIC_TYPE belowSamplesLesser(); + @Override + Entry KEY_VALUE_GENERIC_TYPE belowSamplesGreater(); + @Override + Entry KEY_VALUE_GENERIC_TYPE aboveSamplesLesser(); + @Override + Entry KEY_VALUE_GENERIC_TYPE aboveSamplesGreater(); +} diff --git a/src/builder/resources/speiger/assets/testers/templates/impl/CollectionConstructorTests.template b/src/builder/resources/speiger/assets/testers/templates/impl/CollectionConstructorTests.template index 8cd24c7..6c87a43 100644 --- a/src/builder/resources/speiger/assets/testers/templates/impl/CollectionConstructorTests.template +++ b/src/builder/resources/speiger/assets/testers/templates/impl/CollectionConstructorTests.template @@ -1,314 +1,314 @@ -package speiger.src.testers.PACKAGE.impl; - -#if TYPE_OBJECT -import java.util.Arrays; -import java.util.Comparator; -import java.util.Objects; -#endif - -import org.junit.Ignore; - -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.lists.LINKED_LIST; -import speiger.src.collections.PACKAGE.lists.COPY_ON_WRITE_LIST; -import speiger.src.collections.PACKAGE.lists.IMMUTABLE_LIST; -#if !TYPE_BOOLEAN -import speiger.src.collections.PACKAGE.sets.AVL_TREE_SET; -import speiger.src.collections.PACKAGE.sets.ARRAY_SET; -import speiger.src.collections.PACKAGE.sets.LINKED_CUSTOM_HASH_SET; -import speiger.src.collections.PACKAGE.sets.LINKED_HASH_SET; -import speiger.src.collections.PACKAGE.sets.CUSTOM_HASH_SET; -import speiger.src.collections.PACKAGE.sets.HASH_SET; -import speiger.src.collections.PACKAGE.sets.RB_TREE_SET; -import speiger.src.collections.PACKAGE.sets.IMMUTABLE_HASH_SET; -import speiger.src.collections.PACKAGE.utils.STRATEGY; -#endif -#if TYPE_OBJECT -import speiger.src.collections.objects.utils.StringSortTest; -#endif -import speiger.src.testers.PACKAGE.tests.collection.FILE_KEY_TYPECollectionConstructorTester; - -@Ignore -@SuppressWarnings("javadoc") -public class COLLECTION_CONSTRUCTOR_TESTS -{ - public static class ArrayList extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE - { - @SuppressWarnings("deprecation") - public ArrayList() { - setSimpleConstructor(ARRAY_LIST::new); - setSizeConstructor(T -> new ARRAY_LISTBRACES(T)); - setPArrayConstructor(T -> new ARRAY_LISTBRACES(T)); - setPCollectionConstructor(T -> new ARRAY_LISTBRACES(T)); - setCollectionConstructor(T -> new ARRAY_LISTBRACES(T)); - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } -#endif - } - - public static class LinkedList extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE - { - @SuppressWarnings("deprecation") - public LinkedList() { - setSimpleConstructor(LINKED_LIST::new); - setPArrayConstructor(T -> new LINKED_LISTBRACES(T)); - setPCollectionConstructor(T -> new LINKED_LISTBRACES(T)); - setCollectionConstructor(T -> new LINKED_LISTBRACES(T)); - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } -#endif - } - - public static class CopyOnWriteArrayList extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE - { - @SuppressWarnings("deprecation") - public CopyOnWriteArrayList() { - setSimpleConstructor(COPY_ON_WRITE_LIST::new); - setPArrayConstructor(T -> new COPY_ON_WRITE_LISTBRACES(T)); - setPCollectionConstructor(T -> new COPY_ON_WRITE_LISTBRACES(T)); - setCollectionConstructor(T -> new COPY_ON_WRITE_LISTBRACES(T)); - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } -#endif - } - - public static class ImmutableList extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE - { - @SuppressWarnings("deprecation") - public ImmutableList() { - setPArrayConstructor(T -> new IMMUTABLE_LISTBRACES(T)); - setPCollectionConstructor(T -> new IMMUTABLE_LISTBRACES(T)); - setCollectionConstructor(T -> new IMMUTABLE_LISTBRACES(T)); - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } -#endif - } - -#if !TYPE_BOOLEAN - public static class HashSet extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE - { - @SuppressWarnings("deprecation") - public HashSet() { - setSimpleConstructor(HASH_SET::new); - setSizeConstructor(T -> new HASH_SETBRACES(T)); - setPArrayConstructor(T -> new HASH_SETBRACES(T)); - setPCollectionConstructor(T -> new HASH_SETBRACES(T)); - setCollectionConstructor(T -> new HASH_SETBRACES(T)); - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } -#endif - } - - public static class LinkedHashSet extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE - { - @SuppressWarnings("deprecation") - public LinkedHashSet() { - setSimpleConstructor(LINKED_HASH_SET::new); - setSizeConstructor(T -> new LINKED_HASH_SETBRACES(T)); - setPArrayConstructor(T -> new LINKED_HASH_SETBRACES(T)); - setPCollectionConstructor(T -> new LINKED_HASH_SETBRACES(T)); - setCollectionConstructor(T -> new LINKED_HASH_SETBRACES(T)); - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } -#endif - } - - public static class CustomHashSet extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE - { - @SuppressWarnings("deprecation") - public CustomHashSet() { - setSimpleConstructor(() -> new CUSTOM_HASH_SET KEY_STRING_GENERIC_TYPE(HashStrategy.INSTANCE)); - setSizeConstructor(T -> new CUSTOM_HASH_SET KEY_STRING_GENERIC_TYPE(T, HashStrategy.INSTANCE)); - setPArrayConstructor(T -> new CUSTOM_HASH_SET KEY_STRING_GENERIC_TYPE(T, HashStrategy.INSTANCE)); - setPCollectionConstructor(T -> new CUSTOM_HASH_SET KEY_STRING_GENERIC_TYPE(T, HashStrategy.INSTANCE)); - setCollectionConstructor(T -> new CUSTOM_HASH_SET KEY_STRING_GENERIC_TYPE(T, HashStrategy.INSTANCE)); - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } -#endif - } - - public static class LinkedCustomHashSet extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE - { - @SuppressWarnings("deprecation") - public LinkedCustomHashSet() { - setSimpleConstructor(() -> new LINKED_CUSTOM_HASH_SET KEY_STRING_GENERIC_TYPE(HashStrategy.INSTANCE)); - setSizeConstructor(T -> new LINKED_CUSTOM_HASH_SET KEY_STRING_GENERIC_TYPE(T, HashStrategy.INSTANCE)); - setPArrayConstructor(T -> new LINKED_CUSTOM_HASH_SET KEY_STRING_GENERIC_TYPE(T, HashStrategy.INSTANCE)); - setPCollectionConstructor(T -> new LINKED_CUSTOM_HASH_SET KEY_STRING_GENERIC_TYPE(T, HashStrategy.INSTANCE)); - setCollectionConstructor(T -> new LINKED_CUSTOM_HASH_SET KEY_STRING_GENERIC_TYPE(T, HashStrategy.INSTANCE)); - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } -#endif - } - - public static class ImmutableHashSet extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE - { - @SuppressWarnings("deprecation") - public ImmutableHashSet() { - setPArrayConstructor(T -> new IMMUTABLE_HASH_SETBRACES(T)); - setPCollectionConstructor(T -> new IMMUTABLE_HASH_SETBRACES(T)); - setCollectionConstructor(T -> new IMMUTABLE_HASH_SETBRACES(T)); - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } -#endif - } - - public static class ArraySet extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE - { - @SuppressWarnings("deprecation") - public ArraySet() { - setSimpleConstructor(ARRAY_SET::new); - setSizeConstructor(T -> new ARRAY_SETBRACES(T)); - setPArrayConstructor(T -> new ARRAY_SETBRACES(T)); - setPCollectionConstructor(T -> new ARRAY_SETBRACES(T)); - setCollectionConstructor(T -> new ARRAY_SETBRACES(T)); - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } -#endif - } - - public static class RBTreeSet extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE - { - @SuppressWarnings("deprecation") - public RBTreeSet() { - setSimpleConstructor(RB_TREE_SET::new); - setPArrayConstructor(T -> new RB_TREE_SETBRACES(T)); - setPCollectionConstructor(T -> new RB_TREE_SETBRACES(T)); - setCollectionConstructor(T -> new RB_TREE_SETBRACES(T)); - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } -#endif - } - - public static class AVLTreeSet extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE - { - @SuppressWarnings("deprecation") - public AVLTreeSet() { - setSimpleConstructor(AVL_TREE_SET::new); - setPArrayConstructor(T -> new AVL_TREE_SETBRACES(T)); - setPCollectionConstructor(T -> new AVL_TREE_SETBRACES(T)); - setCollectionConstructor(T -> new AVL_TREE_SETBRACES(T)); - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } -#endif - } - - public static class RBTreeSetComparator extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE - { - @SuppressWarnings("deprecation") - public RBTreeSetComparator() { -#if TYPE_OBJECT - setSimpleConstructor(() -> new RB_TREE_SET(Comparator.naturalOrder())); - setPArrayConstructor(T -> new RB_TREE_SET<>(T, Comparator.naturalOrder())); - setPCollectionConstructor(T -> new RB_TREE_SET<>(T, Comparator.naturalOrder())); - setCollectionConstructor(T -> new RB_TREE_SET<>(T, Comparator.naturalOrder())); -#else - setSimpleConstructor(() -> new RB_TREE_SET(CLASS_TYPE::compare)); - setPArrayConstructor(T -> new RB_TREE_SET(T, CLASS_TYPE::compare)); - setPCollectionConstructor(T -> new RB_TREE_SET(T, CLASS_TYPE::compare)); - setCollectionConstructor(T -> new RB_TREE_SET(T, CLASS_TYPE::compare)); -#endif - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } -#endif - } - - public static class AVLTreeSetComparator extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE - { - @SuppressWarnings("deprecation") - public AVLTreeSetComparator() { -#if TYPE_OBJECT - setSimpleConstructor(() -> new AVL_TREE_SET(Comparator.naturalOrder())); - setPArrayConstructor(T -> new AVL_TREE_SET<>(T, Comparator.naturalOrder())); - setPCollectionConstructor(T -> new AVL_TREE_SET<>(T, Comparator.naturalOrder())); - setCollectionConstructor(T -> new AVL_TREE_SET<>(T, Comparator.naturalOrder())); -#else - setSimpleConstructor(() -> new AVL_TREE_SET(CLASS_TYPE::compare)); - setPArrayConstructor(T -> new AVL_TREE_SET(T, CLASS_TYPE::compare)); - setPCollectionConstructor(T -> new AVL_TREE_SET(T, CLASS_TYPE::compare)); - setCollectionConstructor(T -> new AVL_TREE_SET(T, CLASS_TYPE::compare)); -#endif - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } -#endif - } - - private static class HashStrategy implements STRATEGY KEY_STRING_GENERIC_TYPE { - static final HashStrategy INSTANCE = new HashStrategy(); - @Override - public int hashCode(KEY_STRING_TYPE o) { return KEY_TO_HASH(o); } - @Override - public boolean equals(KEY_STRING_TYPE key, KEY_STRING_TYPE value) { return KEY_EQUALS(key, value); } - } -#endif +package speiger.src.testers.PACKAGE.impl; + +#if TYPE_OBJECT +import java.util.Arrays; +import java.util.Comparator; +import java.util.Objects; +#endif + +import org.junit.Ignore; + +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.lists.LINKED_LIST; +import speiger.src.collections.PACKAGE.lists.COPY_ON_WRITE_LIST; +import speiger.src.collections.PACKAGE.lists.IMMUTABLE_LIST; +#if !TYPE_BOOLEAN +import speiger.src.collections.PACKAGE.sets.AVL_TREE_SET; +import speiger.src.collections.PACKAGE.sets.ARRAY_SET; +import speiger.src.collections.PACKAGE.sets.LINKED_CUSTOM_HASH_SET; +import speiger.src.collections.PACKAGE.sets.LINKED_HASH_SET; +import speiger.src.collections.PACKAGE.sets.CUSTOM_HASH_SET; +import speiger.src.collections.PACKAGE.sets.HASH_SET; +import speiger.src.collections.PACKAGE.sets.RB_TREE_SET; +import speiger.src.collections.PACKAGE.sets.IMMUTABLE_HASH_SET; +import speiger.src.collections.PACKAGE.utils.STRATEGY; +#endif +#if TYPE_OBJECT +import speiger.src.collections.objects.utils.StringSortTest; +#endif +import speiger.src.testers.PACKAGE.tests.collection.FILE_KEY_TYPECollectionConstructorTester; + +@Ignore +@SuppressWarnings("javadoc") +public class COLLECTION_CONSTRUCTOR_TESTS +{ + public static class ArrayList extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE + { + @SuppressWarnings("deprecation") + public ArrayList() { + setSimpleConstructor(ARRAY_LIST::new); + setSizeConstructor(T -> new ARRAY_LISTBRACES(T)); + setPArrayConstructor(T -> new ARRAY_LISTBRACES(T)); + setPCollectionConstructor(T -> new ARRAY_LISTBRACES(T)); + setCollectionConstructor(T -> new ARRAY_LISTBRACES(T)); + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } +#endif + } + + public static class LinkedList extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE + { + @SuppressWarnings("deprecation") + public LinkedList() { + setSimpleConstructor(LINKED_LIST::new); + setPArrayConstructor(T -> new LINKED_LISTBRACES(T)); + setPCollectionConstructor(T -> new LINKED_LISTBRACES(T)); + setCollectionConstructor(T -> new LINKED_LISTBRACES(T)); + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } +#endif + } + + public static class CopyOnWriteArrayList extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE + { + @SuppressWarnings("deprecation") + public CopyOnWriteArrayList() { + setSimpleConstructor(COPY_ON_WRITE_LIST::new); + setPArrayConstructor(T -> new COPY_ON_WRITE_LISTBRACES(T)); + setPCollectionConstructor(T -> new COPY_ON_WRITE_LISTBRACES(T)); + setCollectionConstructor(T -> new COPY_ON_WRITE_LISTBRACES(T)); + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } +#endif + } + + public static class ImmutableList extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE + { + @SuppressWarnings("deprecation") + public ImmutableList() { + setPArrayConstructor(T -> new IMMUTABLE_LISTBRACES(T)); + setPCollectionConstructor(T -> new IMMUTABLE_LISTBRACES(T)); + setCollectionConstructor(T -> new IMMUTABLE_LISTBRACES(T)); + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } +#endif + } + +#if !TYPE_BOOLEAN + public static class HashSet extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE + { + @SuppressWarnings("deprecation") + public HashSet() { + setSimpleConstructor(HASH_SET::new); + setSizeConstructor(T -> new HASH_SETBRACES(T)); + setPArrayConstructor(T -> new HASH_SETBRACES(T)); + setPCollectionConstructor(T -> new HASH_SETBRACES(T)); + setCollectionConstructor(T -> new HASH_SETBRACES(T)); + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } +#endif + } + + public static class LinkedHashSet extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE + { + @SuppressWarnings("deprecation") + public LinkedHashSet() { + setSimpleConstructor(LINKED_HASH_SET::new); + setSizeConstructor(T -> new LINKED_HASH_SETBRACES(T)); + setPArrayConstructor(T -> new LINKED_HASH_SETBRACES(T)); + setPCollectionConstructor(T -> new LINKED_HASH_SETBRACES(T)); + setCollectionConstructor(T -> new LINKED_HASH_SETBRACES(T)); + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } +#endif + } + + public static class CustomHashSet extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE + { + @SuppressWarnings("deprecation") + public CustomHashSet() { + setSimpleConstructor(() -> new CUSTOM_HASH_SET KEY_STRING_GENERIC_TYPE(HashStrategy.INSTANCE)); + setSizeConstructor(T -> new CUSTOM_HASH_SET KEY_STRING_GENERIC_TYPE(T, HashStrategy.INSTANCE)); + setPArrayConstructor(T -> new CUSTOM_HASH_SET KEY_STRING_GENERIC_TYPE(T, HashStrategy.INSTANCE)); + setPCollectionConstructor(T -> new CUSTOM_HASH_SET KEY_STRING_GENERIC_TYPE(T, HashStrategy.INSTANCE)); + setCollectionConstructor(T -> new CUSTOM_HASH_SET KEY_STRING_GENERIC_TYPE(T, HashStrategy.INSTANCE)); + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } +#endif + } + + public static class LinkedCustomHashSet extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE + { + @SuppressWarnings("deprecation") + public LinkedCustomHashSet() { + setSimpleConstructor(() -> new LINKED_CUSTOM_HASH_SET KEY_STRING_GENERIC_TYPE(HashStrategy.INSTANCE)); + setSizeConstructor(T -> new LINKED_CUSTOM_HASH_SET KEY_STRING_GENERIC_TYPE(T, HashStrategy.INSTANCE)); + setPArrayConstructor(T -> new LINKED_CUSTOM_HASH_SET KEY_STRING_GENERIC_TYPE(T, HashStrategy.INSTANCE)); + setPCollectionConstructor(T -> new LINKED_CUSTOM_HASH_SET KEY_STRING_GENERIC_TYPE(T, HashStrategy.INSTANCE)); + setCollectionConstructor(T -> new LINKED_CUSTOM_HASH_SET KEY_STRING_GENERIC_TYPE(T, HashStrategy.INSTANCE)); + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } +#endif + } + + public static class ImmutableHashSet extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE + { + @SuppressWarnings("deprecation") + public ImmutableHashSet() { + setPArrayConstructor(T -> new IMMUTABLE_HASH_SETBRACES(T)); + setPCollectionConstructor(T -> new IMMUTABLE_HASH_SETBRACES(T)); + setCollectionConstructor(T -> new IMMUTABLE_HASH_SETBRACES(T)); + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } +#endif + } + + public static class ArraySet extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE + { + @SuppressWarnings("deprecation") + public ArraySet() { + setSimpleConstructor(ARRAY_SET::new); + setSizeConstructor(T -> new ARRAY_SETBRACES(T)); + setPArrayConstructor(T -> new ARRAY_SETBRACES(T)); + setPCollectionConstructor(T -> new ARRAY_SETBRACES(T)); + setCollectionConstructor(T -> new ARRAY_SETBRACES(T)); + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } +#endif + } + + public static class RBTreeSet extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE + { + @SuppressWarnings("deprecation") + public RBTreeSet() { + setSimpleConstructor(RB_TREE_SET::new); + setPArrayConstructor(T -> new RB_TREE_SETBRACES(T)); + setPCollectionConstructor(T -> new RB_TREE_SETBRACES(T)); + setCollectionConstructor(T -> new RB_TREE_SETBRACES(T)); + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } +#endif + } + + public static class AVLTreeSet extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE + { + @SuppressWarnings("deprecation") + public AVLTreeSet() { + setSimpleConstructor(AVL_TREE_SET::new); + setPArrayConstructor(T -> new AVL_TREE_SETBRACES(T)); + setPCollectionConstructor(T -> new AVL_TREE_SETBRACES(T)); + setCollectionConstructor(T -> new AVL_TREE_SETBRACES(T)); + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } +#endif + } + + public static class RBTreeSetComparator extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE + { + @SuppressWarnings("deprecation") + public RBTreeSetComparator() { +#if TYPE_OBJECT + setSimpleConstructor(() -> new RB_TREE_SET(Comparator.naturalOrder())); + setPArrayConstructor(T -> new RB_TREE_SET<>(T, Comparator.naturalOrder())); + setPCollectionConstructor(T -> new RB_TREE_SET<>(T, Comparator.naturalOrder())); + setCollectionConstructor(T -> new RB_TREE_SET<>(T, Comparator.naturalOrder())); +#else + setSimpleConstructor(() -> new RB_TREE_SET(CLASS_TYPE::compare)); + setPArrayConstructor(T -> new RB_TREE_SET(T, CLASS_TYPE::compare)); + setPCollectionConstructor(T -> new RB_TREE_SET(T, CLASS_TYPE::compare)); + setCollectionConstructor(T -> new RB_TREE_SET(T, CLASS_TYPE::compare)); +#endif + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } +#endif + } + + public static class AVLTreeSetComparator extends FILE_KEY_TYPECollectionConstructorTester KEY_STRING_GENERIC_TYPE + { + @SuppressWarnings("deprecation") + public AVLTreeSetComparator() { +#if TYPE_OBJECT + setSimpleConstructor(() -> new AVL_TREE_SET(Comparator.naturalOrder())); + setPArrayConstructor(T -> new AVL_TREE_SET<>(T, Comparator.naturalOrder())); + setPCollectionConstructor(T -> new AVL_TREE_SET<>(T, Comparator.naturalOrder())); + setCollectionConstructor(T -> new AVL_TREE_SET<>(T, Comparator.naturalOrder())); +#else + setSimpleConstructor(() -> new AVL_TREE_SET(CLASS_TYPE::compare)); + setPArrayConstructor(T -> new AVL_TREE_SET(T, CLASS_TYPE::compare)); + setPCollectionConstructor(T -> new AVL_TREE_SET(T, CLASS_TYPE::compare)); + setCollectionConstructor(T -> new AVL_TREE_SET(T, CLASS_TYPE::compare)); +#endif + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } +#endif + } + + private static class HashStrategy implements STRATEGY KEY_STRING_GENERIC_TYPE { + static final HashStrategy INSTANCE = new HashStrategy(); + @Override + public int hashCode(KEY_STRING_TYPE o) { return KEY_TO_HASH(o); } + @Override + public boolean equals(KEY_STRING_TYPE key, KEY_STRING_TYPE value) { return KEY_EQUALS(key, value); } + } +#endif } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/impl/SimpleQueueTestGenerator.template b/src/builder/resources/speiger/assets/testers/templates/impl/SimpleQueueTestGenerator.template index eb3abd2..cf282a8 100644 --- a/src/builder/resources/speiger/assets/testers/templates/impl/SimpleQueueTestGenerator.template +++ b/src/builder/resources/speiger/assets/testers/templates/impl/SimpleQueueTestGenerator.template @@ -1,82 +1,82 @@ -package speiger.src.testers.PACKAGE.impl; - -import java.util.List; -import java.util.function.Function; - -import speiger.src.collections.PACKAGE.collections.ITERABLE; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.collections.PACKAGE.queues.PRIORITY_QUEUE; -#if TYPE_OBJECT -import speiger.src.collections.objects.utils.ObjectArrays; -#endif -import speiger.src.testers.PACKAGE.generators.TEST_QUEUE_GENERATOR; -import speiger.src.testers.PACKAGE.utils.SAMPLE_ELEMENTS; - -@SuppressWarnings("javadoc") -public class SIMPLE_QUEUE_TEST_GENERATOR KEY_GENERIC_TYPE implements TEST_QUEUE_GENERATOR KEY_GENERIC_TYPE -{ - Function mapper; -#if TYPE_OBJECT - KEY_TYPE[] keys; -#endif - - public SIMPLE_QUEUE_TEST_GENERATOR(Function mapper) { - this.mapper = mapper; - } - -#if TYPE_OBJECT - public SIMPLE_QUEUE_TEST_GENERATOR KEY_GENERIC_TYPE setElements(KEY_TYPE...keys) { - this.keys = keys; - return this; - } - -#endif - public SAMPLE_ELEMENTS KEY_GENERIC_TYPE getSamples() { -#if TYPE_BOOLEAN - return new SAMPLE_ELEMENTS(true, false, true, false, true); -#else if TYPE_BYTE - return new SAMPLE_ELEMENTS((byte)0, (byte)1, (byte)2, (byte)3, (byte)4); -#else if TYPE_SHORT - return new SAMPLE_ELEMENTS((short)0, (short)1, (short)2, (short)3, (short)4); -#else if TYPE_CHAR - return new SAMPLE_ELEMENTS((char)0, (char)1, (char)2, (char)3, (char)4); -#else if TYPE_OBJECT - return new SAMPLE_ELEMENTSBRACES(keys[0], keys[1], keys[2], keys[3], keys[4]); -#else - return new SAMPLE_ELEMENTS(0, 1, 2, 3, 4); -#endif - } - -#if !TYPE_OBJECT - public PRIORITY_QUEUE KEY_GENERIC_TYPE create(KEY_TYPE... elements) { - return mapper.apply(elements); - } - - public PRIORITY_QUEUE KEY_GENERIC_TYPE create(Object... elements) { - KEY_TYPE[] array = NEW_KEY_ARRAY(elements.length); - int i = 0; - for (Object e : elements) { - array[i++] = CLASS_TO_KEY(e); - } - return mapper.apply(array); - } - -#else - public PRIORITY_QUEUE KEY_GENERIC_TYPE create(Object... elements) { - T[] array = (T[])ObjectArrays.newArray(keys[0].getClass(), elements.length); - int i = 0; - for (Object e : elements) { - array[i++] = CLASS_TO_KEY(e); - } - return mapper.apply(array); - } - -#endif - public ITERABLE KEY_GENERIC_TYPE order(LIST KEY_GENERIC_TYPE insertionOrder) { - return insertionOrder; - } - - public Iterable order(List insertionOrder) { - return insertionOrder; - } +package speiger.src.testers.PACKAGE.impl; + +import java.util.List; +import java.util.function.Function; + +import speiger.src.collections.PACKAGE.collections.ITERABLE; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.collections.PACKAGE.queues.PRIORITY_QUEUE; +#if TYPE_OBJECT +import speiger.src.collections.objects.utils.ObjectArrays; +#endif +import speiger.src.testers.PACKAGE.generators.TEST_QUEUE_GENERATOR; +import speiger.src.testers.PACKAGE.utils.SAMPLE_ELEMENTS; + +@SuppressWarnings("javadoc") +public class SIMPLE_QUEUE_TEST_GENERATOR KEY_GENERIC_TYPE implements TEST_QUEUE_GENERATOR KEY_GENERIC_TYPE +{ + Function mapper; +#if TYPE_OBJECT + KEY_TYPE[] keys; +#endif + + public SIMPLE_QUEUE_TEST_GENERATOR(Function mapper) { + this.mapper = mapper; + } + +#if TYPE_OBJECT + public SIMPLE_QUEUE_TEST_GENERATOR KEY_GENERIC_TYPE setElements(KEY_TYPE...keys) { + this.keys = keys; + return this; + } + +#endif + public SAMPLE_ELEMENTS KEY_GENERIC_TYPE getSamples() { +#if TYPE_BOOLEAN + return new SAMPLE_ELEMENTS(true, false, true, false, true); +#else if TYPE_BYTE + return new SAMPLE_ELEMENTS((byte)0, (byte)1, (byte)2, (byte)3, (byte)4); +#else if TYPE_SHORT + return new SAMPLE_ELEMENTS((short)0, (short)1, (short)2, (short)3, (short)4); +#else if TYPE_CHAR + return new SAMPLE_ELEMENTS((char)0, (char)1, (char)2, (char)3, (char)4); +#else if TYPE_OBJECT + return new SAMPLE_ELEMENTSBRACES(keys[0], keys[1], keys[2], keys[3], keys[4]); +#else + return new SAMPLE_ELEMENTS(0, 1, 2, 3, 4); +#endif + } + +#if !TYPE_OBJECT + public PRIORITY_QUEUE KEY_GENERIC_TYPE create(KEY_TYPE... elements) { + return mapper.apply(elements); + } + + public PRIORITY_QUEUE KEY_GENERIC_TYPE create(Object... elements) { + KEY_TYPE[] array = NEW_KEY_ARRAY(elements.length); + int i = 0; + for (Object e : elements) { + array[i++] = CLASS_TO_KEY(e); + } + return mapper.apply(array); + } + +#else + public PRIORITY_QUEUE KEY_GENERIC_TYPE create(Object... elements) { + T[] array = (T[])ObjectArrays.newArray(keys[0].getClass(), elements.length); + int i = 0; + for (Object e : elements) { + array[i++] = CLASS_TO_KEY(e); + } + return mapper.apply(array); + } + +#endif + public ITERABLE KEY_GENERIC_TYPE order(LIST KEY_GENERIC_TYPE insertionOrder) { + return insertionOrder; + } + + public Iterable order(List insertionOrder) { + return insertionOrder; + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/impl/SimpleTestGenerator.template b/src/builder/resources/speiger/assets/testers/templates/impl/SimpleTestGenerator.template index 92c2c39..22356cd 100644 --- a/src/builder/resources/speiger/assets/testers/templates/impl/SimpleTestGenerator.template +++ b/src/builder/resources/speiger/assets/testers/templates/impl/SimpleTestGenerator.template @@ -1,221 +1,221 @@ -package speiger.src.testers.PACKAGE.impl; - -import java.util.List; -import java.util.function.Function; - -import speiger.src.collections.PACKAGE.collections.COLLECTION; -import speiger.src.collections.PACKAGE.collections.ITERABLE; -import speiger.src.collections.PACKAGE.lists.LIST; -#if !TYPE_BOOLEAN -import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET; -import speiger.src.collections.PACKAGE.sets.ORDERED_SET; -import speiger.src.collections.PACKAGE.sets.SET; -import speiger.src.collections.PACKAGE.sets.SORTED_SET; -#if TYPE_OBJECT -import speiger.src.collections.objects.utils.ObjectArrays; -#endif -#endif -import speiger.src.testers.PACKAGE.generators.TEST_COLLECTION_GENERATOR; -import speiger.src.testers.PACKAGE.generators.TEST_LIST_GENERATOR; -#if !TYPE_BOOLEAN -import speiger.src.testers.PACKAGE.generators.TEST_NAVIGABLE_SET_GENERATOR; -import speiger.src.testers.PACKAGE.generators.TEST_ORDERED_SET_GENERATOR; -import speiger.src.testers.PACKAGE.generators.TEST_SET_GENERATOR; -import speiger.src.testers.PACKAGE.generators.TEST_SORTED_SET_GENERATOR; -#endif -import speiger.src.testers.PACKAGE.utils.SAMPLE_ELEMENTS; - -@SuppressWarnings("javadoc") -public class SIMPLE_TEST_GENERATOR KKS_GENERIC_TYPE { - Function mapper; -#if TYPE_OBJECT - KEY_TYPE[] keys; -#endif - - public SIMPLE_TEST_GENERATOR(Function mapper) { - this.mapper = mapper; - } - -#if TYPE_OBJECT - public SIMPLE_TEST_GENERATOR KKS_GENERIC_TYPE setElements(KEY_TYPE...keys) { - this.keys = keys; - return this; - } - -#endif - public SAMPLE_ELEMENTS KEY_GENERIC_TYPE getSamples() { -#if TYPE_BOOLEAN - return new SAMPLE_ELEMENTS(true, false, true, false, true); -#else if TYPE_BYTE - return new SAMPLE_ELEMENTS((byte)0, (byte)1, (byte)2, (byte)3, (byte)4); -#else if TYPE_SHORT - return new SAMPLE_ELEMENTS((short)0, (short)1, (short)2, (short)3, (short)4); -#else if TYPE_CHAR - return new SAMPLE_ELEMENTS((char)0, (char)1, (char)2, (char)3, (char)4); -#else if TYPE_OBJECT - return new SAMPLE_ELEMENTSBRACES(keys[0], keys[1], keys[2], keys[3], keys[4]); -#else - return new SAMPLE_ELEMENTS(0, 1, 2, 3, 4); -#endif - } - -#if !TYPE_OBJECT - public E create(KEY_TYPE... elements) { - return mapper.apply(elements); - } - - public E create(Object... elements) { - KEY_TYPE[] array = NEW_KEY_ARRAY(elements.length); - int i = 0; - for (Object e : elements) { - array[i++] = CLASS_TO_KEY(e); - } - return mapper.apply(array); - } - -#else - public E create(Object... elements) { - T[] array = (T[])ObjectArrays.newArray(keys[0].getClass(), elements.length); - int i = 0; - for (Object e : elements) { - array[i++] = CLASS_TO_KEY(e); - } - return mapper.apply(array); - } - -#endif - public ITERABLE KEY_GENERIC_TYPE order(LIST KEY_GENERIC_TYPE insertionOrder) { - return insertionOrder; - } - - public Iterable order(List insertionOrder) { - return insertionOrder; - } - - public static class Collections KEY_GENERIC_TYPE extends SIMPLE_TEST_GENERATOR KKS_GENERIC_TYPE implements TEST_COLLECTION_GENERATOR KEY_GENERIC_TYPE - { - public Collections(Function mapper) { - super(mapper); - } - } - - public static class Lists KEY_GENERIC_TYPE extends SIMPLE_TEST_GENERATOR KKS_GENERIC_TYPE implements TEST_LIST_GENERATOR KEY_GENERIC_TYPE - { - public Lists(Function mapper) { - super(mapper); - } - } - -#if !TYPE_BOOLEAN - public static class Sets KEY_GENERIC_TYPE extends SIMPLE_TEST_GENERATOR KKS_GENERIC_TYPE implements TEST_SET_GENERATOR KEY_GENERIC_TYPE - { - public Sets(Function mapper) { - super(mapper); - } - } - - public static class OrderedSets KEY_GENERIC_TYPE extends SIMPLE_TEST_GENERATOR KKS_GENERIC_TYPE implements TEST_ORDERED_SET_GENERATOR KEY_GENERIC_TYPE - { - public OrderedSets(Function mapper) { - super(mapper); - } - } - - public static class SortedSets KEY_GENERIC_TYPE extends SIMPLE_TEST_GENERATOR KKS_GENERIC_TYPE implements TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE - { - public SortedSets(Function mapper) { - super(mapper); - } - - @Override - public ITERABLE KEY_GENERIC_TYPE order(LIST KEY_GENERIC_TYPE insertionOrder) { - insertionOrder.sort(null); - return insertionOrder; - } - - @Override - public Iterable order(List insertionOrder) { - insertionOrder.sort(null); - return insertionOrder; - } - -#if TYPE_CHAR - @Override - public KEY_TYPE belowSamplesLesser() { return '_'; } - @Override - public KEY_TYPE belowSamplesGreater() { return '`'; } - @Override - public KEY_TYPE aboveSamplesLesser() { return 'f'; } - @Override - public KEY_TYPE aboveSamplesGreater() { return 'g'; } -#else if TYPE_OBJECT - @Override - public KEY_TYPE belowSamplesLesser() { return keys[5]; } - @Override - public KEY_TYPE belowSamplesGreater() { return keys[6]; } - @Override - public KEY_TYPE aboveSamplesLesser() { return keys[7]; } - @Override - public KEY_TYPE aboveSamplesGreater() { return keys[8]; } -#else - @Override - public KEY_TYPE belowSamplesLesser() { return -2; } - @Override - public KEY_TYPE belowSamplesGreater() { return -1; } - @Override - public KEY_TYPE aboveSamplesLesser() { return 5; } - @Override - public KEY_TYPE aboveSamplesGreater() { return 6; } -#endif - } - - public static class NavigableSets KEY_GENERIC_TYPE extends SIMPLE_TEST_GENERATOR KKS_GENERIC_TYPE implements TEST_NAVIGABLE_SET_GENERATOR KEY_GENERIC_TYPE - { - public NavigableSets(Function mapper) { - super(mapper); - } - - @Override - public ITERABLE KEY_GENERIC_TYPE order(LIST KEY_GENERIC_TYPE insertionOrder) { - insertionOrder.sort(null); - return insertionOrder; - } - - @Override - public Iterable order(List insertionOrder) { - insertionOrder.sort(null); - return insertionOrder; - } - -#if TYPE_CHAR - public SAMPLE_ELEMENTS KEY_GENERIC_TYPE getSamples() { return new SAMPLE_ELEMENTS('a', 'b', 'c', 'd', 'e'); } - @Override - public KEY_TYPE belowSamplesLesser() { return '_'; } - @Override - public KEY_TYPE belowSamplesGreater() { return '`'; } - @Override - public KEY_TYPE aboveSamplesLesser() { return 'f'; } - @Override - public KEY_TYPE aboveSamplesGreater() { return 'g'; } -#else if TYPE_OBJECT - @Override - public KEY_TYPE belowSamplesLesser() { return keys[5]; } - @Override - public KEY_TYPE belowSamplesGreater() { return keys[6]; } - @Override - public KEY_TYPE aboveSamplesLesser() { return keys[7]; } - @Override - public KEY_TYPE aboveSamplesGreater() { return keys[8]; } -#else - @Override - public KEY_TYPE belowSamplesLesser() { return -2; } - @Override - public KEY_TYPE belowSamplesGreater() { return -1; } - @Override - public KEY_TYPE aboveSamplesLesser() { return 5; } - @Override - public KEY_TYPE aboveSamplesGreater() { return 6; } -#endif - } -#endif +package speiger.src.testers.PACKAGE.impl; + +import java.util.List; +import java.util.function.Function; + +import speiger.src.collections.PACKAGE.collections.COLLECTION; +import speiger.src.collections.PACKAGE.collections.ITERABLE; +import speiger.src.collections.PACKAGE.lists.LIST; +#if !TYPE_BOOLEAN +import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET; +import speiger.src.collections.PACKAGE.sets.ORDERED_SET; +import speiger.src.collections.PACKAGE.sets.SET; +import speiger.src.collections.PACKAGE.sets.SORTED_SET; +#if TYPE_OBJECT +import speiger.src.collections.objects.utils.ObjectArrays; +#endif +#endif +import speiger.src.testers.PACKAGE.generators.TEST_COLLECTION_GENERATOR; +import speiger.src.testers.PACKAGE.generators.TEST_LIST_GENERATOR; +#if !TYPE_BOOLEAN +import speiger.src.testers.PACKAGE.generators.TEST_NAVIGABLE_SET_GENERATOR; +import speiger.src.testers.PACKAGE.generators.TEST_ORDERED_SET_GENERATOR; +import speiger.src.testers.PACKAGE.generators.TEST_SET_GENERATOR; +import speiger.src.testers.PACKAGE.generators.TEST_SORTED_SET_GENERATOR; +#endif +import speiger.src.testers.PACKAGE.utils.SAMPLE_ELEMENTS; + +@SuppressWarnings("javadoc") +public class SIMPLE_TEST_GENERATOR KKS_GENERIC_TYPE { + Function mapper; +#if TYPE_OBJECT + KEY_TYPE[] keys; +#endif + + public SIMPLE_TEST_GENERATOR(Function mapper) { + this.mapper = mapper; + } + +#if TYPE_OBJECT + public SIMPLE_TEST_GENERATOR KKS_GENERIC_TYPE setElements(KEY_TYPE...keys) { + this.keys = keys; + return this; + } + +#endif + public SAMPLE_ELEMENTS KEY_GENERIC_TYPE getSamples() { +#if TYPE_BOOLEAN + return new SAMPLE_ELEMENTS(true, false, true, false, true); +#else if TYPE_BYTE + return new SAMPLE_ELEMENTS((byte)0, (byte)1, (byte)2, (byte)3, (byte)4); +#else if TYPE_SHORT + return new SAMPLE_ELEMENTS((short)0, (short)1, (short)2, (short)3, (short)4); +#else if TYPE_CHAR + return new SAMPLE_ELEMENTS((char)0, (char)1, (char)2, (char)3, (char)4); +#else if TYPE_OBJECT + return new SAMPLE_ELEMENTSBRACES(keys[0], keys[1], keys[2], keys[3], keys[4]); +#else + return new SAMPLE_ELEMENTS(0, 1, 2, 3, 4); +#endif + } + +#if !TYPE_OBJECT + public E create(KEY_TYPE... elements) { + return mapper.apply(elements); + } + + public E create(Object... elements) { + KEY_TYPE[] array = NEW_KEY_ARRAY(elements.length); + int i = 0; + for (Object e : elements) { + array[i++] = CLASS_TO_KEY(e); + } + return mapper.apply(array); + } + +#else + public E create(Object... elements) { + T[] array = (T[])ObjectArrays.newArray(keys[0].getClass(), elements.length); + int i = 0; + for (Object e : elements) { + array[i++] = CLASS_TO_KEY(e); + } + return mapper.apply(array); + } + +#endif + public ITERABLE KEY_GENERIC_TYPE order(LIST KEY_GENERIC_TYPE insertionOrder) { + return insertionOrder; + } + + public Iterable order(List insertionOrder) { + return insertionOrder; + } + + public static class Collections KEY_GENERIC_TYPE extends SIMPLE_TEST_GENERATOR KKS_GENERIC_TYPE implements TEST_COLLECTION_GENERATOR KEY_GENERIC_TYPE + { + public Collections(Function mapper) { + super(mapper); + } + } + + public static class Lists KEY_GENERIC_TYPE extends SIMPLE_TEST_GENERATOR KKS_GENERIC_TYPE implements TEST_LIST_GENERATOR KEY_GENERIC_TYPE + { + public Lists(Function mapper) { + super(mapper); + } + } + +#if !TYPE_BOOLEAN + public static class Sets KEY_GENERIC_TYPE extends SIMPLE_TEST_GENERATOR KKS_GENERIC_TYPE implements TEST_SET_GENERATOR KEY_GENERIC_TYPE + { + public Sets(Function mapper) { + super(mapper); + } + } + + public static class OrderedSets KEY_GENERIC_TYPE extends SIMPLE_TEST_GENERATOR KKS_GENERIC_TYPE implements TEST_ORDERED_SET_GENERATOR KEY_GENERIC_TYPE + { + public OrderedSets(Function mapper) { + super(mapper); + } + } + + public static class SortedSets KEY_GENERIC_TYPE extends SIMPLE_TEST_GENERATOR KKS_GENERIC_TYPE implements TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE + { + public SortedSets(Function mapper) { + super(mapper); + } + + @Override + public ITERABLE KEY_GENERIC_TYPE order(LIST KEY_GENERIC_TYPE insertionOrder) { + insertionOrder.sort(null); + return insertionOrder; + } + + @Override + public Iterable order(List insertionOrder) { + insertionOrder.sort(null); + return insertionOrder; + } + +#if TYPE_CHAR + @Override + public KEY_TYPE belowSamplesLesser() { return '_'; } + @Override + public KEY_TYPE belowSamplesGreater() { return '`'; } + @Override + public KEY_TYPE aboveSamplesLesser() { return 'f'; } + @Override + public KEY_TYPE aboveSamplesGreater() { return 'g'; } +#else if TYPE_OBJECT + @Override + public KEY_TYPE belowSamplesLesser() { return keys[5]; } + @Override + public KEY_TYPE belowSamplesGreater() { return keys[6]; } + @Override + public KEY_TYPE aboveSamplesLesser() { return keys[7]; } + @Override + public KEY_TYPE aboveSamplesGreater() { return keys[8]; } +#else + @Override + public KEY_TYPE belowSamplesLesser() { return -2; } + @Override + public KEY_TYPE belowSamplesGreater() { return -1; } + @Override + public KEY_TYPE aboveSamplesLesser() { return 5; } + @Override + public KEY_TYPE aboveSamplesGreater() { return 6; } +#endif + } + + public static class NavigableSets KEY_GENERIC_TYPE extends SIMPLE_TEST_GENERATOR KKS_GENERIC_TYPE implements TEST_NAVIGABLE_SET_GENERATOR KEY_GENERIC_TYPE + { + public NavigableSets(Function mapper) { + super(mapper); + } + + @Override + public ITERABLE KEY_GENERIC_TYPE order(LIST KEY_GENERIC_TYPE insertionOrder) { + insertionOrder.sort(null); + return insertionOrder; + } + + @Override + public Iterable order(List insertionOrder) { + insertionOrder.sort(null); + return insertionOrder; + } + +#if TYPE_CHAR + public SAMPLE_ELEMENTS KEY_GENERIC_TYPE getSamples() { return new SAMPLE_ELEMENTS('a', 'b', 'c', 'd', 'e'); } + @Override + public KEY_TYPE belowSamplesLesser() { return '_'; } + @Override + public KEY_TYPE belowSamplesGreater() { return '`'; } + @Override + public KEY_TYPE aboveSamplesLesser() { return 'f'; } + @Override + public KEY_TYPE aboveSamplesGreater() { return 'g'; } +#else if TYPE_OBJECT + @Override + public KEY_TYPE belowSamplesLesser() { return keys[5]; } + @Override + public KEY_TYPE belowSamplesGreater() { return keys[6]; } + @Override + public KEY_TYPE aboveSamplesLesser() { return keys[7]; } + @Override + public KEY_TYPE aboveSamplesGreater() { return keys[8]; } +#else + @Override + public KEY_TYPE belowSamplesLesser() { return -2; } + @Override + public KEY_TYPE belowSamplesGreater() { return -1; } + @Override + public KEY_TYPE aboveSamplesLesser() { return 5; } + @Override + public KEY_TYPE aboveSamplesGreater() { return 6; } +#endif + } +#endif } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/impl/SortedSetSubsetTestSetGenerator.template b/src/builder/resources/speiger/assets/testers/templates/impl/SortedSetSubsetTestSetGenerator.template index 806e610..abbddc5 100644 --- a/src/builder/resources/speiger/assets/testers/templates/impl/SortedSetSubsetTestSetGenerator.template +++ b/src/builder/resources/speiger/assets/testers/templates/impl/SortedSetSubsetTestSetGenerator.template @@ -1,173 +1,173 @@ -package speiger.src.testers.PACKAGE.impl; - -#if TYPE_OBJECT -import java.util.Comparator; -#endif -import java.util.List; - -import com.google.common.collect.testing.DerivedCollectionGenerators.Bound; - -import speiger.src.collections.PACKAGE.collections.ITERABLE; -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.functions.COMPARATOR; -#endif -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET; -import speiger.src.collections.PACKAGE.sets.SORTED_SET; -import speiger.src.testers.PACKAGE.generators.TEST_SORTED_SET_GENERATOR; -import speiger.src.testers.PACKAGE.generators.TEST_NAVIGABLE_SET_GENERATOR; -import speiger.src.testers.PACKAGE.utils.SAMPLE_ELEMENTS; - -@SuppressWarnings("javadoc") -public class SUB_SORTED_SET_CLASS_GENERATOR KEY_GENERIC_TYPE implements TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE -{ - final Bound to; - final Bound from; - final KEY_TYPE firstInclusive; - final KEY_TYPE lastInclusive; - private final COMPARATOR KEY_GENERIC_TYPE comparator; - private final TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE delegate; - - public SUB_SORTED_SET_CLASS_GENERATOR(TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE delegate, Bound to, Bound from) { - this.to = to; - this.from = from; - this.delegate = delegate; - - SORTED_SET KEY_GENERIC_TYPE emptySet = delegate.create(NEW_KEY_ARRAY(0)); - comparator = emptySet.comparator(); - - SAMPLE_ELEMENTS KEY_GENERIC_TYPE samples = delegate.getSamples(); - LIST KEY_GENERIC_TYPE samplesList = new ARRAY_LISTBRACES(samples.asList()); - samplesList.sort(comparator); - firstInclusive = samplesList.GET_KEY(0); - lastInclusive = samplesList.GET_KEY(samplesList.size() - 1); - } - - public final TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE getInnerGenerator() { - return delegate; - } - - public final Bound getTo() { - return to; - } - - public final Bound getFrom() { - return from; - } - - SORTED_SET KEY_GENERIC_TYPE createSubSet(SORTED_SET KEY_GENERIC_TYPE set, KEY_TYPE firstExclusive, KEY_TYPE lastExclusive) { - if (from == Bound.NO_BOUND && to == Bound.EXCLUSIVE) { - return set.headSet(lastExclusive); - } else if (from == Bound.INCLUSIVE && to == Bound.NO_BOUND) { - return set.tailSet(firstInclusive); - } else if (from == Bound.INCLUSIVE && to == Bound.EXCLUSIVE) { - return set.subSet(firstInclusive, lastExclusive); - } else { - throw new IllegalArgumentException(); - } - } - - @Override - public KEY_TYPE belowSamplesLesser() { - throw new UnsupportedOperationException(); - } - - @Override - public KEY_TYPE belowSamplesGreater() { - throw new UnsupportedOperationException(); - } - - @Override - public KEY_TYPE aboveSamplesLesser() { - throw new UnsupportedOperationException(); - } - - @Override - public KEY_TYPE aboveSamplesGreater() { - throw new UnsupportedOperationException(); - } - - @Override - public SAMPLE_ELEMENTS KEY_GENERIC_TYPE getSamples() { - return delegate.getSamples(); - } - - @Override - public ITERABLE KEY_GENERIC_TYPE order(LIST KEY_GENERIC_TYPE insertionOrder) { - return delegate.order(insertionOrder); - } - - @Override - public Iterable order(List insertionOrder) { - return delegate.order(insertionOrder); - } - - @Override - public SORTED_SET KEY_GENERIC_TYPE create(KEY_OBJECT_TYPE... elements) { -#if TYPE_OBJECT - LIST KEY_GENERIC_TYPE normalValues = (LIST KEY_GENERIC_TYPE)ARRAY_LIST.wrap(elements); -#else - LIST KEY_GENERIC_TYPE normalValues = ARRAY_LIST.wrap(elements); -#endif - LIST KEY_GENERIC_TYPE extremeValues = new ARRAY_LISTBRACES(); - KEY_TYPE firstExclusive = delegate.belowSamplesGreater(); - KEY_TYPE lastExclusive = delegate.aboveSamplesLesser(); - if (from != Bound.NO_BOUND) { - extremeValues.add(delegate.belowSamplesLesser()); - extremeValues.add(delegate.belowSamplesGreater()); - } - if (to != Bound.NO_BOUND) { - extremeValues.add(delegate.aboveSamplesLesser()); - extremeValues.add(delegate.aboveSamplesGreater()); - } - LIST KEY_GENERIC_TYPE allEntries = new ARRAY_LISTBRACES(); - allEntries.addAll(extremeValues); - allEntries.addAll(normalValues); - SORTED_SET KEY_GENERIC_TYPE set = delegate.create(allEntries.toArray()); - - return createSubSet(set, firstExclusive, lastExclusive); - } - -#if !TYPE_OBJECT - @Override - public SORTED_SET KEY_GENERIC_TYPE create(Object... elements) { - KEY_TYPE[] array = NEW_KEY_ARRAY(elements.length); - int i = 0; - for (Object e : elements) { - array[i++] = CLASS_TO_KEY(e); - } - return create(array); - } - -#endif - public static final class SUB_NAVIGABLE_SET_CLASS_GENERATOR KEY_GENERIC_TYPE extends SUB_SORTED_SET_CLASS_GENERATOR KEY_GENERIC_TYPE implements TEST_NAVIGABLE_SET_GENERATOR KEY_GENERIC_TYPE { - public SUB_NAVIGABLE_SET_CLASS_GENERATOR(TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE delegate, Bound to, Bound from) { - super(delegate, to, from); - } - -#if !TYPE_OBJECT - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE create(KEY_TYPE... elements) { - return (NAVIGABLE_SET KEY_GENERIC_TYPE)super.create(elements); - } - -#endif - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE create(Object... elements) { - return (NAVIGABLE_SET KEY_GENERIC_TYPE)super.create(elements); - } - - @Override - NAVIGABLE_SET KEY_GENERIC_TYPE createSubSet(SORTED_SET KEY_GENERIC_TYPE sortedSet, KEY_TYPE firstExclusive, KEY_TYPE lastExclusive) { - NAVIGABLE_SET KEY_GENERIC_TYPE set = (NAVIGABLE_SET KEY_GENERIC_TYPE) sortedSet; - if (from == Bound.NO_BOUND && to == Bound.INCLUSIVE) return set.headSet(lastInclusive, true); - else if (from == Bound.EXCLUSIVE && to == Bound.NO_BOUND) return set.tailSet(firstExclusive, false); - else if (from == Bound.EXCLUSIVE && to == Bound.EXCLUSIVE) return set.subSet(firstExclusive, false, lastExclusive, false); - else if (from == Bound.EXCLUSIVE && to == Bound.INCLUSIVE) return set.subSet(firstExclusive, false, lastInclusive, true); - else if (from == Bound.INCLUSIVE && to == Bound.INCLUSIVE) return set.subSet(firstInclusive, true, lastInclusive, true); - return (NAVIGABLE_SET KEY_GENERIC_TYPE)super.createSubSet(set, firstExclusive, lastExclusive); - - } - } -} +package speiger.src.testers.PACKAGE.impl; + +#if TYPE_OBJECT +import java.util.Comparator; +#endif +import java.util.List; + +import com.google.common.collect.testing.DerivedCollectionGenerators.Bound; + +import speiger.src.collections.PACKAGE.collections.ITERABLE; +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.functions.COMPARATOR; +#endif +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET; +import speiger.src.collections.PACKAGE.sets.SORTED_SET; +import speiger.src.testers.PACKAGE.generators.TEST_SORTED_SET_GENERATOR; +import speiger.src.testers.PACKAGE.generators.TEST_NAVIGABLE_SET_GENERATOR; +import speiger.src.testers.PACKAGE.utils.SAMPLE_ELEMENTS; + +@SuppressWarnings("javadoc") +public class SUB_SORTED_SET_CLASS_GENERATOR KEY_GENERIC_TYPE implements TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE +{ + final Bound to; + final Bound from; + final KEY_TYPE firstInclusive; + final KEY_TYPE lastInclusive; + private final COMPARATOR KEY_GENERIC_TYPE comparator; + private final TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE delegate; + + public SUB_SORTED_SET_CLASS_GENERATOR(TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE delegate, Bound to, Bound from) { + this.to = to; + this.from = from; + this.delegate = delegate; + + SORTED_SET KEY_GENERIC_TYPE emptySet = delegate.create(NEW_KEY_ARRAY(0)); + comparator = emptySet.comparator(); + + SAMPLE_ELEMENTS KEY_GENERIC_TYPE samples = delegate.getSamples(); + LIST KEY_GENERIC_TYPE samplesList = new ARRAY_LISTBRACES(samples.asList()); + samplesList.sort(comparator); + firstInclusive = samplesList.GET_KEY(0); + lastInclusive = samplesList.GET_KEY(samplesList.size() - 1); + } + + public final TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE getInnerGenerator() { + return delegate; + } + + public final Bound getTo() { + return to; + } + + public final Bound getFrom() { + return from; + } + + SORTED_SET KEY_GENERIC_TYPE createSubSet(SORTED_SET KEY_GENERIC_TYPE set, KEY_TYPE firstExclusive, KEY_TYPE lastExclusive) { + if (from == Bound.NO_BOUND && to == Bound.EXCLUSIVE) { + return set.headSet(lastExclusive); + } else if (from == Bound.INCLUSIVE && to == Bound.NO_BOUND) { + return set.tailSet(firstInclusive); + } else if (from == Bound.INCLUSIVE && to == Bound.EXCLUSIVE) { + return set.subSet(firstInclusive, lastExclusive); + } else { + throw new IllegalArgumentException(); + } + } + + @Override + public KEY_TYPE belowSamplesLesser() { + throw new UnsupportedOperationException(); + } + + @Override + public KEY_TYPE belowSamplesGreater() { + throw new UnsupportedOperationException(); + } + + @Override + public KEY_TYPE aboveSamplesLesser() { + throw new UnsupportedOperationException(); + } + + @Override + public KEY_TYPE aboveSamplesGreater() { + throw new UnsupportedOperationException(); + } + + @Override + public SAMPLE_ELEMENTS KEY_GENERIC_TYPE getSamples() { + return delegate.getSamples(); + } + + @Override + public ITERABLE KEY_GENERIC_TYPE order(LIST KEY_GENERIC_TYPE insertionOrder) { + return delegate.order(insertionOrder); + } + + @Override + public Iterable order(List insertionOrder) { + return delegate.order(insertionOrder); + } + + @Override + public SORTED_SET KEY_GENERIC_TYPE create(KEY_OBJECT_TYPE... elements) { +#if TYPE_OBJECT + LIST KEY_GENERIC_TYPE normalValues = (LIST KEY_GENERIC_TYPE)ARRAY_LIST.wrap(elements); +#else + LIST KEY_GENERIC_TYPE normalValues = ARRAY_LIST.wrap(elements); +#endif + LIST KEY_GENERIC_TYPE extremeValues = new ARRAY_LISTBRACES(); + KEY_TYPE firstExclusive = delegate.belowSamplesGreater(); + KEY_TYPE lastExclusive = delegate.aboveSamplesLesser(); + if (from != Bound.NO_BOUND) { + extremeValues.add(delegate.belowSamplesLesser()); + extremeValues.add(delegate.belowSamplesGreater()); + } + if (to != Bound.NO_BOUND) { + extremeValues.add(delegate.aboveSamplesLesser()); + extremeValues.add(delegate.aboveSamplesGreater()); + } + LIST KEY_GENERIC_TYPE allEntries = new ARRAY_LISTBRACES(); + allEntries.addAll(extremeValues); + allEntries.addAll(normalValues); + SORTED_SET KEY_GENERIC_TYPE set = delegate.create(allEntries.toArray()); + + return createSubSet(set, firstExclusive, lastExclusive); + } + +#if !TYPE_OBJECT + @Override + public SORTED_SET KEY_GENERIC_TYPE create(Object... elements) { + KEY_TYPE[] array = NEW_KEY_ARRAY(elements.length); + int i = 0; + for (Object e : elements) { + array[i++] = CLASS_TO_KEY(e); + } + return create(array); + } + +#endif + public static final class SUB_NAVIGABLE_SET_CLASS_GENERATOR KEY_GENERIC_TYPE extends SUB_SORTED_SET_CLASS_GENERATOR KEY_GENERIC_TYPE implements TEST_NAVIGABLE_SET_GENERATOR KEY_GENERIC_TYPE { + public SUB_NAVIGABLE_SET_CLASS_GENERATOR(TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE delegate, Bound to, Bound from) { + super(delegate, to, from); + } + +#if !TYPE_OBJECT + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE create(KEY_TYPE... elements) { + return (NAVIGABLE_SET KEY_GENERIC_TYPE)super.create(elements); + } + +#endif + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE create(Object... elements) { + return (NAVIGABLE_SET KEY_GENERIC_TYPE)super.create(elements); + } + + @Override + NAVIGABLE_SET KEY_GENERIC_TYPE createSubSet(SORTED_SET KEY_GENERIC_TYPE sortedSet, KEY_TYPE firstExclusive, KEY_TYPE lastExclusive) { + NAVIGABLE_SET KEY_GENERIC_TYPE set = (NAVIGABLE_SET KEY_GENERIC_TYPE) sortedSet; + if (from == Bound.NO_BOUND && to == Bound.INCLUSIVE) return set.headSet(lastInclusive, true); + else if (from == Bound.EXCLUSIVE && to == Bound.NO_BOUND) return set.tailSet(firstExclusive, false); + else if (from == Bound.EXCLUSIVE && to == Bound.EXCLUSIVE) return set.subSet(firstExclusive, false, lastExclusive, false); + else if (from == Bound.EXCLUSIVE && to == Bound.INCLUSIVE) return set.subSet(firstExclusive, false, lastInclusive, true); + else if (from == Bound.INCLUSIVE && to == Bound.INCLUSIVE) return set.subSet(firstInclusive, true, lastInclusive, true); + return (NAVIGABLE_SET KEY_GENERIC_TYPE)super.createSubSet(set, firstExclusive, lastExclusive); + + } + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/impl/maps/DerivedMapGenerators.template b/src/builder/resources/speiger/assets/testers/templates/impl/maps/DerivedMapGenerators.template index 7b7b423..a8d141a 100644 --- a/src/builder/resources/speiger/assets/testers/templates/impl/maps/DerivedMapGenerators.template +++ b/src/builder/resources/speiger/assets/testers/templates/impl/maps/DerivedMapGenerators.template @@ -1,550 +1,550 @@ -package speiger.src.testers.PACKAGE.impl.maps; - -import java.util.Comparator; -import java.util.List; -import java.util.Map; -#if VALUE_OBJECT -import java.util.Objects; -#endif - -import com.google.common.collect.testing.DerivedCollectionGenerators.Bound; -import com.google.common.collect.testing.OneSizeTestContainerGenerator; - -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.functions.COMPARATOR; -import speiger.src.collections.PACKAGE.collections.ITERABLE; -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.lists.LIST; -#endif -import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.MAP.Entry; -import speiger.src.collections.PACKAGE.maps.interfaces.NAVIGABLE_MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.SORTED_MAP; -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.sets.SET; -import speiger.src.collections.PACKAGE.sets.ORDERED_SET; -#endif -import speiger.src.collections.PACKAGE.sets.SORTED_SET; -import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET; -#if !TYPE_OBJECT -import speiger.src.testers.PACKAGE.generators.TEST_SET_GENERATOR; -#endif -import speiger.src.testers.PACKAGE.generators.TEST_ORDERED_SET_GENERATOR; -import speiger.src.testers.PACKAGE.generators.TEST_SORTED_SET_GENERATOR; -import speiger.src.testers.PACKAGE.generators.TEST_NAVIGABLE_SET_GENERATOR; -import speiger.src.testers.PACKAGE.generators.maps.TEST_MAP_GENERATOR; -import speiger.src.testers.PACKAGE.generators.maps.TEST_SORTED_MAP_GENERATOR; -import speiger.src.testers.PACKAGE.generators.maps.TEST_ORDERED_MAP_GENERATOR; -#if !TYPE_OBJECT -import speiger.src.testers.PACKAGE.utils.SAMPLE_ELEMENTS; -#endif -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; -#if !VALUE_OBJECT && !SAME_TYPE -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERABLE; -import speiger.src.collections.VALUE_PACKAGE.lists.VALUE_LIST; -import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_COMPARATOR; -#endif -import speiger.src.testers.VALUE_PACKAGE.generators.VALUE_TEST_COLLECTION_GENERATOR; -#if !VALUE_OBJECT && !SAME_TYPE -import speiger.src.testers.VALUE_PACKAGE.utils.VALUE_SAMPLE_ELEMENTS; -#endif -import speiger.src.collections.objects.collections.ObjectIterable; -import speiger.src.collections.objects.lists.ObjectArrayList; -import speiger.src.collections.objects.lists.ObjectList; -import speiger.src.collections.objects.sets.ObjectSet; -import speiger.src.collections.objects.sets.ObjectOrderedSet; -import speiger.src.collections.objects.utils.ObjectIterators; -import speiger.src.collections.objects.utils.ObjectLists; -import speiger.src.testers.objects.generators.TestObjectSetGenerator; -#if !TYPE_OBJECT -import speiger.src.testers.objects.generators.TestObjectOrderedSetGenerator; -#endif -import speiger.src.testers.objects.utils.ObjectSamples; - -@SuppressWarnings("javadoc") -public class DERIVED_MAP_GENERATORS { - public static class NavigableMapGenerator KEY_VALUE_GENERIC_TYPE extends SortedMapGenerator KEY_VALUE_GENERIC_TYPE { - public NavigableMapGenerator(TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE parent, Bound to, Bound from) { - super(parent, to, from); - } - - @Override - NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE createSubMap(SORTED_MAP KEY_VALUE_GENERIC_TYPE sortedMap, KEY_TYPE firstExclusive, KEY_TYPE lastExclusive) { - NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map = (NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE) sortedMap; - if (from == Bound.NO_BOUND && to == Bound.INCLUSIVE) { - return map.headMap(lastInclusive, true); - } else if (from == Bound.EXCLUSIVE && to == Bound.NO_BOUND) { - return map.tailMap(firstExclusive, false); - } else if (from == Bound.EXCLUSIVE && to == Bound.EXCLUSIVE) { - return map.subMap(firstExclusive, false, lastExclusive, false); - } else if (from == Bound.EXCLUSIVE && to == Bound.INCLUSIVE) { - return map.subMap(firstExclusive, false, lastInclusive, true); - } else if (from == Bound.INCLUSIVE && to == Bound.INCLUSIVE) { - return map.subMap(firstInclusive, true, lastInclusive, true); - } else { - return (NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE) super.createSubMap(map, firstExclusive, lastExclusive); - } - } - } - - public static class SortedMapGenerator KEY_VALUE_GENERIC_TYPE extends MapGenerator KEY_VALUE_GENERIC_TYPE implements TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE { - TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE parent; - Bound to; - Bound from; - KEY_TYPE firstInclusive; - KEY_TYPE lastInclusive; - Comparator entryComparator; - - public SortedMapGenerator(TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE parent, Bound to, Bound from) { - super(parent); - this.parent = parent; - this.to = to; - this.from = from; - SORTED_MAP KEY_VALUE_GENERIC_TYPE map = parent.create(); - entryComparator = DERIVED_MAP_GENERATORS.entryComparator(map.comparator()); - ObjectList samples = parent.getSamples().asList(); - samples.sort(entryComparator); - firstInclusive = samples.get(0).ENTRY_KEY(); - lastInclusive = samples.get(samples.size() - 1).ENTRY_KEY(); - } - - @Override - public SORTED_MAP KEY_VALUE_GENERIC_TYPE create(Entry KEY_VALUE_GENERIC_TYPE... elements) { - ObjectList entries = new ObjectArrayList<>(); - if (from != Bound.NO_BOUND) { - entries.add(parent.belowSamplesLesser()); - entries.add(parent.belowSamplesGreater()); - } - if (to != Bound.NO_BOUND) { - entries.add(parent.aboveSamplesLesser()); - entries.add(parent.aboveSamplesGreater()); - } - entries.addAll(elements); - return createSubMap(parent.create(entries.toArray(Entry[]::new)), parent.belowSamplesGreater().ENTRY_KEY(), parent.aboveSamplesLesser().ENTRY_KEY()); - } - - SORTED_MAP KEY_VALUE_GENERIC_TYPE createSubMap(SORTED_MAP KEY_VALUE_GENERIC_TYPE map, KEY_TYPE firstExclusive, KEY_TYPE lastExclusive) { - if (from == Bound.NO_BOUND && to == Bound.EXCLUSIVE) { - return map.headMap(lastExclusive); - } else if (from == Bound.INCLUSIVE && to == Bound.NO_BOUND) { - return map.tailMap(firstInclusive); - } else if (from == Bound.INCLUSIVE && to == Bound.EXCLUSIVE) { - return map.subMap(firstInclusive, lastExclusive); - } else { - throw new IllegalArgumentException(); - } - } - - @Override - public Entry KEY_VALUE_GENERIC_TYPE belowSamplesLesser() { - throw new UnsupportedOperationException(); - } - - @Override - public Entry KEY_VALUE_GENERIC_TYPE belowSamplesGreater() { - throw new UnsupportedOperationException(); - } - - @Override - public Entry KEY_VALUE_GENERIC_TYPE aboveSamplesLesser() { - throw new UnsupportedOperationException(); - } - - @Override - public Entry KEY_VALUE_GENERIC_TYPE aboveSamplesGreater() { - throw new UnsupportedOperationException(); - } - } - - public static class DescendingTestMapGenerator KEY_VALUE_GENERIC_TYPE extends MapGenerator KEY_VALUE_GENERIC_TYPE implements TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE - { - TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE parent; - - public DescendingTestMapGenerator(TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE parent) { - super(parent); - this.parent = parent; - } - - @Override - public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE create(Entry KEY_VALUE_GENERIC_TYPE... elements) { - return ((NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE)parent.create(elements)).descendingMap(); - } - - @Override - public Iterable> order(List> insertionOrder) { - ObjectList> values = ObjectIterators.pour(ObjectIterators.wrap(parent.order(insertionOrder).iterator())); - ObjectLists.reverse(values); - return values; - } - - @Override - public ObjectIterable order(ObjectList insertionOrder) { - ObjectList values = parent.order(insertionOrder).pourAsList(); - ObjectLists.reverse(values); - return values; - } - - @Override - public Entry KEY_VALUE_GENERIC_TYPE belowSamplesLesser() { - return parent.aboveSamplesGreater(); - } - - @Override - public Entry KEY_VALUE_GENERIC_TYPE belowSamplesGreater() { - return parent.aboveSamplesLesser(); - } - - @Override - public Entry KEY_VALUE_GENERIC_TYPE aboveSamplesLesser() { - return parent.belowSamplesGreater(); - } - - @Override - public Entry KEY_VALUE_GENERIC_TYPE aboveSamplesGreater() { - return parent.belowSamplesLesser(); - } - } - - public static class MapGenerator KEY_VALUE_GENERIC_TYPE implements TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE - { - TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE parent; - - public MapGenerator(TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE parent) { - this.parent = parent; - } - - @Override - public Iterable> order(List> insertionOrder) { - return parent.order(insertionOrder); - } - - @Override - public ObjectSamples getSamples() { - return parent.getSamples(); - } - - @Override - public ObjectIterable order(ObjectList insertionOrder) { - return parent.order(insertionOrder); - } - - @Override - public MAP KEY_VALUE_GENERIC_TYPE create(Entry KEY_VALUE_GENERIC_TYPE... elements) { - return parent.create(elements); - } - } - - public static GENERIC_KEY_VALUE_BRACES TestObjectSetGenerator entrySetGenerator(OneSizeTestContainerGenerator, Map.Entry> inner) { - if(inner.getInnerGenerator() instanceof TEST_ORDERED_MAP_GENERATOR) { - ObjectSet set = ((TEST_ORDERED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE) inner.getInnerGenerator()).create().ENTRY_SET(); - if(set instanceof ObjectOrderedSet) return new OrderedMapEntrySetGeneratorKV_BRACES(inner); - } - return new MapEntrySetGeneratorKV_BRACES(inner); - } - - public static class OrderedMapEntrySetGenerator KEY_VALUE_GENERIC_TYPE extends MapEntrySetGenerator KEY_VALUE_GENERIC_TYPE implements TestObjectOrderedSetGenerator { - - public OrderedMapEntrySetGenerator(OneSizeTestContainerGenerator, Map.Entry> inner) { - super(inner); - } - - public ObjectOrderedSet create(Object... elements) { - return (ObjectOrderedSet)super.create(elements); - } - } - - public static class MapEntrySetGenerator KEY_VALUE_GENERIC_TYPE implements TestObjectSetGenerator { - TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE generator; - - public MapEntrySetGenerator(OneSizeTestContainerGenerator, Map.Entry> inner) { - generator = (TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE) inner.getInnerGenerator(); - } - - @Override - public ObjectSamples getSamples() { - return generator.getSamples(); - } - - @Override - public ObjectIterable order(ObjectList insertionOrder) { - return generator.order(insertionOrder); - } - - @Override - public Iterable order(List insertionOrder) { - return generator.order(new ObjectArrayList(insertionOrder)); - } - - @Override - public Entry KEY_VALUE_GENERIC_TYPE[] createArray(int length) { - return new Entry[length]; - } - - @Override - public ObjectSet create(Object... elements) { - return generator.create(elements).ENTRY_SET(); - } - } - - public static GENERIC_KEY_VALUE_BRACES TEST_SET_GENERATOR KEY_GENERIC_TYPE keySetGenerator(OneSizeTestContainerGenerator, Map.Entry> inner) { - if (inner.getInnerGenerator() instanceof TEST_SORTED_MAP_GENERATOR) { - SET KEY_GENERIC_TYPE set = ((TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE) inner.getInnerGenerator()).create().keySet(); - if(set instanceof NAVIGABLE_SET) return new MapNavigableKeySetGeneratorKV_BRACES(inner); - if(set instanceof SORTED_SET) return new MapSortedKeySetGeneratorKV_BRACES(inner); - } - if(inner.getInnerGenerator() instanceof TEST_ORDERED_MAP_GENERATOR) { - SET KEY_GENERIC_TYPE set = ((TEST_ORDERED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE) inner.getInnerGenerator()).create().keySet(); - if(set instanceof ORDERED_SET) return new MapOrderedKeySetGeneratorKV_BRACES(inner); - } - return new MapKeySetGeneratorKV_BRACES(inner); - } - - public static class MapNavigableKeySetGenerator KEY_VALUE_GENERIC_TYPE extends MapSortedKeySetGenerator KEY_VALUE_GENERIC_TYPE implements TEST_NAVIGABLE_SET_GENERATOR KEY_GENERIC_TYPE { - public MapNavigableKeySetGenerator(OneSizeTestContainerGenerator, Map.Entry> inner) { - super(inner); - } - -#if !TYPE_OBJECT - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE create(KEY_TYPE... elements) { - return (NAVIGABLE_SET KEY_GENERIC_TYPE) super.create(elements); - } - -#endif - @Override - public NAVIGABLE_SET KEY_GENERIC_TYPE create(Object... elements) { - return (NAVIGABLE_SET KEY_GENERIC_TYPE) super.create(elements); - } - } - - public static class MapSortedKeySetGenerator KEY_VALUE_GENERIC_TYPE extends MapKeySetGenerator KEY_VALUE_GENERIC_TYPE implements TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE { - TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE generator; - - public MapSortedKeySetGenerator(OneSizeTestContainerGenerator, Map.Entry> inner) { - super(inner); - generator = (TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE) inner.getInnerGenerator(); - } - -#if !TYPE_OBJECT - @Override - public SORTED_SET KEY_GENERIC_TYPE create(KEY_TYPE... elements) { - return (SORTED_SET KEY_GENERIC_TYPE) super.create(elements); - } - -#endif - @Override - public SORTED_SET KEY_GENERIC_TYPE create(Object... elements) { - return (SORTED_SET KEY_GENERIC_TYPE) super.create(elements); - } - - @Override - public KEY_TYPE belowSamplesLesser() { - return generator.belowSamplesLesser().ENTRY_KEY(); - } - - @Override - public KEY_TYPE belowSamplesGreater() { - return generator.belowSamplesGreater().ENTRY_KEY(); - } - - @Override - public KEY_TYPE aboveSamplesLesser() { - return generator.aboveSamplesLesser().ENTRY_KEY(); - } - - @Override - public KEY_TYPE aboveSamplesGreater() { - return generator.aboveSamplesGreater().ENTRY_KEY(); - } - } - - public static class MapOrderedKeySetGenerator KEY_VALUE_GENERIC_TYPE extends MapKeySetGenerator KEY_VALUE_GENERIC_TYPE implements TEST_ORDERED_SET_GENERATOR KEY_GENERIC_TYPE { - - public MapOrderedKeySetGenerator(OneSizeTestContainerGenerator, Map.Entry> inner) { - super(inner); - } - -#if !TYPE_OBJECT - @Override - public ORDERED_SET KEY_GENERIC_TYPE create(KEY_TYPE... elements) { - return (ORDERED_SET KEY_GENERIC_TYPE) super.create(elements); - } - -#endif - @Override - public ORDERED_SET KEY_GENERIC_TYPE create(Object... elements) { - return (ORDERED_SET KEY_GENERIC_TYPE) super.create(elements); - } - } - - public static class MapKeySetGenerator KEY_VALUE_GENERIC_TYPE implements TEST_SET_GENERATOR KEY_GENERIC_TYPE { - TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE generator; - SAMPLE_ELEMENTS KEY_GENERIC_TYPE samples; - - public MapKeySetGenerator(OneSizeTestContainerGenerator, Map.Entry> inner) { - generator = (TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE) inner.getInnerGenerator(); - ObjectSamples samples = generator.getSamples(); - this.samples = new SAMPLE_ELEMENTSBRACES(samples.e0().ENTRY_KEY(), samples.e1().ENTRY_KEY(), samples.e2().ENTRY_KEY(), samples.e3().ENTRY_KEY(), samples.e4().ENTRY_KEY()); - } - - @Override - public SAMPLE_ELEMENTS KEY_GENERIC_TYPE getSamples() { - return samples; - } - - @Override - public ITERABLE KEY_GENERIC_TYPE order(LIST KEY_GENERIC_TYPE insertionOrder) { - VALUE_TYPE value = generator.getSamples().e0().ENTRY_VALUE(); - ObjectList entries = new ObjectArrayList<>(); - for (KEY_TYPE key : insertionOrder) { - entries.add(new ABSTRACT_MAP.BasicEntryKV_BRACES(key, value)); - } - LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); - for (Entry KEY_VALUE_GENERIC_TYPE entry : generator.order(entries)) { - list.add(entry.ENTRY_KEY()); - } - return list; - } - - @Override - public Iterable order(List insertionOrder) { - VALUE_TYPE value = generator.getSamples().e0().ENTRY_VALUE(); - ObjectList entries = new ObjectArrayList<>(); - for (KEY_TYPE key : insertionOrder) { - entries.add(new ABSTRACT_MAP.BasicEntryKV_BRACES(key, value)); - } - LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); - for (Entry KEY_VALUE_GENERIC_TYPE entry : generator.order(entries)) { - list.add(entry.ENTRY_KEY()); - } - return list; - } - -#if !TYPE_OBJECT - @Override - public SET KEY_GENERIC_TYPE create(KEY_TYPE... elements) { - Entry KEY_VALUE_GENERIC_TYPE[] result = new Entry[elements.length]; - int index = 0; - for (Entry KEY_VALUE_GENERIC_TYPE entry : generator.getSamples().asList().subList(0, elements.length)) { - result[index] = new ABSTRACT_MAP.BasicEntryKV_BRACES(elements[index++], entry.ENTRY_VALUE()); - } - return generator.create(result).keySet(); - } - -#endif - @Override - public SET KEY_GENERIC_TYPE create(Object... elements) { - Entry KEY_VALUE_GENERIC_TYPE[] result = new Entry[elements.length]; - int index = 0; - for (Entry KEY_VALUE_GENERIC_TYPE entry : generator.getSamples().asList().subList(0, elements.length)) { - result[index] = new ABSTRACT_MAP.BasicEntryKV_BRACES((CLASS_TYPE) elements[index++], entry.getValue()); - } - return generator.create(result).keySet(); - } - } - - public static class MapValueCollectionGenerator KEY_VALUE_GENERIC_TYPE implements VALUE_TEST_COLLECTION_GENERATOR VALUE_GENERIC_TYPE { - TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE generator; - VALUE_SAMPLE_ELEMENTS VALUE_GENERIC_TYPE samples; - - public MapValueCollectionGenerator(OneSizeTestContainerGenerator, Map.Entry> inner) { - generator = (TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE) inner.getInnerGenerator(); - ObjectSamples samples = generator.getSamples(); - this.samples = new VALUE_SAMPLE_ELEMENTSVALUE_BRACES(samples.e0().ENTRY_VALUE(), samples.e1().ENTRY_VALUE(), samples.e2().ENTRY_VALUE(), samples.e3().ENTRY_VALUE(), samples.e4().ENTRY_VALUE()); - } - - @Override - public VALUE_SAMPLE_ELEMENTS VALUE_GENERIC_TYPE getSamples() { - return samples; - } - - @Override - public VALUE_ITERABLE VALUE_GENERIC_TYPE order(VALUE_LIST VALUE_GENERIC_TYPE insertionOrder) { - ObjectList list = generator.order(generator.getSamples().asList()).pourAsList(); -#if VALUE_OBJECT - insertionOrder.sort(new Comparator() { -#else - insertionOrder.sort(new VALUE_COMPARATOR VALUE_GENERIC_TYPE() { -#endif - @Override - public int compare(VALUE_TYPE key, VALUE_TYPE value) { - return Integer.signum(indexOf(key) - indexOf(value)); - } - - protected int indexOf(VALUE_TYPE entry) { - for(int i = 0,m=list.size();i order(List insertionOrder) { - ObjectList list = generator.order(generator.getSamples().asList()).pourAsList(); - insertionOrder.sort(new Comparator() { - @Override - public int compare(CLASS_VALUE_TYPE key, CLASS_VALUE_TYPE value) { - return Integer.signum(indexOf(key) - indexOf(value)); - } - - protected int indexOf(CLASS_VALUE_TYPE entry) { - for(int i = 0,m=list.size();i> entryObjectComparator(Comparator keyComparator) { - return new Comparator>() { - @Override - public int compare(Map.Entry a, Map.Entry b) { - if(keyComparator == null) { - return COMPAREABLE_TO_KEY(OBJ_TO_KEY(a.getKey()), OBJ_TO_KEY(b.getKey())); - } - return keyComparator.compare(OBJ_TO_KEY(a.getKey()), OBJ_TO_KEY(b.getKey())); - } - }; - } - - public static KEY_VALUE_GENERIC_TYPE Comparator entryComparator(COMPARATOR KEY_GENERIC_TYPE keyComparator) { - return new Comparator() { - @Override - public int compare(Entry KEY_VALUE_GENERIC_TYPE a, Entry KEY_VALUE_GENERIC_TYPE b) { - if(keyComparator == null) { - return COMPAREABLE_TO_KEY(a.ENTRY_KEY(), b.ENTRY_KEY()); - } - return keyComparator.compare(a.ENTRY_KEY(), b.ENTRY_KEY()); - } - }; - } -} +package speiger.src.testers.PACKAGE.impl.maps; + +import java.util.Comparator; +import java.util.List; +import java.util.Map; +#if VALUE_OBJECT +import java.util.Objects; +#endif + +import com.google.common.collect.testing.DerivedCollectionGenerators.Bound; +import com.google.common.collect.testing.OneSizeTestContainerGenerator; + +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.functions.COMPARATOR; +import speiger.src.collections.PACKAGE.collections.ITERABLE; +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.lists.LIST; +#endif +import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.MAP.Entry; +import speiger.src.collections.PACKAGE.maps.interfaces.NAVIGABLE_MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.SORTED_MAP; +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.sets.SET; +import speiger.src.collections.PACKAGE.sets.ORDERED_SET; +#endif +import speiger.src.collections.PACKAGE.sets.SORTED_SET; +import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET; +#if !TYPE_OBJECT +import speiger.src.testers.PACKAGE.generators.TEST_SET_GENERATOR; +#endif +import speiger.src.testers.PACKAGE.generators.TEST_ORDERED_SET_GENERATOR; +import speiger.src.testers.PACKAGE.generators.TEST_SORTED_SET_GENERATOR; +import speiger.src.testers.PACKAGE.generators.TEST_NAVIGABLE_SET_GENERATOR; +import speiger.src.testers.PACKAGE.generators.maps.TEST_MAP_GENERATOR; +import speiger.src.testers.PACKAGE.generators.maps.TEST_SORTED_MAP_GENERATOR; +import speiger.src.testers.PACKAGE.generators.maps.TEST_ORDERED_MAP_GENERATOR; +#if !TYPE_OBJECT +import speiger.src.testers.PACKAGE.utils.SAMPLE_ELEMENTS; +#endif +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; +#if !VALUE_OBJECT && !SAME_TYPE +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERABLE; +import speiger.src.collections.VALUE_PACKAGE.lists.VALUE_LIST; +import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_COMPARATOR; +#endif +import speiger.src.testers.VALUE_PACKAGE.generators.VALUE_TEST_COLLECTION_GENERATOR; +#if !VALUE_OBJECT && !SAME_TYPE +import speiger.src.testers.VALUE_PACKAGE.utils.VALUE_SAMPLE_ELEMENTS; +#endif +import speiger.src.collections.objects.collections.ObjectIterable; +import speiger.src.collections.objects.lists.ObjectArrayList; +import speiger.src.collections.objects.lists.ObjectList; +import speiger.src.collections.objects.sets.ObjectSet; +import speiger.src.collections.objects.sets.ObjectOrderedSet; +import speiger.src.collections.objects.utils.ObjectIterators; +import speiger.src.collections.objects.utils.ObjectLists; +import speiger.src.testers.objects.generators.TestObjectSetGenerator; +#if !TYPE_OBJECT +import speiger.src.testers.objects.generators.TestObjectOrderedSetGenerator; +#endif +import speiger.src.testers.objects.utils.ObjectSamples; + +@SuppressWarnings("javadoc") +public class DERIVED_MAP_GENERATORS { + public static class NavigableMapGenerator KEY_VALUE_GENERIC_TYPE extends SortedMapGenerator KEY_VALUE_GENERIC_TYPE { + public NavigableMapGenerator(TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE parent, Bound to, Bound from) { + super(parent, to, from); + } + + @Override + NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE createSubMap(SORTED_MAP KEY_VALUE_GENERIC_TYPE sortedMap, KEY_TYPE firstExclusive, KEY_TYPE lastExclusive) { + NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map = (NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE) sortedMap; + if (from == Bound.NO_BOUND && to == Bound.INCLUSIVE) { + return map.headMap(lastInclusive, true); + } else if (from == Bound.EXCLUSIVE && to == Bound.NO_BOUND) { + return map.tailMap(firstExclusive, false); + } else if (from == Bound.EXCLUSIVE && to == Bound.EXCLUSIVE) { + return map.subMap(firstExclusive, false, lastExclusive, false); + } else if (from == Bound.EXCLUSIVE && to == Bound.INCLUSIVE) { + return map.subMap(firstExclusive, false, lastInclusive, true); + } else if (from == Bound.INCLUSIVE && to == Bound.INCLUSIVE) { + return map.subMap(firstInclusive, true, lastInclusive, true); + } else { + return (NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE) super.createSubMap(map, firstExclusive, lastExclusive); + } + } + } + + public static class SortedMapGenerator KEY_VALUE_GENERIC_TYPE extends MapGenerator KEY_VALUE_GENERIC_TYPE implements TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE { + TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE parent; + Bound to; + Bound from; + KEY_TYPE firstInclusive; + KEY_TYPE lastInclusive; + Comparator entryComparator; + + public SortedMapGenerator(TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE parent, Bound to, Bound from) { + super(parent); + this.parent = parent; + this.to = to; + this.from = from; + SORTED_MAP KEY_VALUE_GENERIC_TYPE map = parent.create(); + entryComparator = DERIVED_MAP_GENERATORS.entryComparator(map.comparator()); + ObjectList samples = parent.getSamples().asList(); + samples.sort(entryComparator); + firstInclusive = samples.get(0).ENTRY_KEY(); + lastInclusive = samples.get(samples.size() - 1).ENTRY_KEY(); + } + + @Override + public SORTED_MAP KEY_VALUE_GENERIC_TYPE create(Entry KEY_VALUE_GENERIC_TYPE... elements) { + ObjectList entries = new ObjectArrayList<>(); + if (from != Bound.NO_BOUND) { + entries.add(parent.belowSamplesLesser()); + entries.add(parent.belowSamplesGreater()); + } + if (to != Bound.NO_BOUND) { + entries.add(parent.aboveSamplesLesser()); + entries.add(parent.aboveSamplesGreater()); + } + entries.addAll(elements); + return createSubMap(parent.create(entries.toArray(Entry[]::new)), parent.belowSamplesGreater().ENTRY_KEY(), parent.aboveSamplesLesser().ENTRY_KEY()); + } + + SORTED_MAP KEY_VALUE_GENERIC_TYPE createSubMap(SORTED_MAP KEY_VALUE_GENERIC_TYPE map, KEY_TYPE firstExclusive, KEY_TYPE lastExclusive) { + if (from == Bound.NO_BOUND && to == Bound.EXCLUSIVE) { + return map.headMap(lastExclusive); + } else if (from == Bound.INCLUSIVE && to == Bound.NO_BOUND) { + return map.tailMap(firstInclusive); + } else if (from == Bound.INCLUSIVE && to == Bound.EXCLUSIVE) { + return map.subMap(firstInclusive, lastExclusive); + } else { + throw new IllegalArgumentException(); + } + } + + @Override + public Entry KEY_VALUE_GENERIC_TYPE belowSamplesLesser() { + throw new UnsupportedOperationException(); + } + + @Override + public Entry KEY_VALUE_GENERIC_TYPE belowSamplesGreater() { + throw new UnsupportedOperationException(); + } + + @Override + public Entry KEY_VALUE_GENERIC_TYPE aboveSamplesLesser() { + throw new UnsupportedOperationException(); + } + + @Override + public Entry KEY_VALUE_GENERIC_TYPE aboveSamplesGreater() { + throw new UnsupportedOperationException(); + } + } + + public static class DescendingTestMapGenerator KEY_VALUE_GENERIC_TYPE extends MapGenerator KEY_VALUE_GENERIC_TYPE implements TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE + { + TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE parent; + + public DescendingTestMapGenerator(TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE parent) { + super(parent); + this.parent = parent; + } + + @Override + public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE create(Entry KEY_VALUE_GENERIC_TYPE... elements) { + return ((NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE)parent.create(elements)).descendingMap(); + } + + @Override + public Iterable> order(List> insertionOrder) { + ObjectList> values = ObjectIterators.pour(ObjectIterators.wrap(parent.order(insertionOrder).iterator())); + ObjectLists.reverse(values); + return values; + } + + @Override + public ObjectIterable order(ObjectList insertionOrder) { + ObjectList values = parent.order(insertionOrder).pourAsList(); + ObjectLists.reverse(values); + return values; + } + + @Override + public Entry KEY_VALUE_GENERIC_TYPE belowSamplesLesser() { + return parent.aboveSamplesGreater(); + } + + @Override + public Entry KEY_VALUE_GENERIC_TYPE belowSamplesGreater() { + return parent.aboveSamplesLesser(); + } + + @Override + public Entry KEY_VALUE_GENERIC_TYPE aboveSamplesLesser() { + return parent.belowSamplesGreater(); + } + + @Override + public Entry KEY_VALUE_GENERIC_TYPE aboveSamplesGreater() { + return parent.belowSamplesLesser(); + } + } + + public static class MapGenerator KEY_VALUE_GENERIC_TYPE implements TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE + { + TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE parent; + + public MapGenerator(TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE parent) { + this.parent = parent; + } + + @Override + public Iterable> order(List> insertionOrder) { + return parent.order(insertionOrder); + } + + @Override + public ObjectSamples getSamples() { + return parent.getSamples(); + } + + @Override + public ObjectIterable order(ObjectList insertionOrder) { + return parent.order(insertionOrder); + } + + @Override + public MAP KEY_VALUE_GENERIC_TYPE create(Entry KEY_VALUE_GENERIC_TYPE... elements) { + return parent.create(elements); + } + } + + public static GENERIC_KEY_VALUE_BRACES TestObjectSetGenerator entrySetGenerator(OneSizeTestContainerGenerator, Map.Entry> inner) { + if(inner.getInnerGenerator() instanceof TEST_ORDERED_MAP_GENERATOR) { + ObjectSet set = ((TEST_ORDERED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE) inner.getInnerGenerator()).create().ENTRY_SET(); + if(set instanceof ObjectOrderedSet) return new OrderedMapEntrySetGeneratorKV_BRACES(inner); + } + return new MapEntrySetGeneratorKV_BRACES(inner); + } + + public static class OrderedMapEntrySetGenerator KEY_VALUE_GENERIC_TYPE extends MapEntrySetGenerator KEY_VALUE_GENERIC_TYPE implements TestObjectOrderedSetGenerator { + + public OrderedMapEntrySetGenerator(OneSizeTestContainerGenerator, Map.Entry> inner) { + super(inner); + } + + public ObjectOrderedSet create(Object... elements) { + return (ObjectOrderedSet)super.create(elements); + } + } + + public static class MapEntrySetGenerator KEY_VALUE_GENERIC_TYPE implements TestObjectSetGenerator { + TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE generator; + + public MapEntrySetGenerator(OneSizeTestContainerGenerator, Map.Entry> inner) { + generator = (TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE) inner.getInnerGenerator(); + } + + @Override + public ObjectSamples getSamples() { + return generator.getSamples(); + } + + @Override + public ObjectIterable order(ObjectList insertionOrder) { + return generator.order(insertionOrder); + } + + @Override + public Iterable order(List insertionOrder) { + return generator.order(new ObjectArrayList(insertionOrder)); + } + + @Override + public Entry KEY_VALUE_GENERIC_TYPE[] createArray(int length) { + return new Entry[length]; + } + + @Override + public ObjectSet create(Object... elements) { + return generator.create(elements).ENTRY_SET(); + } + } + + public static GENERIC_KEY_VALUE_BRACES TEST_SET_GENERATOR KEY_GENERIC_TYPE keySetGenerator(OneSizeTestContainerGenerator, Map.Entry> inner) { + if (inner.getInnerGenerator() instanceof TEST_SORTED_MAP_GENERATOR) { + SET KEY_GENERIC_TYPE set = ((TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE) inner.getInnerGenerator()).create().keySet(); + if(set instanceof NAVIGABLE_SET) return new MapNavigableKeySetGeneratorKV_BRACES(inner); + if(set instanceof SORTED_SET) return new MapSortedKeySetGeneratorKV_BRACES(inner); + } + if(inner.getInnerGenerator() instanceof TEST_ORDERED_MAP_GENERATOR) { + SET KEY_GENERIC_TYPE set = ((TEST_ORDERED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE) inner.getInnerGenerator()).create().keySet(); + if(set instanceof ORDERED_SET) return new MapOrderedKeySetGeneratorKV_BRACES(inner); + } + return new MapKeySetGeneratorKV_BRACES(inner); + } + + public static class MapNavigableKeySetGenerator KEY_VALUE_GENERIC_TYPE extends MapSortedKeySetGenerator KEY_VALUE_GENERIC_TYPE implements TEST_NAVIGABLE_SET_GENERATOR KEY_GENERIC_TYPE { + public MapNavigableKeySetGenerator(OneSizeTestContainerGenerator, Map.Entry> inner) { + super(inner); + } + +#if !TYPE_OBJECT + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE create(KEY_TYPE... elements) { + return (NAVIGABLE_SET KEY_GENERIC_TYPE) super.create(elements); + } + +#endif + @Override + public NAVIGABLE_SET KEY_GENERIC_TYPE create(Object... elements) { + return (NAVIGABLE_SET KEY_GENERIC_TYPE) super.create(elements); + } + } + + public static class MapSortedKeySetGenerator KEY_VALUE_GENERIC_TYPE extends MapKeySetGenerator KEY_VALUE_GENERIC_TYPE implements TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE { + TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE generator; + + public MapSortedKeySetGenerator(OneSizeTestContainerGenerator, Map.Entry> inner) { + super(inner); + generator = (TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE) inner.getInnerGenerator(); + } + +#if !TYPE_OBJECT + @Override + public SORTED_SET KEY_GENERIC_TYPE create(KEY_TYPE... elements) { + return (SORTED_SET KEY_GENERIC_TYPE) super.create(elements); + } + +#endif + @Override + public SORTED_SET KEY_GENERIC_TYPE create(Object... elements) { + return (SORTED_SET KEY_GENERIC_TYPE) super.create(elements); + } + + @Override + public KEY_TYPE belowSamplesLesser() { + return generator.belowSamplesLesser().ENTRY_KEY(); + } + + @Override + public KEY_TYPE belowSamplesGreater() { + return generator.belowSamplesGreater().ENTRY_KEY(); + } + + @Override + public KEY_TYPE aboveSamplesLesser() { + return generator.aboveSamplesLesser().ENTRY_KEY(); + } + + @Override + public KEY_TYPE aboveSamplesGreater() { + return generator.aboveSamplesGreater().ENTRY_KEY(); + } + } + + public static class MapOrderedKeySetGenerator KEY_VALUE_GENERIC_TYPE extends MapKeySetGenerator KEY_VALUE_GENERIC_TYPE implements TEST_ORDERED_SET_GENERATOR KEY_GENERIC_TYPE { + + public MapOrderedKeySetGenerator(OneSizeTestContainerGenerator, Map.Entry> inner) { + super(inner); + } + +#if !TYPE_OBJECT + @Override + public ORDERED_SET KEY_GENERIC_TYPE create(KEY_TYPE... elements) { + return (ORDERED_SET KEY_GENERIC_TYPE) super.create(elements); + } + +#endif + @Override + public ORDERED_SET KEY_GENERIC_TYPE create(Object... elements) { + return (ORDERED_SET KEY_GENERIC_TYPE) super.create(elements); + } + } + + public static class MapKeySetGenerator KEY_VALUE_GENERIC_TYPE implements TEST_SET_GENERATOR KEY_GENERIC_TYPE { + TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE generator; + SAMPLE_ELEMENTS KEY_GENERIC_TYPE samples; + + public MapKeySetGenerator(OneSizeTestContainerGenerator, Map.Entry> inner) { + generator = (TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE) inner.getInnerGenerator(); + ObjectSamples samples = generator.getSamples(); + this.samples = new SAMPLE_ELEMENTSBRACES(samples.e0().ENTRY_KEY(), samples.e1().ENTRY_KEY(), samples.e2().ENTRY_KEY(), samples.e3().ENTRY_KEY(), samples.e4().ENTRY_KEY()); + } + + @Override + public SAMPLE_ELEMENTS KEY_GENERIC_TYPE getSamples() { + return samples; + } + + @Override + public ITERABLE KEY_GENERIC_TYPE order(LIST KEY_GENERIC_TYPE insertionOrder) { + VALUE_TYPE value = generator.getSamples().e0().ENTRY_VALUE(); + ObjectList entries = new ObjectArrayList<>(); + for (KEY_TYPE key : insertionOrder) { + entries.add(new ABSTRACT_MAP.BasicEntryKV_BRACES(key, value)); + } + LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); + for (Entry KEY_VALUE_GENERIC_TYPE entry : generator.order(entries)) { + list.add(entry.ENTRY_KEY()); + } + return list; + } + + @Override + public Iterable order(List insertionOrder) { + VALUE_TYPE value = generator.getSamples().e0().ENTRY_VALUE(); + ObjectList entries = new ObjectArrayList<>(); + for (KEY_TYPE key : insertionOrder) { + entries.add(new ABSTRACT_MAP.BasicEntryKV_BRACES(key, value)); + } + LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); + for (Entry KEY_VALUE_GENERIC_TYPE entry : generator.order(entries)) { + list.add(entry.ENTRY_KEY()); + } + return list; + } + +#if !TYPE_OBJECT + @Override + public SET KEY_GENERIC_TYPE create(KEY_TYPE... elements) { + Entry KEY_VALUE_GENERIC_TYPE[] result = new Entry[elements.length]; + int index = 0; + for (Entry KEY_VALUE_GENERIC_TYPE entry : generator.getSamples().asList().subList(0, elements.length)) { + result[index] = new ABSTRACT_MAP.BasicEntryKV_BRACES(elements[index++], entry.ENTRY_VALUE()); + } + return generator.create(result).keySet(); + } + +#endif + @Override + public SET KEY_GENERIC_TYPE create(Object... elements) { + Entry KEY_VALUE_GENERIC_TYPE[] result = new Entry[elements.length]; + int index = 0; + for (Entry KEY_VALUE_GENERIC_TYPE entry : generator.getSamples().asList().subList(0, elements.length)) { + result[index] = new ABSTRACT_MAP.BasicEntryKV_BRACES((CLASS_TYPE) elements[index++], entry.getValue()); + } + return generator.create(result).keySet(); + } + } + + public static class MapValueCollectionGenerator KEY_VALUE_GENERIC_TYPE implements VALUE_TEST_COLLECTION_GENERATOR VALUE_GENERIC_TYPE { + TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE generator; + VALUE_SAMPLE_ELEMENTS VALUE_GENERIC_TYPE samples; + + public MapValueCollectionGenerator(OneSizeTestContainerGenerator, Map.Entry> inner) { + generator = (TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE) inner.getInnerGenerator(); + ObjectSamples samples = generator.getSamples(); + this.samples = new VALUE_SAMPLE_ELEMENTSVALUE_BRACES(samples.e0().ENTRY_VALUE(), samples.e1().ENTRY_VALUE(), samples.e2().ENTRY_VALUE(), samples.e3().ENTRY_VALUE(), samples.e4().ENTRY_VALUE()); + } + + @Override + public VALUE_SAMPLE_ELEMENTS VALUE_GENERIC_TYPE getSamples() { + return samples; + } + + @Override + public VALUE_ITERABLE VALUE_GENERIC_TYPE order(VALUE_LIST VALUE_GENERIC_TYPE insertionOrder) { + ObjectList list = generator.order(generator.getSamples().asList()).pourAsList(); +#if VALUE_OBJECT + insertionOrder.sort(new Comparator() { +#else + insertionOrder.sort(new VALUE_COMPARATOR VALUE_GENERIC_TYPE() { +#endif + @Override + public int compare(VALUE_TYPE key, VALUE_TYPE value) { + return Integer.signum(indexOf(key) - indexOf(value)); + } + + protected int indexOf(VALUE_TYPE entry) { + for(int i = 0,m=list.size();i order(List insertionOrder) { + ObjectList list = generator.order(generator.getSamples().asList()).pourAsList(); + insertionOrder.sort(new Comparator() { + @Override + public int compare(CLASS_VALUE_TYPE key, CLASS_VALUE_TYPE value) { + return Integer.signum(indexOf(key) - indexOf(value)); + } + + protected int indexOf(CLASS_VALUE_TYPE entry) { + for(int i = 0,m=list.size();i> entryObjectComparator(Comparator keyComparator) { + return new Comparator>() { + @Override + public int compare(Map.Entry a, Map.Entry b) { + if(keyComparator == null) { + return COMPAREABLE_TO_KEY(OBJ_TO_KEY(a.getKey()), OBJ_TO_KEY(b.getKey())); + } + return keyComparator.compare(OBJ_TO_KEY(a.getKey()), OBJ_TO_KEY(b.getKey())); + } + }; + } + + public static KEY_VALUE_GENERIC_TYPE Comparator entryComparator(COMPARATOR KEY_GENERIC_TYPE keyComparator) { + return new Comparator() { + @Override + public int compare(Entry KEY_VALUE_GENERIC_TYPE a, Entry KEY_VALUE_GENERIC_TYPE b) { + if(keyComparator == null) { + return COMPAREABLE_TO_KEY(a.ENTRY_KEY(), b.ENTRY_KEY()); + } + return keyComparator.compare(a.ENTRY_KEY(), b.ENTRY_KEY()); + } + }; + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/impl/maps/MapConstructorTests.template b/src/builder/resources/speiger/assets/testers/templates/impl/maps/MapConstructorTests.template index 18dc841..82217fb 100644 --- a/src/builder/resources/speiger/assets/testers/templates/impl/maps/MapConstructorTests.template +++ b/src/builder/resources/speiger/assets/testers/templates/impl/maps/MapConstructorTests.template @@ -1,934 +1,934 @@ -package speiger.src.testers.PACKAGE.impl.maps; - -#if TYPE_OBJECT || VALUE_OBJECT -import java.util.Arrays; -#endif -#if TYPE_OBJECT -import java.util.Objects; -import java.util.Comparator; -#endif - -#if TYPE_OBJECT -import org.junit.Assert; -#endif -import org.junit.Ignore; -import org.junit.Test; - -#if TYPE_OBJECT -import com.google.common.collect.testing.AnEnum; -#endif - -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.collections.PACKAGE.maps.impl.hash.HASH_MAP; -import speiger.src.collections.PACKAGE.maps.impl.hash.LINKED_HASH_MAP; -import speiger.src.collections.PACKAGE.maps.impl.customHash.CUSTOM_HASH_MAP; -import speiger.src.collections.PACKAGE.maps.impl.customHash.LINKED_CUSTOM_HASH_MAP; -import speiger.src.collections.PACKAGE.maps.impl.concurrent.CONCURRENT_HASH_MAP; -#if TYPE_OBJECT -import speiger.src.collections.PACKAGE.maps.impl.misc.ENUM_MAP; -import speiger.src.collections.PACKAGE.maps.impl.misc.LINKED_ENUM_MAP; -#endif - -import speiger.src.collections.PACKAGE.maps.impl.tree.RB_TREE_MAP; -import speiger.src.collections.PACKAGE.maps.impl.tree.AVL_TREE_MAP; -import speiger.src.collections.PACKAGE.utils.STRATEGY; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester; -#if TYPE_OBJECT || VALUE_OBJECT -import speiger.src.collections.objects.utils.StringSortTest; -#endif - -@Ignore -@SuppressWarnings("javadoc") -public class MAP_CONSTRUCTOR_TESTS -{ - public static class HashMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE - { - public HashMap() { - setSimpleConstructor(MAP.builder()::map); - setSizeConstructor(MAP.builder()::map); - setPArrayConstructor(MAP.builder()::map); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor(MAP.builder()::map); -#endif - setPMapConstructor(MAP.builder()::map); - setMapConstructor(MAP.builder()::map); - } - - @Test - public void testWrongLoadFactorSize() { - setSizeConstructor(T -> new HASH_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, 0F)); - try { - testSizeConstructor_smallSize(); - fail("A Constructor using a 0 LoadFactor should error"); - } catch(IllegalStateException e) { - } - - setSizeConstructor(T -> new HASH_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, 1F)); - try { - testSizeConstructor_smallSize(); - fail("A Constructor using a 1 LoadFactor should error"); - } catch(IllegalStateException e) { - } - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } - -#endif -#if VALUE_OBJECT - @Override - protected String[] createValueElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); - } - -#endif - } - - public static class LinkedHashMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE - { - public LinkedHashMap() { - setSimpleConstructor(MAP.builder()::linkedMap); - setSizeConstructor(MAP.builder()::linkedMap); - setPArrayConstructor(MAP.builder()::linkedMap); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor(MAP.builder()::linkedMap); -#endif - setPMapConstructor(MAP.builder()::linkedMap); - setMapConstructor(MAP.builder()::linkedMap); - } - - @Test - public void testWrongLoadFactorSize() { - setSizeConstructor(T -> new LINKED_HASH_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, 0F)); - try { - testSizeConstructor_smallSize(); - fail("A Constructor using a 0 LoadFactor should error"); - } catch(IllegalStateException e) { - } - - setSizeConstructor(T -> new LINKED_HASH_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, 1F)); - try { - testSizeConstructor_smallSize(); - fail("A Constructor using a 1 LoadFactor should error"); - } catch(IllegalStateException e) { - } - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } - -#endif -#if VALUE_OBJECT - @Override - protected String[] createValueElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); - } - -#endif - } - -#if TYPE_OBJECT -#if VALUE_OBJECT - public static class EnumMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester -#else - public static class EnumMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester -#endif - { - public EnumMap() { - setSimpleConstructor(() -> new ENUM_MAP<>(AnEnum.class)); - setPArrayConstructor(ENUM_MAP::new); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor(ENUM_MAP::new); -#endif - setPMapConstructor(ENUM_MAP::new); - setMapConstructor(ENUM_MAP::new); - } - - @Test - public void testEnumMapConstructor() { - if(pMapConstructor == null) return; - Assert.assertTrue(pMapConstructor.apply(new ENUM_MAP<>(new LINKED_HASH_MAPKV_BRACES(keys, values))) != null); - } - - @Test - public void testObjectEnumMapConstructor() { - if(pMapConstructor == null) return; - Assert.assertTrue(mapConstructor.apply(new ENUM_MAP<>(new LINKED_HASH_MAPKV_BRACES(keys, values))) != null); - } - - @Override - protected AnEnum[] createKeyElements() { - return AnEnum.values(); - } - -#if VALUE_OBJECT - @Override - protected String[] createValueElements() { - return Arrays.copyOf(StringSortTest.NAMES, AnEnum.values().length); - } -#else - @Override - protected int getSize() { - return AnEnum.values().length; - } -#endif - } - -#if VALUE_OBJECT - public static class LinkedEnumMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester -#else - public static class LinkedEnumMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester -#endif - { - public LinkedEnumMap() { - setSimpleConstructor(() -> new LINKED_ENUM_MAP<>(AnEnum.class)); - setPArrayConstructor(LINKED_ENUM_MAP::new); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor(LINKED_ENUM_MAP::new); -#endif - setPMapConstructor(LINKED_ENUM_MAP::new); - setMapConstructor(LINKED_ENUM_MAP::new); - } - - @Test - public void testEnumMapConstructor() { - if(pMapConstructor == null) return; - Assert.assertTrue(pMapConstructor.apply(new LINKED_ENUM_MAP<>(new LINKED_HASH_MAPKV_BRACES(keys, values))) != null); - Assert.assertTrue(pMapConstructor.apply(new ENUM_MAP<>(new LINKED_HASH_MAPKV_BRACES(keys, values))) != null); - } - - @Test - public void testObjectEnumMapConstructor() { - if(mapConstructor == null) return; - Assert.assertTrue(mapConstructor.apply(new LINKED_ENUM_MAP<>(new LINKED_HASH_MAPKV_BRACES(keys, values))) != null); - Assert.assertTrue(mapConstructor.apply(new ENUM_MAP<>(new LINKED_HASH_MAPKV_BRACES(keys, values))) != null); - } - - @Override - protected AnEnum[] createKeyElements() { - return AnEnum.values(); - } - -#if VALUE_OBJECT - @Override - protected String[] createValueElements() { - return Arrays.copyOf(StringSortTest.NAMES, AnEnum.values().length); - } -#else - @Override - protected int getSize() { - return AnEnum.values().length; - } -#endif - } - -#endif - public static class CustomHashMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE - { - public CustomHashMap() { - setSimpleConstructor(() -> MAP.builder().customMap(HashStrategy.INSTANCE)); - setSizeConstructor(T -> MAP.builder().customMap(T, HashStrategy.INSTANCE)); - setPArrayConstructor((K, V) -> MAP.builder().customMap(K, V, HashStrategy.INSTANCE)); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor((K, V) -> MAP.builder().customMap(K, V, HashStrategy.INSTANCE)); -#endif - setPMapConstructor(T -> MAP.builder().customMap(T, HashStrategy.INSTANCE)); - setMapConstructor(T -> MAP.builder().customMap(T, HashStrategy.INSTANCE)); - } - - @Test - public void testWrongLoadFactorSize() { - setSizeConstructor(T -> new CUSTOM_HASH_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, 0F, HashStrategy.INSTANCE)); - try { - testSizeConstructor_smallSize(); - fail("A Constructor using a 0 LoadFactor should error"); - } catch(IllegalStateException e) { - } - - setSizeConstructor(T -> new CUSTOM_HASH_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, 1F, HashStrategy.INSTANCE)); - try { - testSizeConstructor_smallSize(); - fail("A Constructor using a 1 LoadFactor should error"); - } catch(IllegalStateException e) { - } - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } - -#endif -#if VALUE_OBJECT - @Override - protected String[] createValueElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); - } - -#endif - } - - public static class LinkedCustomHashMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE - { - public LinkedCustomHashMap() { - setSimpleConstructor(() -> MAP.builder().customLinkedMap(HashStrategy.INSTANCE)); - setSizeConstructor(T -> MAP.builder().customLinkedMap(T, HashStrategy.INSTANCE)); - setPArrayConstructor((K, V) -> MAP.builder().customLinkedMap(K, V, HashStrategy.INSTANCE)); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor((K, V) -> MAP.builder().customLinkedMap(K, V, HashStrategy.INSTANCE)); -#endif - setPMapConstructor(T -> MAP.builder().customLinkedMap(T, HashStrategy.INSTANCE)); - setMapConstructor(T -> MAP.builder().customLinkedMap(T, HashStrategy.INSTANCE)); - } - - @Test - public void testWrongLoadFactorSize() { - setSizeConstructor(T -> new LINKED_CUSTOM_HASH_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, 0F, HashStrategy.INSTANCE)); - try { - testSizeConstructor_smallSize(); - fail("A Constructor using a 0 LoadFactor should error"); - } catch(IllegalStateException e) { - } - - setSizeConstructor(T -> new LINKED_CUSTOM_HASH_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, 1F, HashStrategy.INSTANCE)); - try { - testSizeConstructor_smallSize(); - fail("A Constructor using a 1 LoadFactor should error"); - } catch(IllegalStateException e) { - } - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } - -#endif -#if VALUE_OBJECT - @Override - protected String[] createValueElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); - } - -#endif - } - - public static class ImmutableHashMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE - { - public ImmutableHashMap() { - setPArrayConstructor(MAP.builder()::immutable); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor(MAP.builder()::immutable); -#endif - setPMapConstructor(MAP.builder()::immutable); - setMapConstructor(MAP.builder()::immutable); - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } - -#endif -#if VALUE_OBJECT - @Override - protected String[] createValueElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); - } - -#endif - } - - public static class ConcurrentHashMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE - { - public ConcurrentHashMap() { - setSimpleConstructor(CONCURRENT_HASH_MAP::new); - setSizeConstructor(CONCURRENT_HASH_MAP::new); - setPArrayConstructor(CONCURRENT_HASH_MAP::new); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor(CONCURRENT_HASH_MAP::new); -#endif - setPMapConstructor(CONCURRENT_HASH_MAP::new); - setMapConstructor(CONCURRENT_HASH_MAP::new); - } - - @Test - public void testWrongLoadFactorSize() { - setSizeConstructor(T -> new CONCURRENT_HASH_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, 0F)); - try { - testSizeConstructor_smallSize(); - fail("A Constructor using a 0 LoadFactor should error"); - } catch(IllegalStateException e) { - } - - setSizeConstructor(T -> new CONCURRENT_HASH_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, 1F)); - try { - testSizeConstructor_smallSize(); - fail("A Constructor using a 1 LoadFactor should error"); - } catch(IllegalStateException e) { - } - } - - @Test - public void testWrongConcurrency() { - setSizeConstructor(T -> new CONCURRENT_HASH_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, 0)); - try { - testSizeConstructor_smallSize(); - fail("A Constructor using a 0 Concurrency should error"); - } catch(IllegalStateException e) { - } - - setSizeConstructor(T -> new CONCURRENT_HASH_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, Integer.MAX_VALUE)); - try { - testSizeConstructor_smallSize(); - fail("A Constructor using a 65536 or larger Concurrency should error"); - } catch(IllegalStateException e) { - } - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } - -#endif -#if VALUE_OBJECT - @Override - protected String[] createValueElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); - } - -#endif - } - - public static class ArrayMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE - { - public ArrayMap() { - setSimpleConstructor(MAP.builder()::arrayMap); - setSizeConstructor(MAP.builder()::arrayMap); - setPArrayConstructor(MAP.builder()::arrayMap); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor(MAP.builder()::arrayMap); -#endif - setPMapConstructor(MAP.builder()::arrayMap); - setMapConstructor(MAP.builder()::arrayMap); - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } - -#endif -#if VALUE_OBJECT - @Override - protected String[] createValueElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); - } - -#endif - } - - public static class RBTreeMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE - { - public RBTreeMap() { - setSimpleConstructor(MAP.builder()::rbTreeMap); - setPArrayConstructor(RB_TREE_MAP::new); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor(RB_TREE_MAP::new); -#endif - setPMapConstructor(RB_TREE_MAP::new); - setMapConstructor(RB_TREE_MAP::new); - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } - -#endif -#if VALUE_OBJECT - @Override - protected String[] createValueElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); - } - -#endif - } - - public static class RBTreeMapComparator extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE - { - public RBTreeMapComparator() { -#if TYPE_OBJECT - setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPErbTreeMap(Comparator.naturalOrder())); - setPArrayConstructor((K, V) -> MAP.builder().rbTreeMap(K, V, Comparator.naturalOrder())); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor((K, V) -> MAP.builder().rbTreeMap(K, V, Comparator.naturalOrder())); -#endif - setPMapConstructor(T -> MAP.builder().rbTreeMap(T, Comparator.naturalOrder())); - setMapConstructor(T -> MAP.builder().rbTreeMap(T, Comparator.naturalOrder())); -#else - setSimpleConstructor(() -> MAP.builder().rbTreeMap(CLASS_TYPE::compare)); - setPArrayConstructor((K, V) -> MAP.builder().rbTreeMap(K, V, CLASS_TYPE::compare)); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor((K, V) -> MAP.builder().rbTreeMap(K, V, CLASS_TYPE::compare)); -#endif - setPMapConstructor(T -> MAP.builder().rbTreeMap(T, CLASS_TYPE::compare)); - setMapConstructor(T -> MAP.builder().rbTreeMap(T, CLASS_TYPE::compare)); -#endif - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } - -#endif -#if VALUE_OBJECT - @Override - protected String[] createValueElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); - } - -#endif - } - - public static class AVLTreeMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE - { - public AVLTreeMap() { - setSimpleConstructor(MAP.builder()::avlTreeMap); - setPArrayConstructor(AVL_TREE_MAP::new); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor(AVL_TREE_MAP::new); -#endif - setPMapConstructor(AVL_TREE_MAP::new); - setMapConstructor(AVL_TREE_MAP::new); - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } - -#endif -#if VALUE_OBJECT - @Override - protected String[] createValueElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); - } - -#endif - } - - public static class AVLTreeMapComparator extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE - { - public AVLTreeMapComparator() { -#if TYPE_OBJECT - setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEavlTreeMap(Comparator.naturalOrder())); - setPArrayConstructor((K, V) -> MAP.builder().avlTreeMap(K, V, Comparator.naturalOrder())); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor((K, V) -> MAP.builder().avlTreeMap(K, V, Comparator.naturalOrder())); -#endif - setPMapConstructor(T -> MAP.builder().avlTreeMap(T, Comparator.naturalOrder())); - setMapConstructor(T -> MAP.builder().avlTreeMap(T, Comparator.naturalOrder())); -#else - setSimpleConstructor(() -> MAP.builder().avlTreeMap(CLASS_TYPE::compare)); - setPArrayConstructor((K, V) -> MAP.builder().avlTreeMap(K, V, CLASS_TYPE::compare)); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor((K, V) -> MAP.builder().avlTreeMap(K, V, CLASS_TYPE::compare)); -#endif - setPMapConstructor(T -> MAP.builder().avlTreeMap(T, CLASS_TYPE::compare)); - setMapConstructor(T -> MAP.builder().avlTreeMap(T, CLASS_TYPE::compare)); -#endif - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } - -#endif -#if VALUE_OBJECT - @Override - protected String[] createValueElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); - } - -#endif - } - - private static class HashStrategy implements STRATEGY KEY_STRING_GENERIC_TYPE { - static final HashStrategy INSTANCE = new HashStrategy(); - @Override - public int hashCode(KEY_STRING_TYPE o) { return KEY_TO_HASH(o); } - @Override - public boolean equals(KEY_STRING_TYPE key, KEY_STRING_TYPE value) { return KEY_EQUALS(key, value); } - } - - public static class HashMapBuilder extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE - { - public HashMapBuilder() { - setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().map()); - setSizeConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(T).map()); - setPArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).map()); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).map()); -#endif - setPMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).map()); - setMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).map()); - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } - -#endif -#if VALUE_OBJECT - @Override - protected String[] createValueElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); - } - -#endif - } - - public static class LinkedHashMapBuilder extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE - { - public LinkedHashMapBuilder() { - setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().linkedMap()); - setSizeConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(T).linkedMap()); - setPArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).linkedMap()); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).linkedMap()); -#endif - setPMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).linkedMap()); - setMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).linkedMap()); - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } - -#endif -#if VALUE_OBJECT - @Override - protected String[] createValueElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); - } - -#endif - } - - public static class CustomHashMapBuilder extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE - { - public CustomHashMapBuilder() { - setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().customMap(HashStrategy.INSTANCE)); - setSizeConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(T).customMap(HashStrategy.INSTANCE)); - setPArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).customMap(HashStrategy.INSTANCE)); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).customMap(HashStrategy.INSTANCE)); -#endif - setPMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).customMap(HashStrategy.INSTANCE)); - setMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).customMap(HashStrategy.INSTANCE)); - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } - -#endif -#if VALUE_OBJECT - @Override - protected String[] createValueElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); - } - -#endif - } - - public static class LinkedCustomHashMapBuilder extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE - { - public LinkedCustomHashMapBuilder() { - setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().customLinkedMap(HashStrategy.INSTANCE)); - setSizeConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(T).customLinkedMap(HashStrategy.INSTANCE)); - setPArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).customLinkedMap(HashStrategy.INSTANCE)); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).customLinkedMap(HashStrategy.INSTANCE)); -#endif - setPMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).customLinkedMap(HashStrategy.INSTANCE)); - setMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).customLinkedMap(HashStrategy.INSTANCE)); - - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } - -#endif -#if VALUE_OBJECT - @Override - protected String[] createValueElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); - } - -#endif - } - - public static class ImmutableHashMapBuilder extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE - { - public ImmutableHashMapBuilder() { - setPArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).immutable()); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).immutable()); -#endif - setPMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).immutable()); - setMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).immutable()); - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } - -#endif -#if VALUE_OBJECT - @Override - protected String[] createValueElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); - } - -#endif - } - - public static class ConcurrentHashMapBuilder extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE - { - public ConcurrentHashMapBuilder() { - setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().concurrentMap()); - setSizeConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(T).concurrentMap()); - setPArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).concurrentMap()); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).concurrentMap()); -#endif - setPMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).concurrentMap()); - setMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).concurrentMap()); - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } - -#endif -#if VALUE_OBJECT - @Override - protected String[] createValueElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); - } - -#endif - } - - public static class ArrayMapBuilder extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE - { - public ArrayMapBuilder() { - setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().arrayMap()); - setSizeConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(T).arrayMap()); - setPArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).arrayMap()); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).arrayMap()); -#endif - setPMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).arrayMap()); - setMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).arrayMap()); - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } - -#endif -#if VALUE_OBJECT - @Override - protected String[] createValueElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); - } - -#endif - } - - public static class RBTreeMapBuilder extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE - { - public RBTreeMapBuilder() { - setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().rbTreeMap()); - setPArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).rbTreeMap()); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).rbTreeMap()); -#endif - setPMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).rbTreeMap()); - setMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).rbTreeMap()); - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } - -#endif -#if VALUE_OBJECT - @Override - protected String[] createValueElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); - } - -#endif - } - - public static class RBTreeMapComparatorBuilder extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE - { - public RBTreeMapComparatorBuilder() { -#if TYPE_OBJECT - setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().rbTreeMap(Comparator.naturalOrder())); - setPArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).rbTreeMap(Comparator.naturalOrder())); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).rbTreeMap(Comparator.naturalOrder())); -#endif - setPMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).rbTreeMap(Comparator.naturalOrder())); - setMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).rbTreeMap(Comparator.naturalOrder())); -#else - setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().rbTreeMap(CLASS_TYPE::compare)); - setPArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).rbTreeMap(CLASS_TYPE::compare)); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).rbTreeMap(CLASS_TYPE::compare)); -#endif - setPMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).rbTreeMap(CLASS_TYPE::compare)); - setMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).rbTreeMap(CLASS_TYPE::compare)); -#endif - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } - -#endif -#if VALUE_OBJECT - @Override - protected String[] createValueElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); - } - -#endif - } - - public static class AVLTreeMapBuilder extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE - { - public AVLTreeMapBuilder() { - setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().avlTreeMap()); - setPArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).avlTreeMap()); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).avlTreeMap()); -#endif - setPMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).avlTreeMap()); - setMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).avlTreeMap()); - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } - -#endif -#if VALUE_OBJECT - @Override - protected String[] createValueElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); - } - -#endif - } - - public static class AVLTreeMapComparatorBuilder extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE - { - public AVLTreeMapComparatorBuilder() { -#if TYPE_OBJECT - setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().avlTreeMap(Comparator.naturalOrder())); - setPArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).avlTreeMap(Comparator.naturalOrder())); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).avlTreeMap(Comparator.naturalOrder())); -#endif - setPMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).avlTreeMap(Comparator.naturalOrder())); - setMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).avlTreeMap(Comparator.naturalOrder())); -#else - setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().avlTreeMap(CLASS_TYPE::compare)); - setPArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).avlTreeMap(CLASS_TYPE::compare)); -#if !TYPE_OBJECT || !VALUE_OBJECT - setArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).avlTreeMap(CLASS_TYPE::compare)); -#endif - setPMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).avlTreeMap(CLASS_TYPE::compare)); - setMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).avlTreeMap(CLASS_TYPE::compare)); -#endif - } - -#if TYPE_OBJECT - @Override - protected String[] createKeyElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); - } - -#endif -#if VALUE_OBJECT - @Override - protected String[] createValueElements() { - return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); - } - -#endif - } - - private static MAP.BuilderCache KEY_VALUE_STRING_GENERIC_TYPE putAll(MAP.BuilderCache KEY_VALUE_STRING_GENERIC_TYPE cache, KEY_STRING_TYPE[] keys, VALUE_STRING_TYPE[] values) { - if(keys.length != values.length) throw new IllegalStateException("Keys & Values lengths must match"); - for(int i = 0;i new HASH_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, 0F)); + try { + testSizeConstructor_smallSize(); + fail("A Constructor using a 0 LoadFactor should error"); + } catch(IllegalStateException e) { + } + + setSizeConstructor(T -> new HASH_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, 1F)); + try { + testSizeConstructor_smallSize(); + fail("A Constructor using a 1 LoadFactor should error"); + } catch(IllegalStateException e) { + } + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } + +#endif +#if VALUE_OBJECT + @Override + protected String[] createValueElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); + } + +#endif + } + + public static class LinkedHashMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE + { + public LinkedHashMap() { + setSimpleConstructor(MAP.builder()::linkedMap); + setSizeConstructor(MAP.builder()::linkedMap); + setPArrayConstructor(MAP.builder()::linkedMap); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor(MAP.builder()::linkedMap); +#endif + setPMapConstructor(MAP.builder()::linkedMap); + setMapConstructor(MAP.builder()::linkedMap); + } + + @Test + public void testWrongLoadFactorSize() { + setSizeConstructor(T -> new LINKED_HASH_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, 0F)); + try { + testSizeConstructor_smallSize(); + fail("A Constructor using a 0 LoadFactor should error"); + } catch(IllegalStateException e) { + } + + setSizeConstructor(T -> new LINKED_HASH_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, 1F)); + try { + testSizeConstructor_smallSize(); + fail("A Constructor using a 1 LoadFactor should error"); + } catch(IllegalStateException e) { + } + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } + +#endif +#if VALUE_OBJECT + @Override + protected String[] createValueElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); + } + +#endif + } + +#if TYPE_OBJECT +#if VALUE_OBJECT + public static class EnumMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester +#else + public static class EnumMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester +#endif + { + public EnumMap() { + setSimpleConstructor(() -> new ENUM_MAP<>(AnEnum.class)); + setPArrayConstructor(ENUM_MAP::new); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor(ENUM_MAP::new); +#endif + setPMapConstructor(ENUM_MAP::new); + setMapConstructor(ENUM_MAP::new); + } + + @Test + public void testEnumMapConstructor() { + if(pMapConstructor == null) return; + Assert.assertTrue(pMapConstructor.apply(new ENUM_MAP<>(new LINKED_HASH_MAPKV_BRACES(keys, values))) != null); + } + + @Test + public void testObjectEnumMapConstructor() { + if(pMapConstructor == null) return; + Assert.assertTrue(mapConstructor.apply(new ENUM_MAP<>(new LINKED_HASH_MAPKV_BRACES(keys, values))) != null); + } + + @Override + protected AnEnum[] createKeyElements() { + return AnEnum.values(); + } + +#if VALUE_OBJECT + @Override + protected String[] createValueElements() { + return Arrays.copyOf(StringSortTest.NAMES, AnEnum.values().length); + } +#else + @Override + protected int getSize() { + return AnEnum.values().length; + } +#endif + } + +#if VALUE_OBJECT + public static class LinkedEnumMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester +#else + public static class LinkedEnumMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester +#endif + { + public LinkedEnumMap() { + setSimpleConstructor(() -> new LINKED_ENUM_MAP<>(AnEnum.class)); + setPArrayConstructor(LINKED_ENUM_MAP::new); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor(LINKED_ENUM_MAP::new); +#endif + setPMapConstructor(LINKED_ENUM_MAP::new); + setMapConstructor(LINKED_ENUM_MAP::new); + } + + @Test + public void testEnumMapConstructor() { + if(pMapConstructor == null) return; + Assert.assertTrue(pMapConstructor.apply(new LINKED_ENUM_MAP<>(new LINKED_HASH_MAPKV_BRACES(keys, values))) != null); + Assert.assertTrue(pMapConstructor.apply(new ENUM_MAP<>(new LINKED_HASH_MAPKV_BRACES(keys, values))) != null); + } + + @Test + public void testObjectEnumMapConstructor() { + if(mapConstructor == null) return; + Assert.assertTrue(mapConstructor.apply(new LINKED_ENUM_MAP<>(new LINKED_HASH_MAPKV_BRACES(keys, values))) != null); + Assert.assertTrue(mapConstructor.apply(new ENUM_MAP<>(new LINKED_HASH_MAPKV_BRACES(keys, values))) != null); + } + + @Override + protected AnEnum[] createKeyElements() { + return AnEnum.values(); + } + +#if VALUE_OBJECT + @Override + protected String[] createValueElements() { + return Arrays.copyOf(StringSortTest.NAMES, AnEnum.values().length); + } +#else + @Override + protected int getSize() { + return AnEnum.values().length; + } +#endif + } + +#endif + public static class CustomHashMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE + { + public CustomHashMap() { + setSimpleConstructor(() -> MAP.builder().customMap(HashStrategy.INSTANCE)); + setSizeConstructor(T -> MAP.builder().customMap(T, HashStrategy.INSTANCE)); + setPArrayConstructor((K, V) -> MAP.builder().customMap(K, V, HashStrategy.INSTANCE)); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor((K, V) -> MAP.builder().customMap(K, V, HashStrategy.INSTANCE)); +#endif + setPMapConstructor(T -> MAP.builder().customMap(T, HashStrategy.INSTANCE)); + setMapConstructor(T -> MAP.builder().customMap(T, HashStrategy.INSTANCE)); + } + + @Test + public void testWrongLoadFactorSize() { + setSizeConstructor(T -> new CUSTOM_HASH_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, 0F, HashStrategy.INSTANCE)); + try { + testSizeConstructor_smallSize(); + fail("A Constructor using a 0 LoadFactor should error"); + } catch(IllegalStateException e) { + } + + setSizeConstructor(T -> new CUSTOM_HASH_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, 1F, HashStrategy.INSTANCE)); + try { + testSizeConstructor_smallSize(); + fail("A Constructor using a 1 LoadFactor should error"); + } catch(IllegalStateException e) { + } + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } + +#endif +#if VALUE_OBJECT + @Override + protected String[] createValueElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); + } + +#endif + } + + public static class LinkedCustomHashMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE + { + public LinkedCustomHashMap() { + setSimpleConstructor(() -> MAP.builder().customLinkedMap(HashStrategy.INSTANCE)); + setSizeConstructor(T -> MAP.builder().customLinkedMap(T, HashStrategy.INSTANCE)); + setPArrayConstructor((K, V) -> MAP.builder().customLinkedMap(K, V, HashStrategy.INSTANCE)); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor((K, V) -> MAP.builder().customLinkedMap(K, V, HashStrategy.INSTANCE)); +#endif + setPMapConstructor(T -> MAP.builder().customLinkedMap(T, HashStrategy.INSTANCE)); + setMapConstructor(T -> MAP.builder().customLinkedMap(T, HashStrategy.INSTANCE)); + } + + @Test + public void testWrongLoadFactorSize() { + setSizeConstructor(T -> new LINKED_CUSTOM_HASH_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, 0F, HashStrategy.INSTANCE)); + try { + testSizeConstructor_smallSize(); + fail("A Constructor using a 0 LoadFactor should error"); + } catch(IllegalStateException e) { + } + + setSizeConstructor(T -> new LINKED_CUSTOM_HASH_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, 1F, HashStrategy.INSTANCE)); + try { + testSizeConstructor_smallSize(); + fail("A Constructor using a 1 LoadFactor should error"); + } catch(IllegalStateException e) { + } + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } + +#endif +#if VALUE_OBJECT + @Override + protected String[] createValueElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); + } + +#endif + } + + public static class ImmutableHashMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE + { + public ImmutableHashMap() { + setPArrayConstructor(MAP.builder()::immutable); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor(MAP.builder()::immutable); +#endif + setPMapConstructor(MAP.builder()::immutable); + setMapConstructor(MAP.builder()::immutable); + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } + +#endif +#if VALUE_OBJECT + @Override + protected String[] createValueElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); + } + +#endif + } + + public static class ConcurrentHashMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE + { + public ConcurrentHashMap() { + setSimpleConstructor(CONCURRENT_HASH_MAP::new); + setSizeConstructor(CONCURRENT_HASH_MAP::new); + setPArrayConstructor(CONCURRENT_HASH_MAP::new); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor(CONCURRENT_HASH_MAP::new); +#endif + setPMapConstructor(CONCURRENT_HASH_MAP::new); + setMapConstructor(CONCURRENT_HASH_MAP::new); + } + + @Test + public void testWrongLoadFactorSize() { + setSizeConstructor(T -> new CONCURRENT_HASH_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, 0F)); + try { + testSizeConstructor_smallSize(); + fail("A Constructor using a 0 LoadFactor should error"); + } catch(IllegalStateException e) { + } + + setSizeConstructor(T -> new CONCURRENT_HASH_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, 1F)); + try { + testSizeConstructor_smallSize(); + fail("A Constructor using a 1 LoadFactor should error"); + } catch(IllegalStateException e) { + } + } + + @Test + public void testWrongConcurrency() { + setSizeConstructor(T -> new CONCURRENT_HASH_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, 0)); + try { + testSizeConstructor_smallSize(); + fail("A Constructor using a 0 Concurrency should error"); + } catch(IllegalStateException e) { + } + + setSizeConstructor(T -> new CONCURRENT_HASH_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, Integer.MAX_VALUE)); + try { + testSizeConstructor_smallSize(); + fail("A Constructor using a 65536 or larger Concurrency should error"); + } catch(IllegalStateException e) { + } + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } + +#endif +#if VALUE_OBJECT + @Override + protected String[] createValueElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); + } + +#endif + } + + public static class ArrayMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE + { + public ArrayMap() { + setSimpleConstructor(MAP.builder()::arrayMap); + setSizeConstructor(MAP.builder()::arrayMap); + setPArrayConstructor(MAP.builder()::arrayMap); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor(MAP.builder()::arrayMap); +#endif + setPMapConstructor(MAP.builder()::arrayMap); + setMapConstructor(MAP.builder()::arrayMap); + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } + +#endif +#if VALUE_OBJECT + @Override + protected String[] createValueElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); + } + +#endif + } + + public static class RBTreeMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE + { + public RBTreeMap() { + setSimpleConstructor(MAP.builder()::rbTreeMap); + setPArrayConstructor(RB_TREE_MAP::new); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor(RB_TREE_MAP::new); +#endif + setPMapConstructor(RB_TREE_MAP::new); + setMapConstructor(RB_TREE_MAP::new); + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } + +#endif +#if VALUE_OBJECT + @Override + protected String[] createValueElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); + } + +#endif + } + + public static class RBTreeMapComparator extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE + { + public RBTreeMapComparator() { +#if TYPE_OBJECT + setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPErbTreeMap(Comparator.naturalOrder())); + setPArrayConstructor((K, V) -> MAP.builder().rbTreeMap(K, V, Comparator.naturalOrder())); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor((K, V) -> MAP.builder().rbTreeMap(K, V, Comparator.naturalOrder())); +#endif + setPMapConstructor(T -> MAP.builder().rbTreeMap(T, Comparator.naturalOrder())); + setMapConstructor(T -> MAP.builder().rbTreeMap(T, Comparator.naturalOrder())); +#else + setSimpleConstructor(() -> MAP.builder().rbTreeMap(CLASS_TYPE::compare)); + setPArrayConstructor((K, V) -> MAP.builder().rbTreeMap(K, V, CLASS_TYPE::compare)); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor((K, V) -> MAP.builder().rbTreeMap(K, V, CLASS_TYPE::compare)); +#endif + setPMapConstructor(T -> MAP.builder().rbTreeMap(T, CLASS_TYPE::compare)); + setMapConstructor(T -> MAP.builder().rbTreeMap(T, CLASS_TYPE::compare)); +#endif + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } + +#endif +#if VALUE_OBJECT + @Override + protected String[] createValueElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); + } + +#endif + } + + public static class AVLTreeMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE + { + public AVLTreeMap() { + setSimpleConstructor(MAP.builder()::avlTreeMap); + setPArrayConstructor(AVL_TREE_MAP::new); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor(AVL_TREE_MAP::new); +#endif + setPMapConstructor(AVL_TREE_MAP::new); + setMapConstructor(AVL_TREE_MAP::new); + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } + +#endif +#if VALUE_OBJECT + @Override + protected String[] createValueElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); + } + +#endif + } + + public static class AVLTreeMapComparator extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE + { + public AVLTreeMapComparator() { +#if TYPE_OBJECT + setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEavlTreeMap(Comparator.naturalOrder())); + setPArrayConstructor((K, V) -> MAP.builder().avlTreeMap(K, V, Comparator.naturalOrder())); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor((K, V) -> MAP.builder().avlTreeMap(K, V, Comparator.naturalOrder())); +#endif + setPMapConstructor(T -> MAP.builder().avlTreeMap(T, Comparator.naturalOrder())); + setMapConstructor(T -> MAP.builder().avlTreeMap(T, Comparator.naturalOrder())); +#else + setSimpleConstructor(() -> MAP.builder().avlTreeMap(CLASS_TYPE::compare)); + setPArrayConstructor((K, V) -> MAP.builder().avlTreeMap(K, V, CLASS_TYPE::compare)); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor((K, V) -> MAP.builder().avlTreeMap(K, V, CLASS_TYPE::compare)); +#endif + setPMapConstructor(T -> MAP.builder().avlTreeMap(T, CLASS_TYPE::compare)); + setMapConstructor(T -> MAP.builder().avlTreeMap(T, CLASS_TYPE::compare)); +#endif + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } + +#endif +#if VALUE_OBJECT + @Override + protected String[] createValueElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); + } + +#endif + } + + private static class HashStrategy implements STRATEGY KEY_STRING_GENERIC_TYPE { + static final HashStrategy INSTANCE = new HashStrategy(); + @Override + public int hashCode(KEY_STRING_TYPE o) { return KEY_TO_HASH(o); } + @Override + public boolean equals(KEY_STRING_TYPE key, KEY_STRING_TYPE value) { return KEY_EQUALS(key, value); } + } + + public static class HashMapBuilder extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE + { + public HashMapBuilder() { + setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().map()); + setSizeConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(T).map()); + setPArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).map()); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).map()); +#endif + setPMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).map()); + setMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).map()); + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } + +#endif +#if VALUE_OBJECT + @Override + protected String[] createValueElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); + } + +#endif + } + + public static class LinkedHashMapBuilder extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE + { + public LinkedHashMapBuilder() { + setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().linkedMap()); + setSizeConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(T).linkedMap()); + setPArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).linkedMap()); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).linkedMap()); +#endif + setPMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).linkedMap()); + setMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).linkedMap()); + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } + +#endif +#if VALUE_OBJECT + @Override + protected String[] createValueElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); + } + +#endif + } + + public static class CustomHashMapBuilder extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE + { + public CustomHashMapBuilder() { + setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().customMap(HashStrategy.INSTANCE)); + setSizeConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(T).customMap(HashStrategy.INSTANCE)); + setPArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).customMap(HashStrategy.INSTANCE)); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).customMap(HashStrategy.INSTANCE)); +#endif + setPMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).customMap(HashStrategy.INSTANCE)); + setMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).customMap(HashStrategy.INSTANCE)); + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } + +#endif +#if VALUE_OBJECT + @Override + protected String[] createValueElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); + } + +#endif + } + + public static class LinkedCustomHashMapBuilder extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE + { + public LinkedCustomHashMapBuilder() { + setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().customLinkedMap(HashStrategy.INSTANCE)); + setSizeConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(T).customLinkedMap(HashStrategy.INSTANCE)); + setPArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).customLinkedMap(HashStrategy.INSTANCE)); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).customLinkedMap(HashStrategy.INSTANCE)); +#endif + setPMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).customLinkedMap(HashStrategy.INSTANCE)); + setMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).customLinkedMap(HashStrategy.INSTANCE)); + + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } + +#endif +#if VALUE_OBJECT + @Override + protected String[] createValueElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); + } + +#endif + } + + public static class ImmutableHashMapBuilder extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE + { + public ImmutableHashMapBuilder() { + setPArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).immutable()); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).immutable()); +#endif + setPMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).immutable()); + setMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).immutable()); + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } + +#endif +#if VALUE_OBJECT + @Override + protected String[] createValueElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); + } + +#endif + } + + public static class ConcurrentHashMapBuilder extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE + { + public ConcurrentHashMapBuilder() { + setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().concurrentMap()); + setSizeConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(T).concurrentMap()); + setPArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).concurrentMap()); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).concurrentMap()); +#endif + setPMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).concurrentMap()); + setMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).concurrentMap()); + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } + +#endif +#if VALUE_OBJECT + @Override + protected String[] createValueElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); + } + +#endif + } + + public static class ArrayMapBuilder extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE + { + public ArrayMapBuilder() { + setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().arrayMap()); + setSizeConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(T).arrayMap()); + setPArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).arrayMap()); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).arrayMap()); +#endif + setPMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).arrayMap()); + setMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).arrayMap()); + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } + +#endif +#if VALUE_OBJECT + @Override + protected String[] createValueElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); + } + +#endif + } + + public static class RBTreeMapBuilder extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE + { + public RBTreeMapBuilder() { + setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().rbTreeMap()); + setPArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).rbTreeMap()); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).rbTreeMap()); +#endif + setPMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).rbTreeMap()); + setMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).rbTreeMap()); + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } + +#endif +#if VALUE_OBJECT + @Override + protected String[] createValueElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); + } + +#endif + } + + public static class RBTreeMapComparatorBuilder extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE + { + public RBTreeMapComparatorBuilder() { +#if TYPE_OBJECT + setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().rbTreeMap(Comparator.naturalOrder())); + setPArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).rbTreeMap(Comparator.naturalOrder())); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).rbTreeMap(Comparator.naturalOrder())); +#endif + setPMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).rbTreeMap(Comparator.naturalOrder())); + setMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).rbTreeMap(Comparator.naturalOrder())); +#else + setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().rbTreeMap(CLASS_TYPE::compare)); + setPArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).rbTreeMap(CLASS_TYPE::compare)); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).rbTreeMap(CLASS_TYPE::compare)); +#endif + setPMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).rbTreeMap(CLASS_TYPE::compare)); + setMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).rbTreeMap(CLASS_TYPE::compare)); +#endif + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } + +#endif +#if VALUE_OBJECT + @Override + protected String[] createValueElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); + } + +#endif + } + + public static class AVLTreeMapBuilder extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE + { + public AVLTreeMapBuilder() { + setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().avlTreeMap()); + setPArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).avlTreeMap()); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).avlTreeMap()); +#endif + setPMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).avlTreeMap()); + setMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).avlTreeMap()); + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } + +#endif +#if VALUE_OBJECT + @Override + protected String[] createValueElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); + } + +#endif + } + + public static class AVLTreeMapComparatorBuilder extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE + { + public AVLTreeMapComparatorBuilder() { +#if TYPE_OBJECT + setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().avlTreeMap(Comparator.naturalOrder())); + setPArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).avlTreeMap(Comparator.naturalOrder())); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).avlTreeMap(Comparator.naturalOrder())); +#endif + setPMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).avlTreeMap(Comparator.naturalOrder())); + setMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).avlTreeMap(Comparator.naturalOrder())); +#else + setSimpleConstructor(() -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().avlTreeMap(CLASS_TYPE::compare)); + setPArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).avlTreeMap(CLASS_TYPE::compare)); +#if !TYPE_OBJECT || !VALUE_OBJECT + setArrayConstructor((K, V) -> putAll(MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart(), K, V).avlTreeMap(CLASS_TYPE::compare)); +#endif + setPMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).avlTreeMap(CLASS_TYPE::compare)); + setMapConstructor(T -> MAP.builder(). KEY_VALUE_STRING_GENERIC_TYPEstart().putAll(T).avlTreeMap(CLASS_TYPE::compare)); +#endif + } + +#if TYPE_OBJECT + @Override + protected String[] createKeyElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100); + } + +#endif +#if VALUE_OBJECT + @Override + protected String[] createValueElements() { + return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200); + } + +#endif + } + + private static MAP.BuilderCache KEY_VALUE_STRING_GENERIC_TYPE putAll(MAP.BuilderCache KEY_VALUE_STRING_GENERIC_TYPE cache, KEY_STRING_TYPE[] keys, VALUE_STRING_TYPE[] values) { + if(keys.length != values.length) throw new IllegalStateException("Keys & Values lengths must match"); + for(int i = 0;i -{ - BiFunction mapper; -#if TYPE_BYTE - KEY_TYPE[] keys = new KEY_TYPE[]{(byte)0, (byte)1, (byte)2, (byte)3, (byte)4, (byte)-2, (byte)-1, (byte)5, (byte)6}; -#else if TYPE_SHORT - KEY_TYPE[] keys = new KEY_TYPE[]{(short)0, (short)1, (short)2, (short)3, (short)4, (short)-2, (short)-1, (short)5, (short)6}; -#else if TYPE_CHAR - KEY_TYPE[] keys = new KEY_TYPE[]{(char)0, (char)1, (char)2, (char)3, (char)4}; -#else if TYPE_OBJECT - KEY_TYPE[] keys; -#else - KEY_TYPE[] keys = new KEY_TYPE[]{0, 1, 2, 3, 4, -2, -1, 5, 6}; -#endif -#if VALUE_BOOLEAN - VALUE_TYPE[] values = new VALUE_TYPE[]{true, true, true, false, true, false, true, false, true}; -#else if VALUE_BYTE - VALUE_TYPE[] values = new VALUE_TYPE[]{(byte)0, (byte)1, (byte)2, (byte)3, (byte)4, (byte)-2, (byte)-1, (byte)5, (byte)6}; -#else if VALUE_SHORT - VALUE_TYPE[] values = new VALUE_TYPE[]{(short)0, (short)1, (short)2, (short)3, (short)4, (short)-2, (short)-1, (short)5, (short)6}; -#else if VALUE_CHAR - VALUE_TYPE[] values = new VALUE_TYPE[]{(char)0, (char)1, (char)2, (char)3, (char)4}; -#else if VALUE_OBJECT - VALUE_TYPE[] values; -#else - VALUE_TYPE[] values = new VALUE_TYPE[]{0, 1, 2, 3, 4, -2, -1, 5, 6}; -#endif - - public SIMPLE_MAP_TEST_GENERATOR(BiFunction mapper) { - this.mapper = mapper; - } - -#if TYPE_OBJECT || TYPE_CHAR - public void setKeys(KEY_TYPE... keys) { - this.keys = keys; - } - -#endif -#if VALUE_OBJECT || VALUE_CHAR - public void setValues(VALUE_TYPE... values) { - this.values = values; - } - -#endif - public ObjectSamples getSamples() { - return new ObjectSamples( - new ABSTRACT_MAP.BasicEntryKV_BRACES(keys[0], values[0]), - new ABSTRACT_MAP.BasicEntryKV_BRACES(keys[1], values[1]), - new ABSTRACT_MAP.BasicEntryKV_BRACES(keys[2], values[2]), - new ABSTRACT_MAP.BasicEntryKV_BRACES(keys[3], values[3]), - new ABSTRACT_MAP.BasicEntryKV_BRACES(keys[4], values[4]) - ); - } - - public E create(MAP.Entry KEY_VALUE_GENERIC_TYPE... elements) { -#if TYPE_OBJECT - KEY_TYPE[] keys = (T[])ObjectArrays.newArray(getSamples().e0().ENTRY_KEY().getClass(), elements.length); -#else - KEY_TYPE[] keys = NEW_KEY_ARRAY(elements.length); -#endif -#if VALUE_OBJECT - VALUE_TYPE[] values = (V[])ObjectArrays.newArray(getSamples().e0().ENTRY_VALUE().getClass(), elements.length); -#else - VALUE_TYPE[] values = NEW_VALUE_ARRAY(elements.length); -#endif - for(int i = 0;i> order(List> insertionOrder) { - return insertionOrder; - } - - public ObjectIterable order(ObjectList insertionOrder) { - return insertionOrder; - } - - public static class Maps KEY_VALUE_GENERIC_TYPE extends SIMPLE_MAP_TEST_GENERATOR KEY_VALUE_SPECIAL_GENERIC_TYPE implements TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE - { - public Maps(BiFunction mapper) { - super(mapper); - } - } - - public static class OrderedMaps KEY_VALUE_GENERIC_TYPE extends SIMPLE_MAP_TEST_GENERATOR KEY_VALUE_SPECIAL_GENERIC_TYPE implements TEST_ORDERED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE - { - public OrderedMaps(BiFunction mapper) { - super(mapper); - } - } - - public static class ConcurrentMaps KEY_VALUE_GENERIC_TYPE extends SIMPLE_MAP_TEST_GENERATOR KEY_VALUE_SPECIAL_GENERIC_TYPE implements TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE - { - Consumer> sorter; - - public ConcurrentMaps(BiFunction mapper, Consumer> sorter) { - super(mapper); - this.sorter = sorter; - } - - public Iterable> order(List> insertionOrder) { - ObjectList newList = new ObjectArrayList<>(); - for(Map.Entry entry : insertionOrder) { - newList.add(new ABSTRACT_MAP.BasicEntryKV_BRACES(entry.getKey(), entry.getValue())); - } - order(newList); - insertionOrder.sort(new Comparator>() { - @Override - public int compare(Map.Entry key, Map.Entry value) { - return Integer.signum(indexOf(OBJ_TO_KEY(key.getKey())) - indexOf(OBJ_TO_KEY(value.getKey()))); - } - - protected int indexOf(KEY_TYPE key) { - for(int i = 0,m=newList.size();i order(ObjectList insertionOrder) { - sorter.accept(insertionOrder); - return insertionOrder; - } - } - - public static class SortedMaps KEY_VALUE_GENERIC_TYPE extends SIMPLE_MAP_TEST_GENERATOR KEY_VALUE_SPECIAL_GENERIC_TYPE implements TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE - { - public SortedMaps(BiFunction mapper) { - super(mapper); -#if TYPE_CHAR - setKeys(new KEY_TYPE[]{'a', 'b', 'c', 'd', 'e', '_', '`', 'f', 'g'}); -#endif -#if VALUE_CHAR - setValues(new VALUE_TYPE[]{'a', 'b', 'c', 'd', 'e', '_', '`', 'f', 'g'}); -#endif - - } - - public Iterable> order(List> insertionOrder) { -#if TYPE_OBJECT - insertionOrder.sort(DERIVED_MAP_GENERATORS.entryObjectComparator((Comparator)Comparator.naturalOrder())); -#else - insertionOrder.sort(DERIVED_MAP_GENERATORS.entryObjectComparator(CLASS_TYPE::compare)); -#endif - return insertionOrder; - } - - public ObjectIterable order(ObjectList insertionOrder) { -#if TYPE_OBJECT - insertionOrder.sort(DERIVED_MAP_GENERATORS.entryComparator((Comparator)Comparator.naturalOrder())); -#else - insertionOrder.sort(DERIVED_MAP_GENERATORS.entryComparator(CLASS_TYPE::compare)); -#endif - return insertionOrder; - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE belowSamplesLesser() { return new ABSTRACT_MAP.BasicEntryKV_BRACES(keys[5], values[5]); } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE belowSamplesGreater() { return new ABSTRACT_MAP.BasicEntryKV_BRACES(keys[6], values[6]); } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE aboveSamplesLesser() { return new ABSTRACT_MAP.BasicEntryKV_BRACES(keys[7], values[7]); } - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE aboveSamplesGreater() { return new ABSTRACT_MAP.BasicEntryKV_BRACES(keys[8], values[8]); } - } -} +package speiger.src.testers.PACKAGE.impl.maps; + +import java.util.Comparator; +import java.util.List; +import java.util.Map; +#if TYPE_OBJECT +import java.util.Objects; +#endif +import java.util.function.BiFunction; +import java.util.function.Consumer; + +import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.CONCURRENT_MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.SORTED_MAP; +import speiger.src.collections.objects.collections.ObjectIterable; +#if TYPE_OBJECT || VALUE_OBJECT +import speiger.src.collections.objects.utils.ObjectArrays; +#endif +import speiger.src.collections.objects.lists.ObjectList; +import speiger.src.collections.objects.lists.ObjectArrayList; +import speiger.src.testers.PACKAGE.generators.maps.TEST_MAP_GENERATOR; +import speiger.src.testers.PACKAGE.generators.maps.TEST_ORDERED_MAP_GENERATOR; +import speiger.src.testers.PACKAGE.generators.maps.TEST_SORTED_MAP_GENERATOR; +import speiger.src.testers.objects.utils.ObjectSamples; + +@SuppressWarnings("javadoc") +public class SIMPLE_MAP_TEST_GENERATOR KEY_VALUE_SPECIAL_GENERIC_TYPE +{ + BiFunction mapper; +#if TYPE_BYTE + KEY_TYPE[] keys = new KEY_TYPE[]{(byte)0, (byte)1, (byte)2, (byte)3, (byte)4, (byte)-2, (byte)-1, (byte)5, (byte)6}; +#else if TYPE_SHORT + KEY_TYPE[] keys = new KEY_TYPE[]{(short)0, (short)1, (short)2, (short)3, (short)4, (short)-2, (short)-1, (short)5, (short)6}; +#else if TYPE_CHAR + KEY_TYPE[] keys = new KEY_TYPE[]{(char)0, (char)1, (char)2, (char)3, (char)4}; +#else if TYPE_OBJECT + KEY_TYPE[] keys; +#else + KEY_TYPE[] keys = new KEY_TYPE[]{0, 1, 2, 3, 4, -2, -1, 5, 6}; +#endif +#if VALUE_BOOLEAN + VALUE_TYPE[] values = new VALUE_TYPE[]{true, true, true, false, true, false, true, false, true}; +#else if VALUE_BYTE + VALUE_TYPE[] values = new VALUE_TYPE[]{(byte)0, (byte)1, (byte)2, (byte)3, (byte)4, (byte)-2, (byte)-1, (byte)5, (byte)6}; +#else if VALUE_SHORT + VALUE_TYPE[] values = new VALUE_TYPE[]{(short)0, (short)1, (short)2, (short)3, (short)4, (short)-2, (short)-1, (short)5, (short)6}; +#else if VALUE_CHAR + VALUE_TYPE[] values = new VALUE_TYPE[]{(char)0, (char)1, (char)2, (char)3, (char)4}; +#else if VALUE_OBJECT + VALUE_TYPE[] values; +#else + VALUE_TYPE[] values = new VALUE_TYPE[]{0, 1, 2, 3, 4, -2, -1, 5, 6}; +#endif + + public SIMPLE_MAP_TEST_GENERATOR(BiFunction mapper) { + this.mapper = mapper; + } + +#if TYPE_OBJECT || TYPE_CHAR + public void setKeys(KEY_TYPE... keys) { + this.keys = keys; + } + +#endif +#if VALUE_OBJECT || VALUE_CHAR + public void setValues(VALUE_TYPE... values) { + this.values = values; + } + +#endif + public ObjectSamples getSamples() { + return new ObjectSamples( + new ABSTRACT_MAP.BasicEntryKV_BRACES(keys[0], values[0]), + new ABSTRACT_MAP.BasicEntryKV_BRACES(keys[1], values[1]), + new ABSTRACT_MAP.BasicEntryKV_BRACES(keys[2], values[2]), + new ABSTRACT_MAP.BasicEntryKV_BRACES(keys[3], values[3]), + new ABSTRACT_MAP.BasicEntryKV_BRACES(keys[4], values[4]) + ); + } + + public E create(MAP.Entry KEY_VALUE_GENERIC_TYPE... elements) { +#if TYPE_OBJECT + KEY_TYPE[] keys = (T[])ObjectArrays.newArray(getSamples().e0().ENTRY_KEY().getClass(), elements.length); +#else + KEY_TYPE[] keys = NEW_KEY_ARRAY(elements.length); +#endif +#if VALUE_OBJECT + VALUE_TYPE[] values = (V[])ObjectArrays.newArray(getSamples().e0().ENTRY_VALUE().getClass(), elements.length); +#else + VALUE_TYPE[] values = NEW_VALUE_ARRAY(elements.length); +#endif + for(int i = 0;i> order(List> insertionOrder) { + return insertionOrder; + } + + public ObjectIterable order(ObjectList insertionOrder) { + return insertionOrder; + } + + public static class Maps KEY_VALUE_GENERIC_TYPE extends SIMPLE_MAP_TEST_GENERATOR KEY_VALUE_SPECIAL_GENERIC_TYPE implements TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE + { + public Maps(BiFunction mapper) { + super(mapper); + } + } + + public static class OrderedMaps KEY_VALUE_GENERIC_TYPE extends SIMPLE_MAP_TEST_GENERATOR KEY_VALUE_SPECIAL_GENERIC_TYPE implements TEST_ORDERED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE + { + public OrderedMaps(BiFunction mapper) { + super(mapper); + } + } + + public static class ConcurrentMaps KEY_VALUE_GENERIC_TYPE extends SIMPLE_MAP_TEST_GENERATOR KEY_VALUE_SPECIAL_GENERIC_TYPE implements TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE + { + Consumer> sorter; + + public ConcurrentMaps(BiFunction mapper, Consumer> sorter) { + super(mapper); + this.sorter = sorter; + } + + public Iterable> order(List> insertionOrder) { + ObjectList newList = new ObjectArrayList<>(); + for(Map.Entry entry : insertionOrder) { + newList.add(new ABSTRACT_MAP.BasicEntryKV_BRACES(entry.getKey(), entry.getValue())); + } + order(newList); + insertionOrder.sort(new Comparator>() { + @Override + public int compare(Map.Entry key, Map.Entry value) { + return Integer.signum(indexOf(OBJ_TO_KEY(key.getKey())) - indexOf(OBJ_TO_KEY(value.getKey()))); + } + + protected int indexOf(KEY_TYPE key) { + for(int i = 0,m=newList.size();i order(ObjectList insertionOrder) { + sorter.accept(insertionOrder); + return insertionOrder; + } + } + + public static class SortedMaps KEY_VALUE_GENERIC_TYPE extends SIMPLE_MAP_TEST_GENERATOR KEY_VALUE_SPECIAL_GENERIC_TYPE implements TEST_SORTED_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE + { + public SortedMaps(BiFunction mapper) { + super(mapper); +#if TYPE_CHAR + setKeys(new KEY_TYPE[]{'a', 'b', 'c', 'd', 'e', '_', '`', 'f', 'g'}); +#endif +#if VALUE_CHAR + setValues(new VALUE_TYPE[]{'a', 'b', 'c', 'd', 'e', '_', '`', 'f', 'g'}); +#endif + + } + + public Iterable> order(List> insertionOrder) { +#if TYPE_OBJECT + insertionOrder.sort(DERIVED_MAP_GENERATORS.entryObjectComparator((Comparator)Comparator.naturalOrder())); +#else + insertionOrder.sort(DERIVED_MAP_GENERATORS.entryObjectComparator(CLASS_TYPE::compare)); +#endif + return insertionOrder; + } + + public ObjectIterable order(ObjectList insertionOrder) { +#if TYPE_OBJECT + insertionOrder.sort(DERIVED_MAP_GENERATORS.entryComparator((Comparator)Comparator.naturalOrder())); +#else + insertionOrder.sort(DERIVED_MAP_GENERATORS.entryComparator(CLASS_TYPE::compare)); +#endif + return insertionOrder; + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE belowSamplesLesser() { return new ABSTRACT_MAP.BasicEntryKV_BRACES(keys[5], values[5]); } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE belowSamplesGreater() { return new ABSTRACT_MAP.BasicEntryKV_BRACES(keys[6], values[6]); } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE aboveSamplesLesser() { return new ABSTRACT_MAP.BasicEntryKV_BRACES(keys[7], values[7]); } + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE aboveSamplesGreater() { return new ABSTRACT_MAP.BasicEntryKV_BRACES(keys[8], values[8]); } + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/impl/maps/TestMap.template b/src/builder/resources/speiger/assets/testers/templates/impl/maps/TestMap.template index 573673d..cf3f938 100644 --- a/src/builder/resources/speiger/assets/testers/templates/impl/maps/TestMap.template +++ b/src/builder/resources/speiger/assets/testers/templates/impl/maps/TestMap.template @@ -1,92 +1,92 @@ -package speiger.src.testers.PACKAGE.impl.maps; - -import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.collections.PACKAGE.maps.impl.misc.ARRAY_MAP; -import speiger.src.collections.objects.collections.ObjectIterator; -import speiger.src.collections.objects.sets.AbstractObjectSet; -import speiger.src.collections.objects.sets.ObjectSet; - -@SuppressWarnings("javadoc") -public class SIMPLE_TEST_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE -{ - MAP KEY_VALUE_GENERIC_TYPE map; - - public SIMPLE_TEST_MAP(KEY_TYPE[] keys, VALUE_TYPE[] values) { - map = new ARRAY_MAPKV_BRACES(keys, values); - } - - @Override - public ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE setDefaultReturnValue(VALUE_TYPE v) { - map.setDefaultReturnValue(v); - return this; - } - - @Override - public VALUE_TYPE getDefaultReturnValue() { return map.getDefaultReturnValue(); } - - @Override - public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { return map.put(key, value); } - @Override - public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { return map.putIfAbsent(key, value); } -#if VALUE_PRIMITIVES - @Override - public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { return map.addTo(key, value); } - @Override - public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { return map.subFrom(key, value); } -#endif - @Override - public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { return map.REMOVE_VALUE(key); } - @Override - public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { return map.REMOVE_VALUEOrDefault(key, defaultValue); } -#if !TYPE_OBJECT || !VALUE_OBJECT - @Override - public boolean remove(KEY_TYPE key, VALUE_TYPE value) { return map.remove(key, value); } -#endif - @Override - public CLASS_VALUE_TYPE remove(Object key) { return map.remove(key); } - @Override - public boolean remove(Object key, Object value) { return map.remove(key, value); } - @Override - public VALUE_TYPE GET_VALUE(KEY_TYPE key) { return map.GET_VALUE(key); } -#if TYPE_OBJECT && !VALUE_OBJECT - @Override - public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { return map.getOrDefault(key, defaultValue); } -#endif - @Override - public ObjectSet ENTRY_SET() { - return new AbstractObjectSet() { - @Override - public ObjectIterator iterator() { - return new ObjectIterator() { - ObjectIterator iter = map.ENTRY_SET().iterator(); - @Override - public boolean hasNext() { - return iter.hasNext(); - } - - @Override - public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = iter.next(); - return new ABSTRACT_MAP.BasicEntry KEY_VALUE_GENERIC_TYPE(entry.ENTRY_KEY(), entry.ENTRY_VALUE()) { - @Override - public VALUE_TYPE setValue(VALUE_TYPE value) { - return entry.setValue(value); - } - }; - } - - @Override - public void remove() { - iter.remove(); - } - }; - } - - @Override - public int size() { - return map.size(); - } - }; - } +package speiger.src.testers.PACKAGE.impl.maps; + +import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.collections.PACKAGE.maps.impl.misc.ARRAY_MAP; +import speiger.src.collections.objects.collections.ObjectIterator; +import speiger.src.collections.objects.sets.AbstractObjectSet; +import speiger.src.collections.objects.sets.ObjectSet; + +@SuppressWarnings("javadoc") +public class SIMPLE_TEST_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE +{ + MAP KEY_VALUE_GENERIC_TYPE map; + + public SIMPLE_TEST_MAP(KEY_TYPE[] keys, VALUE_TYPE[] values) { + map = new ARRAY_MAPKV_BRACES(keys, values); + } + + @Override + public ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE setDefaultReturnValue(VALUE_TYPE v) { + map.setDefaultReturnValue(v); + return this; + } + + @Override + public VALUE_TYPE getDefaultReturnValue() { return map.getDefaultReturnValue(); } + + @Override + public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { return map.put(key, value); } + @Override + public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { return map.putIfAbsent(key, value); } +#if VALUE_PRIMITIVES + @Override + public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { return map.addTo(key, value); } + @Override + public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { return map.subFrom(key, value); } +#endif + @Override + public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { return map.REMOVE_VALUE(key); } + @Override + public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { return map.REMOVE_VALUEOrDefault(key, defaultValue); } +#if !TYPE_OBJECT || !VALUE_OBJECT + @Override + public boolean remove(KEY_TYPE key, VALUE_TYPE value) { return map.remove(key, value); } +#endif + @Override + public CLASS_VALUE_TYPE remove(Object key) { return map.remove(key); } + @Override + public boolean remove(Object key, Object value) { return map.remove(key, value); } + @Override + public VALUE_TYPE GET_VALUE(KEY_TYPE key) { return map.GET_VALUE(key); } +#if TYPE_OBJECT && !VALUE_OBJECT + @Override + public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { return map.getOrDefault(key, defaultValue); } +#endif + @Override + public ObjectSet ENTRY_SET() { + return new AbstractObjectSet() { + @Override + public ObjectIterator iterator() { + return new ObjectIterator() { + ObjectIterator iter = map.ENTRY_SET().iterator(); + @Override + public boolean hasNext() { + return iter.hasNext(); + } + + @Override + public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = iter.next(); + return new ABSTRACT_MAP.BasicEntry KEY_VALUE_GENERIC_TYPE(entry.ENTRY_KEY(), entry.ENTRY_VALUE()) { + @Override + public VALUE_TYPE setValue(VALUE_TYPE value) { + return entry.setValue(value); + } + }; + } + + @Override + public void remove() { + iter.remove(); + } + }; + } + + @Override + public int size() { + return map.size(); + } + }; + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/base/AbstractCollectionTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/base/AbstractCollectionTester.template index c8f7c3c..433708f 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/base/AbstractCollectionTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/base/AbstractCollectionTester.template @@ -1,28 +1,28 @@ -package speiger.src.testers.PACKAGE.tests.base; - -import org.junit.Ignore; - -import speiger.src.collections.PACKAGE.collections.COLLECTION; - -@Ignore -@SuppressWarnings("javadoc") -public class ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE extends ABSTRACT_CONTAINER_TESTER KKS_GENERIC_TYPE -{ - protected COLLECTION KEY_GENERIC_TYPE collection; - - @Override - protected COLLECTION KEY_GENERIC_TYPE actualContents() { - return collection; - } - - @Override - protected COLLECTION KEY_GENERIC_TYPE resetContainer(COLLECTION KEY_GENERIC_TYPE newContents) { - collection = super.resetContainer(newContents); - return collection; - } - - protected void resetCollection() { - resetContainer(); - } - -} +package speiger.src.testers.PACKAGE.tests.base; + +import org.junit.Ignore; + +import speiger.src.collections.PACKAGE.collections.COLLECTION; + +@Ignore +@SuppressWarnings("javadoc") +public class ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE extends ABSTRACT_CONTAINER_TESTER KKS_GENERIC_TYPE +{ + protected COLLECTION KEY_GENERIC_TYPE collection; + + @Override + protected COLLECTION KEY_GENERIC_TYPE actualContents() { + return collection; + } + + @Override + protected COLLECTION KEY_GENERIC_TYPE resetContainer(COLLECTION KEY_GENERIC_TYPE newContents) { + collection = super.resetContainer(newContents); + return collection; + } + + protected void resetCollection() { + resetContainer(); + } + +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/base/AbstractContainerTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/base/AbstractContainerTester.template index 010b6b3..ef0cc4c 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/base/AbstractContainerTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/base/AbstractContainerTester.template @@ -1,188 +1,188 @@ -package speiger.src.testers.PACKAGE.tests.base; - -import com.google.common.collect.testing.AbstractTester; -import com.google.common.collect.testing.OneSizeTestContainerGenerator; -import com.google.common.collect.testing.TestContainerGenerator; -import com.google.common.collect.testing.features.CollectionSize; -import com.google.errorprone.annotations.OverridingMethodsMustInvokeSuper; - -import org.junit.Ignore; - -import speiger.src.collections.PACKAGE.collections.COLLECTION; -import speiger.src.collections.PACKAGE.collections.ITERATOR; -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.collections.PACKAGE.utils.LISTS; -import speiger.src.testers.PACKAGE.generators.TEST_COLLECTION_GENERATOR; -import speiger.src.testers.PACKAGE.utils.HELPERS; -import speiger.src.testers.PACKAGE.utils.SAMPLE_ELEMENTS; -import speiger.src.testers.PACKAGE.utils.MINIMAL_COLLECTION; - -@Ignore -@SuppressWarnings("javadoc") -public abstract class ABSTRACT_CONTAINER_TESTER KKS_GENERIC_TYPE extends AbstractTester> -{ - protected SAMPLE_ELEMENTS KEY_GENERIC_TYPE samples; - protected E container; - protected TEST_COLLECTION_GENERATOR KEY_GENERIC_TYPE primitiveGenerator; - protected CollectionSize size; - - @Override - @OverridingMethodsMustInvokeSuper - public void setUp() throws Exception { - super.setUp(); - setupGenerator(); - } - - protected void setupGenerator() { - TestContainerGenerator generator = getSubjectGenerator().getInnerGenerator(); - if (!(generator instanceof TEST_COLLECTION_GENERATOR)) throw new IllegalStateException("Test Generator Must extend TEST_COLLECTION_GENERATOR"); - primitiveGenerator = (TEST_COLLECTION_GENERATOR KEY_GENERIC_TYPE) generator; - samples = primitiveGenerator.getSamples(); - size = getSubjectGenerator().getCollectionSize(); - resetContainer(); - } - - protected abstract COLLECTION KEY_GENERIC_TYPE actualContents(); - - protected E resetContainer() { - return resetContainer(createTestSubject()); - } - - protected E resetContainer(E newValue) { - container = newValue; - return container; - } - - protected void expectContents(KEY_TYPE... elements) { - expectContents(ARRAY_LIST.wrap(elements)); - } - - protected void expectContents(COLLECTION KEY_GENERIC_TYPE expected) { - HELPERS.assertEqualIgnoringOrder(expected, actualContents()); - } - - protected void expectUnchanged() { - expectContents(getOrderedElements()); - } - - protected final void expectAdded(KEY_TYPE... elements) { - LIST KEY_GENERIC_TYPE expected = HELPERS.copyToList(getSampleElements()); - expected.addAll(elements); - expectContents(expected); - } - - protected final void expectAddedIndex(int index, KEY_TYPE... elements) { - expectAdded(index, ARRAY_LIST.wrap(elements)); - } - - protected final void expectAdded(int index, COLLECTION KEY_GENERIC_TYPE elements) { - LIST KEY_GENERIC_TYPE expected = HELPERS.copyToList(getSampleElements()); - expected.addAll(index, elements); - expectContents(expected); - } - - protected void expectMissing(KEY_TYPE... elements) { - for (KEY_TYPE element : elements) { - assertFalse("Should not contain " + element, actualContents().contains(element)); - } - } - - protected KEY_TYPE[] createSamplesArray() { - return getSampleElements().TO_ARRAY(NEW_KEY_ARRAY(getNumElements())); - } - - protected KEY_TYPE[] createOrderedArray() { - return getOrderedElements().TO_ARRAY(NEW_KEY_ARRAY(getNumElements())); - } - - public static class ArrayWithDuplicate KEY_GENERIC_TYPE { - public final KEY_TYPE[] elements; - public final KEY_TYPE duplicate; - - private ArrayWithDuplicate(KEY_TYPE[] elements, KEY_TYPE duplicate) { - this.elements = elements; - this.duplicate = duplicate; - } - } - - protected ArrayWithDuplicate KEY_GENERIC_TYPE createArrayWithDuplicateElement() { - KEY_TYPE[] elements = createSamplesArray(); - KEY_TYPE duplicate = elements[(elements.length / 2) - 1]; - elements[(elements.length / 2) + 1] = duplicate; - return new ArrayWithDuplicateBRACES(elements, duplicate); - } - - protected int getNumElements() { - return size.getNumElements(); - } - - protected COLLECTION KEY_GENERIC_TYPE getSampleElements() { - return getSampleElements(getNumElements()); - } - - protected LIST KEY_GENERIC_TYPE getOrderedElements() { - LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); - for (ITERATOR KEY_GENERIC_TYPE iter = primitiveGenerator.order(new ARRAY_LISTBRACES(getSampleElements())).iterator(); iter.hasNext();) { - list.add(iter.NEXT()); - } - return LISTS.unmodifiable(list); - } - -#if TYPE_OBJECT - protected KEY_TYPE[] createDisjointArray() { - KEY_TYPE[] array = NEW_KEY_ARRAY(2); - array[0] = e3(); - array[1] = e4(); - return array; - } -#else - protected KEY_TYPE[] createDisjointArray() { - return new KEY_TYPE[]{e3(), e4()}; - } - -#endif - protected KEY_TYPE[] emptyArray() { - return NEW_KEY_ARRAY(0); - } - - protected MINIMAL_COLLECTION KEY_GENERIC_TYPE createDisjointCollection() { - return MINIMAL_COLLECTION.of(e3(), e4()); - } - - protected MINIMAL_COLLECTION KEY_GENERIC_TYPE emptyCollection() { - return MINIMAL_COLLECTION.of(); - } - - public KEY_TYPE[] createArray(KEY_TYPE...array) { - return array; - } - - protected final KEY_TYPE e0() { - return samples.e0(); - } - - protected final KEY_TYPE e1() { - return samples.e1(); - } - - protected final KEY_TYPE e2() { - return samples.e2(); - } - - protected final KEY_TYPE e3() { - return samples.e3(); - } - - protected final KEY_TYPE e4() { - return samples.e4(); - } - - protected E createTestSubject() { - return (E)primitiveGenerator.create(getSampleElements(size.getNumElements()).TO_ARRAY(NEW_KEY_ARRAY(getNumElements()))); - } - - protected COLLECTION KEY_GENERIC_TYPE getSampleElements(int howMany) { - return new ARRAY_LISTBRACES(samples.asList().subList(0, howMany)); - } +package speiger.src.testers.PACKAGE.tests.base; + +import com.google.common.collect.testing.AbstractTester; +import com.google.common.collect.testing.OneSizeTestContainerGenerator; +import com.google.common.collect.testing.TestContainerGenerator; +import com.google.common.collect.testing.features.CollectionSize; +import com.google.errorprone.annotations.OverridingMethodsMustInvokeSuper; + +import org.junit.Ignore; + +import speiger.src.collections.PACKAGE.collections.COLLECTION; +import speiger.src.collections.PACKAGE.collections.ITERATOR; +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.collections.PACKAGE.utils.LISTS; +import speiger.src.testers.PACKAGE.generators.TEST_COLLECTION_GENERATOR; +import speiger.src.testers.PACKAGE.utils.HELPERS; +import speiger.src.testers.PACKAGE.utils.SAMPLE_ELEMENTS; +import speiger.src.testers.PACKAGE.utils.MINIMAL_COLLECTION; + +@Ignore +@SuppressWarnings("javadoc") +public abstract class ABSTRACT_CONTAINER_TESTER KKS_GENERIC_TYPE extends AbstractTester> +{ + protected SAMPLE_ELEMENTS KEY_GENERIC_TYPE samples; + protected E container; + protected TEST_COLLECTION_GENERATOR KEY_GENERIC_TYPE primitiveGenerator; + protected CollectionSize size; + + @Override + @OverridingMethodsMustInvokeSuper + public void setUp() throws Exception { + super.setUp(); + setupGenerator(); + } + + protected void setupGenerator() { + TestContainerGenerator generator = getSubjectGenerator().getInnerGenerator(); + if (!(generator instanceof TEST_COLLECTION_GENERATOR)) throw new IllegalStateException("Test Generator Must extend TEST_COLLECTION_GENERATOR"); + primitiveGenerator = (TEST_COLLECTION_GENERATOR KEY_GENERIC_TYPE) generator; + samples = primitiveGenerator.getSamples(); + size = getSubjectGenerator().getCollectionSize(); + resetContainer(); + } + + protected abstract COLLECTION KEY_GENERIC_TYPE actualContents(); + + protected E resetContainer() { + return resetContainer(createTestSubject()); + } + + protected E resetContainer(E newValue) { + container = newValue; + return container; + } + + protected void expectContents(KEY_TYPE... elements) { + expectContents(ARRAY_LIST.wrap(elements)); + } + + protected void expectContents(COLLECTION KEY_GENERIC_TYPE expected) { + HELPERS.assertEqualIgnoringOrder(expected, actualContents()); + } + + protected void expectUnchanged() { + expectContents(getOrderedElements()); + } + + protected final void expectAdded(KEY_TYPE... elements) { + LIST KEY_GENERIC_TYPE expected = HELPERS.copyToList(getSampleElements()); + expected.addAll(elements); + expectContents(expected); + } + + protected final void expectAddedIndex(int index, KEY_TYPE... elements) { + expectAdded(index, ARRAY_LIST.wrap(elements)); + } + + protected final void expectAdded(int index, COLLECTION KEY_GENERIC_TYPE elements) { + LIST KEY_GENERIC_TYPE expected = HELPERS.copyToList(getSampleElements()); + expected.addAll(index, elements); + expectContents(expected); + } + + protected void expectMissing(KEY_TYPE... elements) { + for (KEY_TYPE element : elements) { + assertFalse("Should not contain " + element, actualContents().contains(element)); + } + } + + protected KEY_TYPE[] createSamplesArray() { + return getSampleElements().TO_ARRAY(NEW_KEY_ARRAY(getNumElements())); + } + + protected KEY_TYPE[] createOrderedArray() { + return getOrderedElements().TO_ARRAY(NEW_KEY_ARRAY(getNumElements())); + } + + public static class ArrayWithDuplicate KEY_GENERIC_TYPE { + public final KEY_TYPE[] elements; + public final KEY_TYPE duplicate; + + private ArrayWithDuplicate(KEY_TYPE[] elements, KEY_TYPE duplicate) { + this.elements = elements; + this.duplicate = duplicate; + } + } + + protected ArrayWithDuplicate KEY_GENERIC_TYPE createArrayWithDuplicateElement() { + KEY_TYPE[] elements = createSamplesArray(); + KEY_TYPE duplicate = elements[(elements.length / 2) - 1]; + elements[(elements.length / 2) + 1] = duplicate; + return new ArrayWithDuplicateBRACES(elements, duplicate); + } + + protected int getNumElements() { + return size.getNumElements(); + } + + protected COLLECTION KEY_GENERIC_TYPE getSampleElements() { + return getSampleElements(getNumElements()); + } + + protected LIST KEY_GENERIC_TYPE getOrderedElements() { + LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); + for (ITERATOR KEY_GENERIC_TYPE iter = primitiveGenerator.order(new ARRAY_LISTBRACES(getSampleElements())).iterator(); iter.hasNext();) { + list.add(iter.NEXT()); + } + return LISTS.unmodifiable(list); + } + +#if TYPE_OBJECT + protected KEY_TYPE[] createDisjointArray() { + KEY_TYPE[] array = NEW_KEY_ARRAY(2); + array[0] = e3(); + array[1] = e4(); + return array; + } +#else + protected KEY_TYPE[] createDisjointArray() { + return new KEY_TYPE[]{e3(), e4()}; + } + +#endif + protected KEY_TYPE[] emptyArray() { + return NEW_KEY_ARRAY(0); + } + + protected MINIMAL_COLLECTION KEY_GENERIC_TYPE createDisjointCollection() { + return MINIMAL_COLLECTION.of(e3(), e4()); + } + + protected MINIMAL_COLLECTION KEY_GENERIC_TYPE emptyCollection() { + return MINIMAL_COLLECTION.of(); + } + + public KEY_TYPE[] createArray(KEY_TYPE...array) { + return array; + } + + protected final KEY_TYPE e0() { + return samples.e0(); + } + + protected final KEY_TYPE e1() { + return samples.e1(); + } + + protected final KEY_TYPE e2() { + return samples.e2(); + } + + protected final KEY_TYPE e3() { + return samples.e3(); + } + + protected final KEY_TYPE e4() { + return samples.e4(); + } + + protected E createTestSubject() { + return (E)primitiveGenerator.create(getSampleElements(size.getNumElements()).TO_ARRAY(NEW_KEY_ARRAY(getNumElements()))); + } + + protected COLLECTION KEY_GENERIC_TYPE getSampleElements(int howMany) { + return new ARRAY_LISTBRACES(samples.asList().subList(0, howMany)); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/base/AbstractListIndexOfTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/base/AbstractListIndexOfTester.template index 083241e..2702433 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/base/AbstractListIndexOfTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/base/AbstractListIndexOfTester.template @@ -1,27 +1,27 @@ -package speiger.src.testers.PACKAGE.tests.base; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; - -@Ignore -@SuppressWarnings("javadoc") -public abstract class ABSTRACT_LIST_INDEX_OF_TESTER KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ - protected abstract int find(KEY_TYPE o); - - protected abstract String getMethodName(); - - @CollectionSize.Require(absent = ZERO) - public void testFind_yes() { - assertEquals(getMethodName() + "(firstElement) should return 0", 0, find(getOrderedElements().GET_KEY(0))); - } - - public void testFind_no() { - assertEquals(getMethodName() + "(notPresent) should return -1", -1, find(e3())); - } -} +package speiger.src.testers.PACKAGE.tests.base; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; + +@Ignore +@SuppressWarnings("javadoc") +public abstract class ABSTRACT_LIST_INDEX_OF_TESTER KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ + protected abstract int find(KEY_TYPE o); + + protected abstract String getMethodName(); + + @CollectionSize.Require(absent = ZERO) + public void testFind_yes() { + assertEquals(getMethodName() + "(firstElement) should return 0", 0, find(getOrderedElements().GET_KEY(0))); + } + + public void testFind_no() { + assertEquals(getMethodName() + "(notPresent) should return -1", -1, find(e3())); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/base/AbstractListTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/base/AbstractListTester.template index 0eec85e..65d2b78 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/base/AbstractListTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/base/AbstractListTester.template @@ -1,39 +1,39 @@ -package speiger.src.testers.PACKAGE.tests.base; - -import org.junit.Ignore; - -#if TYPE_OBJECT -import java.util.Objects; -#endif - -import speiger.src.collections.PACKAGE.collections.COLLECTION; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.testers.PACKAGE.utils.HELPERS; - -@Ignore -@SuppressWarnings("javadoc") -public class ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE -{ - protected final LIST KEY_GENERIC_TYPE getList() { - return (LIST KEY_GENERIC_TYPE) collection; - } - - @Override - protected void expectContents(COLLECTION KEY_GENERIC_TYPE expectedCollection) { - LIST KEY_GENERIC_TYPE expectedList = HELPERS.copyToList(expectedCollection); - if (getList().size() != expectedList.size()) { - fail("size mismatch: " + reportContext(expectedList)); - } - for (int i = 0; i < expectedList.size(); i++) { - KEY_TYPE expected = expectedList.GET_KEY(i); - KEY_TYPE actual = getList().GET_KEY(i); - if (KEY_EQUALS_NOT(expected, actual)) { - fail("mismatch at index " + i + ": " + reportContext(expectedList)); - } - } - } - - private String reportContext(LIST KEY_GENERIC_TYPE expected) { - return String.format("expected collection %s; actual collection %s", expected, collection); - } +package speiger.src.testers.PACKAGE.tests.base; + +import org.junit.Ignore; + +#if TYPE_OBJECT +import java.util.Objects; +#endif + +import speiger.src.collections.PACKAGE.collections.COLLECTION; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.testers.PACKAGE.utils.HELPERS; + +@Ignore +@SuppressWarnings("javadoc") +public class ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE +{ + protected final LIST KEY_GENERIC_TYPE getList() { + return (LIST KEY_GENERIC_TYPE) collection; + } + + @Override + protected void expectContents(COLLECTION KEY_GENERIC_TYPE expectedCollection) { + LIST KEY_GENERIC_TYPE expectedList = HELPERS.copyToList(expectedCollection); + if (getList().size() != expectedList.size()) { + fail("size mismatch: " + reportContext(expectedList)); + } + for (int i = 0; i < expectedList.size(); i++) { + KEY_TYPE expected = expectedList.GET_KEY(i); + KEY_TYPE actual = getList().GET_KEY(i); + if (KEY_EQUALS_NOT(expected, actual)) { + fail("mismatch at index " + i + ": " + reportContext(expectedList)); + } + } + } + + private String reportContext(LIST KEY_GENERIC_TYPE expected) { + return String.format("expected collection %s; actual collection %s", expected, collection); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/base/AbstractQueueTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/base/AbstractQueueTester.template index faee9c3..586423a 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/base/AbstractQueueTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/base/AbstractQueueTester.template @@ -1,81 +1,81 @@ -package speiger.src.testers.PACKAGE.tests.base; - -#if TYPE_OBJECT -import java.util.Objects; -#endif - -import org.junit.Ignore; - -import com.google.common.collect.testing.TestContainerGenerator; - -import speiger.src.collections.PACKAGE.collections.COLLECTION; -import speiger.src.collections.PACKAGE.collections.ITERATOR; -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.collections.PACKAGE.queues.PRIORITY_QUEUE; -import speiger.src.collections.PACKAGE.utils.LISTS; -import speiger.src.testers.PACKAGE.generators.TEST_QUEUE_GENERATOR; -import speiger.src.testers.PACKAGE.utils.HELPERS; - -@Ignore -@SuppressWarnings("javadoc") -public class ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE extends ABSTRACT_CONTAINER_TESTER KKS_GENERIC_TYPE -{ - protected TEST_QUEUE_GENERATOR KEY_GENERIC_TYPE queueGenerator; - protected PRIORITY_QUEUE KEY_GENERIC_TYPE queue; - - @Override - protected void setupGenerator() { - TestContainerGenerator generator = getSubjectGenerator().getInnerGenerator(); - if (!(generator instanceof TEST_QUEUE_GENERATOR)) throw new IllegalStateException("Test Generator Must extend TestLongCollectionGenerator"); - queueGenerator = (TEST_QUEUE_GENERATOR KEY_GENERIC_TYPE) generator; - samples = queueGenerator.getSamples(); - size = getSubjectGenerator().getCollectionSize(); - resetContainer(); - } - - @Override - protected COLLECTION KEY_GENERIC_TYPE actualContents() { return null; } - - @Override - protected PRIORITY_QUEUE KEY_GENERIC_TYPE resetContainer(PRIORITY_QUEUE KEY_GENERIC_TYPE newValue) { - queue = super.resetContainer(newValue); - return queue; - } - - protected void resetQueue() { - resetContainer(); - } - - protected LIST KEY_GENERIC_TYPE getOrderedElements() { - LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); - for (ITERATOR KEY_GENERIC_TYPE iter = queueGenerator.order(new ARRAY_LISTBRACES(getSampleElements())).iterator(); iter.hasNext();) { - list.add(iter.NEXT()); - } - return LISTS.unmodifiable(list); - } - - @Override - protected PRIORITY_QUEUE KEY_GENERIC_TYPE createTestSubject() { - return queueGenerator.create(getSampleElements(size.getNumElements()).TO_ARRAY(NEW_KEY_ARRAY(getNumElements()))); - } - - @Override - protected void expectContents(COLLECTION KEY_GENERIC_TYPE expected) { - HELPERS.assertContentsAnyOrder(expected, queue.TO_ARRAY()); - } - - @Override - protected void expectMissing(KEY_TYPE... elements) { - for (KEY_TYPE element : elements) { - assertFalse("Should not contain " + element, contains(element)); - } - } - - protected boolean contains(KEY_TYPE element) { - for(int i = 0,m=queue.size();i +{ + protected TEST_QUEUE_GENERATOR KEY_GENERIC_TYPE queueGenerator; + protected PRIORITY_QUEUE KEY_GENERIC_TYPE queue; + + @Override + protected void setupGenerator() { + TestContainerGenerator generator = getSubjectGenerator().getInnerGenerator(); + if (!(generator instanceof TEST_QUEUE_GENERATOR)) throw new IllegalStateException("Test Generator Must extend TestLongCollectionGenerator"); + queueGenerator = (TEST_QUEUE_GENERATOR KEY_GENERIC_TYPE) generator; + samples = queueGenerator.getSamples(); + size = getSubjectGenerator().getCollectionSize(); + resetContainer(); + } + + @Override + protected COLLECTION KEY_GENERIC_TYPE actualContents() { return null; } + + @Override + protected PRIORITY_QUEUE KEY_GENERIC_TYPE resetContainer(PRIORITY_QUEUE KEY_GENERIC_TYPE newValue) { + queue = super.resetContainer(newValue); + return queue; + } + + protected void resetQueue() { + resetContainer(); + } + + protected LIST KEY_GENERIC_TYPE getOrderedElements() { + LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); + for (ITERATOR KEY_GENERIC_TYPE iter = queueGenerator.order(new ARRAY_LISTBRACES(getSampleElements())).iterator(); iter.hasNext();) { + list.add(iter.NEXT()); + } + return LISTS.unmodifiable(list); + } + + @Override + protected PRIORITY_QUEUE KEY_GENERIC_TYPE createTestSubject() { + return queueGenerator.create(getSampleElements(size.getNumElements()).TO_ARRAY(NEW_KEY_ARRAY(getNumElements()))); + } + + @Override + protected void expectContents(COLLECTION KEY_GENERIC_TYPE expected) { + HELPERS.assertContentsAnyOrder(expected, queue.TO_ARRAY()); + } + + @Override + protected void expectMissing(KEY_TYPE... elements) { + for (KEY_TYPE element : elements) { + assertFalse("Should not contain " + element, contains(element)); + } + } + + protected boolean contains(KEY_TYPE element) { + for(int i = 0,m=queue.size();i -{ - protected TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE primitiveMapGenerator; - - protected MAP KEY_VALUE_GENERIC_TYPE getMap() { - return container; - } - - @Override - protected void setupGenerator() { - TestContainerGenerator, ? extends Map.Entry> generator = getSubjectGenerator().getInnerGenerator(); - if (!(generator instanceof TEST_MAP_GENERATOR)) throw new IllegalStateException("Test Generator Must extend TestLong2ByteMapGenerator"); - primitiveMapGenerator = (TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE) generator; - samples = primitiveMapGenerator.getSamples(); - size = getSubjectGenerator().getCollectionSize(); - resetContainer(); - } - - @Override - protected MAP KEY_VALUE_GENERIC_TYPE createTestSubject() { - return primitiveMapGenerator.create(getSampleElements(size.getNumElements()).toArray(new MAP.Entry[getNumElements()])); - } - - @Override - protected ObjectList getOrderedElements() { - ObjectList list = new ObjectArrayList<>(); - for (ObjectIterator iter = primitiveMapGenerator.order(new ObjectArrayList(getSampleElements())).iterator(); iter.hasNext();) { - list.add(iter.next()); - } - return ObjectLists.unmodifiable(list); - } - - @Override - protected ObjectCollection actualContents() { - return getMap().ENTRY_SET(); - } - - protected final void resetMap() { - resetContainer(); - } - - protected void resetMap(MAP.Entry KEY_VALUE_GENERIC_TYPE[] entries) { - resetContainer(primitiveMapGenerator.create(entries)); - } - - @Override - protected MAP KEY_VALUE_GENERIC_TYPE resetContainer(MAP KEY_VALUE_GENERIC_TYPE newValue) { - newValue.setDefaultReturnValue(INVALID_VALUE); - return super.resetContainer(newValue); - } - - protected void expectMissingKeys(KEY_TYPE... elements) { - for (KEY_TYPE element : elements) { - assertFalse("Should not contain key " + element, getMap().containsKey(element)); - } - } - - protected void expectMissingValues(VALUE_TYPE... elements) { - for (VALUE_TYPE element : elements) { - assertFalse("Should not contain value " + element, getMap().containsValue(element)); - } - } - - protected int getNumEntries() { - return getNumElements(); - } - - protected ObjectCollection getSampleEntries(int howMany) { - return getSampleElements(howMany); - } - - protected ObjectCollection getSampleEntries() { - return getSampleElements(); - } - - @Override - protected void expectMissing(MAP.Entry KEY_VALUE_GENERIC_TYPE... entries) { - for (MAP.Entry KEY_VALUE_GENERIC_TYPE entry : entries) { - assertFalse("Should not contain entry " + entry, actualContents().contains(entry)); -#if !VALUE_BOOLEAN - assertFalse("Should not contain key " + entry.ENTRY_KEY() + " mapped to value " + entry.ENTRY_VALUE(), valueEquals(getMap().get(entry.ENTRY_KEY()), entry.ENTRY_VALUE())); -#endif - } - } - - @Override - protected void expectContents(ObjectCollection expected) { - super.expectContents(expected); - for (MAP.Entry KEY_VALUE_GENERIC_TYPE entry : expected) { - assertEquals("Wrong value for key " + entry.ENTRY_KEY(), entry.ENTRY_VALUE(), getMap().GET_VALUE(entry.ENTRY_KEY())); - } - } - - protected final void expectReplacement(MAP.Entry KEY_VALUE_GENERIC_TYPE newEntry) { - ObjectList expected = ObjectHelpers.copyToList(getSampleElements()); - replaceValue(expected, newEntry); - expectContents(expected); - } - - private void replaceValue(ObjectList expected, MAP.Entry KEY_VALUE_GENERIC_TYPE newEntry) { - for (ObjectListIterator i = expected.listIterator(); i.hasNext();) { - if (HELPERS.equals(i.next().ENTRY_KEY(), newEntry.ENTRY_KEY())) { - i.set(newEntry); - return; - } - } - throw new IllegalArgumentException(String.format(Locale.ROOT, "key %s not found in entries %s", newEntry.ENTRY_KEY(), expected)); - } - -#if !VALUE_BOOLEAN - private static GENERIC_VALUE_BRACES boolean valueEquals(VALUE_TYPE a, VALUE_TYPE b) { - return VALUE_EQUALS(a, b); - } - -#endif - protected MAP.Entry KEY_VALUE_GENERIC_TYPE entry(KEY_TYPE key, VALUE_TYPE value) { - return new ABSTRACT_MAP.BasicEntryKV_BRACES(key, value); - } - - protected KEY_TYPE[] emptyKeyArray() { - return NEW_KEY_ARRAY(0); - } - - protected KEY_TYPE[] createDisjointedKeyArray() { - KEY_TYPE[] array = NEW_KEY_ARRAY(2); - array[0] = k3(); - array[1] = k4(); - return array; - } - - protected CLASS_TYPE[] emptyKeyObjectArray() { - return NEW_CLASS_ARRAY(0); - } - - protected CLASS_TYPE[] createDisjointedKeyObjectArray() { - CLASS_TYPE[] array = NEW_CLASS_ARRAY(2); - array[0] = k3(); - array[1] = k4(); - return array; - } - - protected VALUE_TYPE[] emptyValueArray() { - return NEW_VALUE_ARRAY(0); - } - - protected VALUE_TYPE[] createDisjointedValueArray() { - VALUE_TYPE[] array = NEW_VALUE_ARRAY(2); - array[0] = v3(); - array[1] = v4(); - return array; - } - - protected CLASS_VALUE_TYPE[] emptyValueObjectArray() { - return NEW_CLASS_VALUE_ARRAY(0); - } - - protected CLASS_VALUE_TYPE[] createDisjointedValueObjectArray() { - CLASS_VALUE_TYPE[] array = NEW_CLASS_VALUE_ARRAY(2); - array[0] = v3(); - array[1] = v4(); - return array; - } - - protected VALUE_TYPE get(KEY_TYPE key) { - return getMap().GET_VALUE(key); - } - -#if !TYPE_OBJECT - @SuppressWarnings("deprecation") - protected CLASS_VALUE_TYPE get(CLASS_TYPE key) { - return getMap().get(key); - } - -#endif - protected final KEY_TYPE k0() { - return e0().ENTRY_KEY(); - } - - protected final VALUE_TYPE v0() { - return e0().ENTRY_VALUE(); - } - - protected final KEY_TYPE k1() { - return e1().ENTRY_KEY(); - } - - protected final VALUE_TYPE v1() { - return e1().ENTRY_VALUE(); - } - - protected final KEY_TYPE k2() { - return e2().ENTRY_KEY(); - } - - protected final VALUE_TYPE v2() { - return e2().ENTRY_VALUE(); - } - - protected final KEY_TYPE k3() { - return e3().ENTRY_KEY(); - } - - protected final VALUE_TYPE v3() { - return e3().ENTRY_VALUE(); - } - - protected final KEY_TYPE k4() { - return e4().ENTRY_KEY(); - } - - protected final VALUE_TYPE v4() { - return e4().ENTRY_VALUE(); - } -} +package speiger.src.testers.PACKAGE.tests.base.maps; + +import java.util.Locale; +import java.util.Map; +#if VALUE_OBJECT +import java.util.Objects; +#endif + +import org.junit.Ignore; + +import com.google.common.collect.testing.TestContainerGenerator; + +import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.collections.objects.collections.ObjectCollection; +import speiger.src.collections.objects.collections.ObjectIterator; +import speiger.src.collections.objects.lists.ObjectArrayList; +import speiger.src.collections.objects.lists.ObjectList; +import speiger.src.collections.objects.lists.ObjectListIterator; +import speiger.src.collections.objects.utils.ObjectLists; +import speiger.src.testers.PACKAGE.generators.maps.TEST_MAP_GENERATOR; +#if !TYPE_OBJECT +import speiger.src.testers.PACKAGE.utils.HELPERS; +#endif +import speiger.src.testers.objects.tests.base.AbstractObjectContainerTester; +import speiger.src.testers.objects.utils.ObjectHelpers; + +@Ignore +@SuppressWarnings("javadoc") +public class ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE extends AbstractObjectContainerTester +{ + protected TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE primitiveMapGenerator; + + protected MAP KEY_VALUE_GENERIC_TYPE getMap() { + return container; + } + + @Override + protected void setupGenerator() { + TestContainerGenerator, ? extends Map.Entry> generator = getSubjectGenerator().getInnerGenerator(); + if (!(generator instanceof TEST_MAP_GENERATOR)) throw new IllegalStateException("Test Generator Must extend TestLong2ByteMapGenerator"); + primitiveMapGenerator = (TEST_MAP_GENERATOR KEY_VALUE_GENERIC_TYPE) generator; + samples = primitiveMapGenerator.getSamples(); + size = getSubjectGenerator().getCollectionSize(); + resetContainer(); + } + + @Override + protected MAP KEY_VALUE_GENERIC_TYPE createTestSubject() { + return primitiveMapGenerator.create(getSampleElements(size.getNumElements()).toArray(new MAP.Entry[getNumElements()])); + } + + @Override + protected ObjectList getOrderedElements() { + ObjectList list = new ObjectArrayList<>(); + for (ObjectIterator iter = primitiveMapGenerator.order(new ObjectArrayList(getSampleElements())).iterator(); iter.hasNext();) { + list.add(iter.next()); + } + return ObjectLists.unmodifiable(list); + } + + @Override + protected ObjectCollection actualContents() { + return getMap().ENTRY_SET(); + } + + protected final void resetMap() { + resetContainer(); + } + + protected void resetMap(MAP.Entry KEY_VALUE_GENERIC_TYPE[] entries) { + resetContainer(primitiveMapGenerator.create(entries)); + } + + @Override + protected MAP KEY_VALUE_GENERIC_TYPE resetContainer(MAP KEY_VALUE_GENERIC_TYPE newValue) { + newValue.setDefaultReturnValue(INVALID_VALUE); + return super.resetContainer(newValue); + } + + protected void expectMissingKeys(KEY_TYPE... elements) { + for (KEY_TYPE element : elements) { + assertFalse("Should not contain key " + element, getMap().containsKey(element)); + } + } + + protected void expectMissingValues(VALUE_TYPE... elements) { + for (VALUE_TYPE element : elements) { + assertFalse("Should not contain value " + element, getMap().containsValue(element)); + } + } + + protected int getNumEntries() { + return getNumElements(); + } + + protected ObjectCollection getSampleEntries(int howMany) { + return getSampleElements(howMany); + } + + protected ObjectCollection getSampleEntries() { + return getSampleElements(); + } + + @Override + protected void expectMissing(MAP.Entry KEY_VALUE_GENERIC_TYPE... entries) { + for (MAP.Entry KEY_VALUE_GENERIC_TYPE entry : entries) { + assertFalse("Should not contain entry " + entry, actualContents().contains(entry)); +#if !VALUE_BOOLEAN + assertFalse("Should not contain key " + entry.ENTRY_KEY() + " mapped to value " + entry.ENTRY_VALUE(), valueEquals(getMap().get(entry.ENTRY_KEY()), entry.ENTRY_VALUE())); +#endif + } + } + + @Override + protected void expectContents(ObjectCollection expected) { + super.expectContents(expected); + for (MAP.Entry KEY_VALUE_GENERIC_TYPE entry : expected) { + assertEquals("Wrong value for key " + entry.ENTRY_KEY(), entry.ENTRY_VALUE(), getMap().GET_VALUE(entry.ENTRY_KEY())); + } + } + + protected final void expectReplacement(MAP.Entry KEY_VALUE_GENERIC_TYPE newEntry) { + ObjectList expected = ObjectHelpers.copyToList(getSampleElements()); + replaceValue(expected, newEntry); + expectContents(expected); + } + + private void replaceValue(ObjectList expected, MAP.Entry KEY_VALUE_GENERIC_TYPE newEntry) { + for (ObjectListIterator i = expected.listIterator(); i.hasNext();) { + if (HELPERS.equals(i.next().ENTRY_KEY(), newEntry.ENTRY_KEY())) { + i.set(newEntry); + return; + } + } + throw new IllegalArgumentException(String.format(Locale.ROOT, "key %s not found in entries %s", newEntry.ENTRY_KEY(), expected)); + } + +#if !VALUE_BOOLEAN + private static GENERIC_VALUE_BRACES boolean valueEquals(VALUE_TYPE a, VALUE_TYPE b) { + return VALUE_EQUALS(a, b); + } + +#endif + protected MAP.Entry KEY_VALUE_GENERIC_TYPE entry(KEY_TYPE key, VALUE_TYPE value) { + return new ABSTRACT_MAP.BasicEntryKV_BRACES(key, value); + } + + protected KEY_TYPE[] emptyKeyArray() { + return NEW_KEY_ARRAY(0); + } + + protected KEY_TYPE[] createDisjointedKeyArray() { + KEY_TYPE[] array = NEW_KEY_ARRAY(2); + array[0] = k3(); + array[1] = k4(); + return array; + } + + protected CLASS_TYPE[] emptyKeyObjectArray() { + return NEW_CLASS_ARRAY(0); + } + + protected CLASS_TYPE[] createDisjointedKeyObjectArray() { + CLASS_TYPE[] array = NEW_CLASS_ARRAY(2); + array[0] = k3(); + array[1] = k4(); + return array; + } + + protected VALUE_TYPE[] emptyValueArray() { + return NEW_VALUE_ARRAY(0); + } + + protected VALUE_TYPE[] createDisjointedValueArray() { + VALUE_TYPE[] array = NEW_VALUE_ARRAY(2); + array[0] = v3(); + array[1] = v4(); + return array; + } + + protected CLASS_VALUE_TYPE[] emptyValueObjectArray() { + return NEW_CLASS_VALUE_ARRAY(0); + } + + protected CLASS_VALUE_TYPE[] createDisjointedValueObjectArray() { + CLASS_VALUE_TYPE[] array = NEW_CLASS_VALUE_ARRAY(2); + array[0] = v3(); + array[1] = v4(); + return array; + } + + protected VALUE_TYPE get(KEY_TYPE key) { + return getMap().GET_VALUE(key); + } + +#if !TYPE_OBJECT + @SuppressWarnings("deprecation") + protected CLASS_VALUE_TYPE get(CLASS_TYPE key) { + return getMap().get(key); + } + +#endif + protected final KEY_TYPE k0() { + return e0().ENTRY_KEY(); + } + + protected final VALUE_TYPE v0() { + return e0().ENTRY_VALUE(); + } + + protected final KEY_TYPE k1() { + return e1().ENTRY_KEY(); + } + + protected final VALUE_TYPE v1() { + return e1().ENTRY_VALUE(); + } + + protected final KEY_TYPE k2() { + return e2().ENTRY_KEY(); + } + + protected final VALUE_TYPE v2() { + return e2().ENTRY_VALUE(); + } + + protected final KEY_TYPE k3() { + return e3().ENTRY_KEY(); + } + + protected final VALUE_TYPE v3() { + return e3().ENTRY_VALUE(); + } + + protected final KEY_TYPE k4() { + return e4().ENTRY_KEY(); + } + + protected final VALUE_TYPE v4() { + return e4().ENTRY_VALUE(); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionAddAllArrayTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionAddAllArrayTester.template index c1d62f9..d02d277 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionAddAllArrayTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionAddAllArrayTester.template @@ -1,151 +1,151 @@ -package speiger.src.testers.PACKAGE.tests.collection; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import java.util.ConcurrentModificationException; - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.collections.ITERATOR; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPECollectionAddAllArrayTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) - public void testAddAllArray_supportedNothing() { - assertFalse("addAll(nothing[]) should return false", collection.addAll(emptyArray())); - expectUnchanged(); - } - - @CollectionFeature.Require(absent = SUPPORTS_ADD) - public void testAddAllArray_unsupportedNothing() { - try { - assertFalse("addAll(nothing[]) should return false or throw", collection.addAll(emptyArray())); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } - - @CollectionFeature.Require(SUPPORTS_ADD) - public void testAddAllArray_supportedNonePresent() { - assertTrue("addAll(nonePresent[]) should return true", collection.addAll(createDisjointArray())); - expectAdded(e3(), e4()); - } - - @CollectionFeature.Require(absent = SUPPORTS_ADD) - public void testAddAllArray_unsupportedNonePresent() { - try { - collection.addAll(createDisjointArray()); - fail("addAll(nonePresent[]) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - expectMissing(e3(), e4()); - } -#endignore - -#if !TYPE_BOOLEAN -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) -#endignore - public void testAddAllArray_supportedToLargeOffset() { - try { - collection.addAll(createDisjointArray(), 5, 2); - } catch (IndexOutOfBoundsException e) { - } - expectUnchanged(); - expectMissing(e3(), e4()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) -#endignore - public void testAddAllArray_supportedToLargeArray() { - try { - collection.addAll(createDisjointArray(), 3); - } catch (IndexOutOfBoundsException e) { - } - expectUnchanged(); - expectMissing(e3(), e4()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) -#endignore - public void testAddAllArray_supportedToSmallOffset() { - try { - collection.addAll(createDisjointArray(), -1, 2); - } catch (IndexOutOfBoundsException e) { - } - expectUnchanged(); - expectMissing(e3(), e4()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) -#endignore - public void testAddAllArray_supportedAddSubArray() { - try { - collection.addAll(createDisjointArray(), 1); - } catch (IndexOutOfBoundsException e) { - } - expectAdded(e3()); - expectMissing(e4()); - } -#endif -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) - @CollectionSize.Require(absent = ZERO) - public void testAddAllArray_supportedSomePresent() { - assertTrue("addAll(somePresent[]) should return true", collection.addAll(e3(), e0())); - assertTrue("should contain " + e3(), collection.contains(e3())); - assertTrue("should contain " + e0(), collection.contains(e0())); - } - - @CollectionFeature.Require(absent = SUPPORTS_ADD) - @CollectionSize.Require(absent = ZERO) - public void testAddAllArray_unsupportedSomePresent() { - try { - collection.addAll(e3(), e0()); - fail("addAll(somePresent[]) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } - - @CollectionFeature.Require({ SUPPORTS_ADD, FAILS_FAST_ON_CONCURRENT_MODIFICATION }) - @CollectionSize.Require(absent = ZERO) - public void testAddAllArrayConcurrentWithIteration() { -#endignore - try { - ITERATOR KEY_GENERIC_TYPE iterator = collection.iterator(); - assertTrue(collection.addAll(e3(), e0())); - iterator.NEXT(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#ignore - @CollectionFeature.Require(absent = SUPPORTS_ADD) - @CollectionSize.Require(absent = ZERO) - public void testAddAllArray_unsupportedAllPresent() { - try { - assertFalse("addAll(allPresent[]) should return false or throw", collection.addAll(e0())); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } -#endignore +package speiger.src.testers.PACKAGE.tests.collection; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import java.util.ConcurrentModificationException; + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.collections.ITERATOR; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPECollectionAddAllArrayTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) + public void testAddAllArray_supportedNothing() { + assertFalse("addAll(nothing[]) should return false", collection.addAll(emptyArray())); + expectUnchanged(); + } + + @CollectionFeature.Require(absent = SUPPORTS_ADD) + public void testAddAllArray_unsupportedNothing() { + try { + assertFalse("addAll(nothing[]) should return false or throw", collection.addAll(emptyArray())); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } + + @CollectionFeature.Require(SUPPORTS_ADD) + public void testAddAllArray_supportedNonePresent() { + assertTrue("addAll(nonePresent[]) should return true", collection.addAll(createDisjointArray())); + expectAdded(e3(), e4()); + } + + @CollectionFeature.Require(absent = SUPPORTS_ADD) + public void testAddAllArray_unsupportedNonePresent() { + try { + collection.addAll(createDisjointArray()); + fail("addAll(nonePresent[]) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + expectMissing(e3(), e4()); + } +#endignore + +#if !TYPE_BOOLEAN +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) +#endignore + public void testAddAllArray_supportedToLargeOffset() { + try { + collection.addAll(createDisjointArray(), 5, 2); + } catch (IndexOutOfBoundsException e) { + } + expectUnchanged(); + expectMissing(e3(), e4()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) +#endignore + public void testAddAllArray_supportedToLargeArray() { + try { + collection.addAll(createDisjointArray(), 3); + } catch (IndexOutOfBoundsException e) { + } + expectUnchanged(); + expectMissing(e3(), e4()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) +#endignore + public void testAddAllArray_supportedToSmallOffset() { + try { + collection.addAll(createDisjointArray(), -1, 2); + } catch (IndexOutOfBoundsException e) { + } + expectUnchanged(); + expectMissing(e3(), e4()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) +#endignore + public void testAddAllArray_supportedAddSubArray() { + try { + collection.addAll(createDisjointArray(), 1); + } catch (IndexOutOfBoundsException e) { + } + expectAdded(e3()); + expectMissing(e4()); + } +#endif +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) + @CollectionSize.Require(absent = ZERO) + public void testAddAllArray_supportedSomePresent() { + assertTrue("addAll(somePresent[]) should return true", collection.addAll(e3(), e0())); + assertTrue("should contain " + e3(), collection.contains(e3())); + assertTrue("should contain " + e0(), collection.contains(e0())); + } + + @CollectionFeature.Require(absent = SUPPORTS_ADD) + @CollectionSize.Require(absent = ZERO) + public void testAddAllArray_unsupportedSomePresent() { + try { + collection.addAll(e3(), e0()); + fail("addAll(somePresent[]) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } + + @CollectionFeature.Require({ SUPPORTS_ADD, FAILS_FAST_ON_CONCURRENT_MODIFICATION }) + @CollectionSize.Require(absent = ZERO) + public void testAddAllArrayConcurrentWithIteration() { +#endignore + try { + ITERATOR KEY_GENERIC_TYPE iterator = collection.iterator(); + assertTrue(collection.addAll(e3(), e0())); + iterator.NEXT(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#ignore + @CollectionFeature.Require(absent = SUPPORTS_ADD) + @CollectionSize.Require(absent = ZERO) + public void testAddAllArray_unsupportedAllPresent() { + try { + assertFalse("addAll(allPresent[]) should return false or throw", collection.addAll(e0())); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } +#endignore } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionAddAllTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionAddAllTester.template index f41e199..cc4802f 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionAddAllTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionAddAllTester.template @@ -1,102 +1,102 @@ -package speiger.src.testers.PACKAGE.tests.collection; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import java.util.ConcurrentModificationException; - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.collections.ITERATOR; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; -import speiger.src.testers.PACKAGE.utils.MINIMAL_COLLECTION; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPECollectionAddAllTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) - public void testAddAll_supportedNothing() { - assertFalse("addAll(nothing) should return false", collection.addAll(emptyCollection())); - expectUnchanged(); - } - - @CollectionFeature.Require(absent = SUPPORTS_ADD) - public void testAddAll_unsupportedNothing() { - try { - assertFalse("addAll(nothing) should return false or throw", collection.addAll(emptyCollection())); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } - - @CollectionFeature.Require(SUPPORTS_ADD) - public void testAddAll_supportedNonePresent() { - assertTrue("addAll(nonePresent) should return true", collection.addAll(createDisjointCollection())); - expectAdded(e3(), e4()); - } - - @CollectionFeature.Require(absent = SUPPORTS_ADD) - public void testAddAll_unsupportedNonePresent() { - try { - collection.addAll(createDisjointCollection()); - fail("addAll(nonePresent) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - expectMissing(e3(), e4()); - } - - @CollectionFeature.Require(SUPPORTS_ADD) - @CollectionSize.Require(absent = ZERO) - public void testAddAll_supportedSomePresent() { -#endignore - assertTrue("addAll(somePresent) should return true", collection.addAll(MINIMAL_COLLECTION.of(e3(), e0()))); - assertTrue("should contain " + e3(), collection.contains(e3())); - assertTrue("should contain " + e0(), collection.contains(e0())); - } -#ignore - @CollectionFeature.Require(absent = SUPPORTS_ADD) - @CollectionSize.Require(absent = ZERO) - public void testAddAll_unsupportedSomePresent() { -#endignore - try { - collection.addAll(MINIMAL_COLLECTION.of(e3(), e0())); - fail("addAll(somePresent) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } - -#ignore - @CollectionFeature.Require({ SUPPORTS_ADD, FAILS_FAST_ON_CONCURRENT_MODIFICATION }) - @CollectionSize.Require(absent = ZERO) - public void testAddAllConcurrentWithIteration() { -#endignore - try { - ITERATOR KEY_GENERIC_TYPE iterator = collection.iterator(); - assertTrue(collection.addAll(MINIMAL_COLLECTION.of(e3(), e0()))); - iterator.NEXT(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - - @CollectionFeature.Require(absent = SUPPORTS_ADD) - @CollectionSize.Require(absent = ZERO) - public void testAddAll_unsupportedAllPresent() { - try { - assertFalse("addAll(allPresent) should return false or throw", collection.addAll(MINIMAL_COLLECTION.of(e0()))); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } -} +package speiger.src.testers.PACKAGE.tests.collection; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import java.util.ConcurrentModificationException; + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.collections.ITERATOR; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; +import speiger.src.testers.PACKAGE.utils.MINIMAL_COLLECTION; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPECollectionAddAllTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) + public void testAddAll_supportedNothing() { + assertFalse("addAll(nothing) should return false", collection.addAll(emptyCollection())); + expectUnchanged(); + } + + @CollectionFeature.Require(absent = SUPPORTS_ADD) + public void testAddAll_unsupportedNothing() { + try { + assertFalse("addAll(nothing) should return false or throw", collection.addAll(emptyCollection())); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } + + @CollectionFeature.Require(SUPPORTS_ADD) + public void testAddAll_supportedNonePresent() { + assertTrue("addAll(nonePresent) should return true", collection.addAll(createDisjointCollection())); + expectAdded(e3(), e4()); + } + + @CollectionFeature.Require(absent = SUPPORTS_ADD) + public void testAddAll_unsupportedNonePresent() { + try { + collection.addAll(createDisjointCollection()); + fail("addAll(nonePresent) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + expectMissing(e3(), e4()); + } + + @CollectionFeature.Require(SUPPORTS_ADD) + @CollectionSize.Require(absent = ZERO) + public void testAddAll_supportedSomePresent() { +#endignore + assertTrue("addAll(somePresent) should return true", collection.addAll(MINIMAL_COLLECTION.of(e3(), e0()))); + assertTrue("should contain " + e3(), collection.contains(e3())); + assertTrue("should contain " + e0(), collection.contains(e0())); + } +#ignore + @CollectionFeature.Require(absent = SUPPORTS_ADD) + @CollectionSize.Require(absent = ZERO) + public void testAddAll_unsupportedSomePresent() { +#endignore + try { + collection.addAll(MINIMAL_COLLECTION.of(e3(), e0())); + fail("addAll(somePresent) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } + +#ignore + @CollectionFeature.Require({ SUPPORTS_ADD, FAILS_FAST_ON_CONCURRENT_MODIFICATION }) + @CollectionSize.Require(absent = ZERO) + public void testAddAllConcurrentWithIteration() { +#endignore + try { + ITERATOR KEY_GENERIC_TYPE iterator = collection.iterator(); + assertTrue(collection.addAll(MINIMAL_COLLECTION.of(e3(), e0()))); + iterator.NEXT(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + + @CollectionFeature.Require(absent = SUPPORTS_ADD) + @CollectionSize.Require(absent = ZERO) + public void testAddAll_unsupportedAllPresent() { + try { + assertFalse("addAll(allPresent) should return false or throw", collection.addAll(MINIMAL_COLLECTION.of(e0()))); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionAddTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionAddTester.template index 180dc9a..32e42e2 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionAddTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionAddTester.template @@ -1,64 +1,64 @@ -package speiger.src.testers.PACKAGE.tests.collection; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import java.util.ConcurrentModificationException; - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.collections.ITERATOR; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPECollectionAddTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) - public void testAdd_supportedNotPresent() { - assertTrue("add(notPresent) should return true", collection.add(e3())); - expectAdded(e3()); - } - - @CollectionFeature.Require(absent = SUPPORTS_ADD) - public void testAdd_unsupportedNotPresent() { - try { - collection.add(e3()); - fail("add(notPresent) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - expectMissing(e3()); - } - - @CollectionFeature.Require(absent = SUPPORTS_ADD) - @CollectionSize.Require(absent = ZERO) - public void testAdd_unsupportedPresent() { - try { - assertFalse("add(present) should return false or throw", collection.add(e0())); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } - - @CollectionFeature.Require({ SUPPORTS_ADD, FAILS_FAST_ON_CONCURRENT_MODIFICATION }) - @CollectionSize.Require(absent = ZERO) - public void testAddConcurrentWithIteration() { -#endignore - try { - ITERATOR KEY_GENERIC_TYPE iterator = collection.iterator(); - assertTrue(collection.add(e3())); - iterator.NEXT(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } -} +package speiger.src.testers.PACKAGE.tests.collection; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import java.util.ConcurrentModificationException; + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.collections.ITERATOR; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPECollectionAddTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) + public void testAdd_supportedNotPresent() { + assertTrue("add(notPresent) should return true", collection.add(e3())); + expectAdded(e3()); + } + + @CollectionFeature.Require(absent = SUPPORTS_ADD) + public void testAdd_unsupportedNotPresent() { + try { + collection.add(e3()); + fail("add(notPresent) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + expectMissing(e3()); + } + + @CollectionFeature.Require(absent = SUPPORTS_ADD) + @CollectionSize.Require(absent = ZERO) + public void testAdd_unsupportedPresent() { + try { + assertFalse("add(present) should return false or throw", collection.add(e0())); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } + + @CollectionFeature.Require({ SUPPORTS_ADD, FAILS_FAST_ON_CONCURRENT_MODIFICATION }) + @CollectionSize.Require(absent = ZERO) + public void testAddConcurrentWithIteration() { +#endignore + try { + ITERATOR KEY_GENERIC_TYPE iterator = collection.iterator(); + assertTrue(collection.add(e3())); + iterator.NEXT(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionClearTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionClearTester.template index 1381bfb..40f1554 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionClearTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionClearTester.template @@ -1,68 +1,68 @@ -package speiger.src.testers.PACKAGE.tests.collection; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; -import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import java.util.ConcurrentModificationException; - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.collections.ITERATOR; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPECollectionClearTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - public void testClear() { - collection.clear(); - assertTrue("After clear(), a collection should be empty.", collection.isEmpty()); - assertEquals(0, collection.size()); - assertFalse(collection.iterator().hasNext()); - } - - @CollectionFeature.Require(absent = SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) - public void testClear_unsupported() { - try { - collection.clear(); - fail("clear() should throw UnsupportedOperation if a collection does " - + "not support it and is not empty."); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } - - @CollectionFeature.Require(absent = SUPPORTS_REMOVE) - @CollectionSize.Require(ZERO) - public void testClear_unsupportedByEmptyCollection() { - try { - collection.clear(); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } - - @CollectionFeature.Require({ SUPPORTS_REMOVE, FAILS_FAST_ON_CONCURRENT_MODIFICATION }) - @CollectionSize.Require(SEVERAL) - public void testClearConcurrentWithIteration() { -#endignore - try { - ITERATOR KEY_GENERIC_TYPE iterator = collection.iterator(); - collection.clear(); - iterator.NEXT(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } -} +package speiger.src.testers.PACKAGE.tests.collection; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; +import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import java.util.ConcurrentModificationException; + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.collections.ITERATOR; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPECollectionClearTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + public void testClear() { + collection.clear(); + assertTrue("After clear(), a collection should be empty.", collection.isEmpty()); + assertEquals(0, collection.size()); + assertFalse(collection.iterator().hasNext()); + } + + @CollectionFeature.Require(absent = SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) + public void testClear_unsupported() { + try { + collection.clear(); + fail("clear() should throw UnsupportedOperation if a collection does " + + "not support it and is not empty."); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } + + @CollectionFeature.Require(absent = SUPPORTS_REMOVE) + @CollectionSize.Require(ZERO) + public void testClear_unsupportedByEmptyCollection() { + try { + collection.clear(); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } + + @CollectionFeature.Require({ SUPPORTS_REMOVE, FAILS_FAST_ON_CONCURRENT_MODIFICATION }) + @CollectionSize.Require(SEVERAL) + public void testClearConcurrentWithIteration() { +#endignore + try { + ITERATOR KEY_GENERIC_TYPE iterator = collection.iterator(); + collection.clear(); + iterator.NEXT(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionConstructorTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionConstructorTester.template index dea1a06..b7d6f54 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionConstructorTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionConstructorTester.template @@ -1,165 +1,165 @@ -package speiger.src.testers.PACKAGE.tests.collection; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.function.Function; -import java.util.function.IntFunction; -import java.util.function.Supplier; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.Ignore; -import junit.framework.TestCase; - -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.collections.COLLECTION; -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.utils.ARRAYS; -#endif -import speiger.src.collections.utils.ITrimmable; - -@Ignore -@SuppressWarnings("javadoc") -public abstract class FILE_KEY_TYPECollectionConstructorTester KEY_GENERIC_TYPE extends TestCase -{ - protected Supplier simpleConstructor; - protected IntFunction sizeConstructor; - protected Function pArrayConstructor; -#if !TYPE_OBJECT - protected Function arrayConstructor; -#endif - protected Function, COLLECTION KEY_GENERIC_TYPE> collectionConstructor; - protected Function pCollectionConstructor; - protected KEY_TYPE[] keys = createKeyElements(); - - protected void setSimpleConstructor(Supplier simpleConstructor) { - this.simpleConstructor = simpleConstructor; - } - - protected void setSizeConstructor(IntFunction sizeConstructor) { - this.sizeConstructor = sizeConstructor; - } - - protected void setPArrayConstructor(Function pArrayConstructor) { - this.pArrayConstructor = pArrayConstructor; - } - -#if !TYPE_OBJECT - protected void setArrayConstructor(Function arrayConstructor) { - this.arrayConstructor = arrayConstructor; - } - -#endif - protected void setCollectionConstructor(Function, COLLECTION KEY_GENERIC_TYPE> collectionConstructor) { - this.collectionConstructor = collectionConstructor; - } - - protected void setPCollectionConstructor(Function pCollectionConstructor) { - this.pCollectionConstructor = pCollectionConstructor; - } - - @Test - public void testPrimitiveArrayConstructor() { - if(pArrayConstructor == null) return; - Assert.assertTrue(pArrayConstructor.apply(keys) != null); - } - -#if !TYPE_OBJECT - @Test - public void testArrayConstructor() { - if(arrayConstructor == null) return; -#if TYPE_OBJECT - Assert.assertTrue(arrayConstructor.apply(keys) != null); -#else - Assert.assertTrue(arrayConstructor.apply(ARRAYS.wrap(keys)) != null); -#endif - } - -#endif - @Test - public void testPrimitiveMapsConstructor() { - if(pCollectionConstructor == null) return; - Assert.assertTrue(pCollectionConstructor.apply(new ARRAY_LISTBRACES(keys)) != null); - } - - @Test - public void testMapsConstructor() { - if(collectionConstructor == null) return; - Assert.assertTrue(collectionConstructor.apply(new ArrayList<>(new ARRAY_LISTBRACES(keys))) != null); - } - - @Test - public void testSimpleConstructor() { - if(simpleConstructor == null) return; - Assert.assertTrue(simpleConstructor.get() != null); - } - - @Test - public void testSizeConstructor_empty() { - if(sizeConstructor == null) return; - Assert.assertTrue(sizeConstructor.apply(0) != null); - } - - @Test - public void testSizeConstructor_smallSize() { - if(sizeConstructor == null) return; - Assert.assertTrue(sizeConstructor.apply(32) != null); - } - - @Test - public void testSizeConstructor_largeSize() { - if(sizeConstructor == null) return; - Assert.assertTrue(sizeConstructor.apply(25212) != null); - } - - @Test - public void testRehash() { - if(sizeConstructor == null) return; - try - { - COLLECTION KEY_GENERIC_TYPE set = sizeConstructor.apply(0); - if(set instanceof ITrimmable) { - ITrimmable trim = (ITrimmable)set; - set.addAll(keys); - set.clear(); - Assert.assertTrue(trim.trim()); - Assert.assertFalse(trim.trim()); - set.addAll(keys); - trim.clearAndTrim(); - set.addAll(keys); - trim.clearAndTrim(Short.MAX_VALUE); - } - } - catch(UnsupportedOperationException e) { - //Ignore thats fine - } - } - - @Test - public void testSizeConstructor_InvalidSize() { - if(sizeConstructor == null) return; - try { - sizeConstructor.apply(-1); - Assert.fail("When Inputted Size is negative this should crash"); - } - catch(IllegalStateException e) { - } - } - -#if TYPE_OBJECT - protected abstract KEY_TYPE[] createKeyElements(); - -#else - protected KEY_TYPE[] createKeyElements() { - KEY_TYPE[] keys = NEW_KEY_ARRAY(100); - for(int i = 0;i<100;i++) { -#if TYPE_BOOLEAN - keys[i] = i % 2 != 0; -#else - keys[i] = (KEY_TYPE)i; -#endif - } - return keys; - } -#endif +package speiger.src.testers.PACKAGE.tests.collection; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.function.Function; +import java.util.function.IntFunction; +import java.util.function.Supplier; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.Ignore; +import junit.framework.TestCase; + +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.collections.COLLECTION; +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.utils.ARRAYS; +#endif +import speiger.src.collections.utils.ITrimmable; + +@Ignore +@SuppressWarnings("javadoc") +public abstract class FILE_KEY_TYPECollectionConstructorTester KEY_GENERIC_TYPE extends TestCase +{ + protected Supplier simpleConstructor; + protected IntFunction sizeConstructor; + protected Function pArrayConstructor; +#if !TYPE_OBJECT + protected Function arrayConstructor; +#endif + protected Function, COLLECTION KEY_GENERIC_TYPE> collectionConstructor; + protected Function pCollectionConstructor; + protected KEY_TYPE[] keys = createKeyElements(); + + protected void setSimpleConstructor(Supplier simpleConstructor) { + this.simpleConstructor = simpleConstructor; + } + + protected void setSizeConstructor(IntFunction sizeConstructor) { + this.sizeConstructor = sizeConstructor; + } + + protected void setPArrayConstructor(Function pArrayConstructor) { + this.pArrayConstructor = pArrayConstructor; + } + +#if !TYPE_OBJECT + protected void setArrayConstructor(Function arrayConstructor) { + this.arrayConstructor = arrayConstructor; + } + +#endif + protected void setCollectionConstructor(Function, COLLECTION KEY_GENERIC_TYPE> collectionConstructor) { + this.collectionConstructor = collectionConstructor; + } + + protected void setPCollectionConstructor(Function pCollectionConstructor) { + this.pCollectionConstructor = pCollectionConstructor; + } + + @Test + public void testPrimitiveArrayConstructor() { + if(pArrayConstructor == null) return; + Assert.assertTrue(pArrayConstructor.apply(keys) != null); + } + +#if !TYPE_OBJECT + @Test + public void testArrayConstructor() { + if(arrayConstructor == null) return; +#if TYPE_OBJECT + Assert.assertTrue(arrayConstructor.apply(keys) != null); +#else + Assert.assertTrue(arrayConstructor.apply(ARRAYS.wrap(keys)) != null); +#endif + } + +#endif + @Test + public void testPrimitiveMapsConstructor() { + if(pCollectionConstructor == null) return; + Assert.assertTrue(pCollectionConstructor.apply(new ARRAY_LISTBRACES(keys)) != null); + } + + @Test + public void testMapsConstructor() { + if(collectionConstructor == null) return; + Assert.assertTrue(collectionConstructor.apply(new ArrayList<>(new ARRAY_LISTBRACES(keys))) != null); + } + + @Test + public void testSimpleConstructor() { + if(simpleConstructor == null) return; + Assert.assertTrue(simpleConstructor.get() != null); + } + + @Test + public void testSizeConstructor_empty() { + if(sizeConstructor == null) return; + Assert.assertTrue(sizeConstructor.apply(0) != null); + } + + @Test + public void testSizeConstructor_smallSize() { + if(sizeConstructor == null) return; + Assert.assertTrue(sizeConstructor.apply(32) != null); + } + + @Test + public void testSizeConstructor_largeSize() { + if(sizeConstructor == null) return; + Assert.assertTrue(sizeConstructor.apply(25212) != null); + } + + @Test + public void testRehash() { + if(sizeConstructor == null) return; + try + { + COLLECTION KEY_GENERIC_TYPE set = sizeConstructor.apply(0); + if(set instanceof ITrimmable) { + ITrimmable trim = (ITrimmable)set; + set.addAll(keys); + set.clear(); + Assert.assertTrue(trim.trim()); + Assert.assertFalse(trim.trim()); + set.addAll(keys); + trim.clearAndTrim(); + set.addAll(keys); + trim.clearAndTrim(Short.MAX_VALUE); + } + } + catch(UnsupportedOperationException e) { + //Ignore thats fine + } + } + + @Test + public void testSizeConstructor_InvalidSize() { + if(sizeConstructor == null) return; + try { + sizeConstructor.apply(-1); + Assert.fail("When Inputted Size is negative this should crash"); + } + catch(IllegalStateException e) { + } + } + +#if TYPE_OBJECT + protected abstract KEY_TYPE[] createKeyElements(); + +#else + protected KEY_TYPE[] createKeyElements() { + KEY_TYPE[] keys = NEW_KEY_ARRAY(100); + for(int i = 0;i<100;i++) { +#if TYPE_BOOLEAN + keys[i] = i % 2 != 0; +#else + keys[i] = (KEY_TYPE)i; +#endif + } + return keys; + } +#endif } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionContainsAllTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionContainsAllTester.template index 045dd62..f31017a 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionContainsAllTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionContainsAllTester.template @@ -1,45 +1,45 @@ -package speiger.src.testers.PACKAGE.tests.collection; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; -import speiger.src.testers.PACKAGE.utils.MINIMAL_COLLECTION; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPECollectionContainsAllTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE -{ - public void testContainsAll_empty() { - assertTrue("containsAll(empty) should return true", collection.containsAll(MINIMAL_COLLECTION.of())); - } - -#ignore - @CollectionSize.Require(absent = ZERO) - public void testContainsAll_subset() { -#endignore - assertTrue("containsAll(subset) should return true", collection.containsAll(MINIMAL_COLLECTION.of(e0()))); - } - - public void testContainsAll_sameElements() { - assertTrue("containsAll(sameElements) should return true", collection.containsAll(MINIMAL_COLLECTION.of(createSamplesArray()))); - } - - public void testContainsAll_self() { - assertTrue("containsAll(this) should return true", collection.containsAll(collection)); - } - - public void testContainsAll_partialOverlap() { - assertFalse("containsAll(partialOverlap) should return false", collection.containsAll(MINIMAL_COLLECTION.of(e0(), e3()))); - } - - public void testContainsAll_disjoint() { - assertFalse("containsAll(disjoint) should return false", collection.containsAll(MINIMAL_COLLECTION.of(e3()))); - } - -} +package speiger.src.testers.PACKAGE.tests.collection; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; +import speiger.src.testers.PACKAGE.utils.MINIMAL_COLLECTION; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPECollectionContainsAllTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE +{ + public void testContainsAll_empty() { + assertTrue("containsAll(empty) should return true", collection.containsAll(MINIMAL_COLLECTION.of())); + } + +#ignore + @CollectionSize.Require(absent = ZERO) + public void testContainsAll_subset() { +#endignore + assertTrue("containsAll(subset) should return true", collection.containsAll(MINIMAL_COLLECTION.of(e0()))); + } + + public void testContainsAll_sameElements() { + assertTrue("containsAll(sameElements) should return true", collection.containsAll(MINIMAL_COLLECTION.of(createSamplesArray()))); + } + + public void testContainsAll_self() { + assertTrue("containsAll(this) should return true", collection.containsAll(collection)); + } + + public void testContainsAll_partialOverlap() { + assertFalse("containsAll(partialOverlap) should return false", collection.containsAll(MINIMAL_COLLECTION.of(e0(), e3()))); + } + + public void testContainsAll_disjoint() { + assertFalse("containsAll(disjoint) should return false", collection.containsAll(MINIMAL_COLLECTION.of(e3()))); + } + +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionContainsAnyTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionContainsAnyTester.template index 22dc634..7e8be40 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionContainsAnyTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionContainsAnyTester.template @@ -1,42 +1,42 @@ -package speiger.src.testers.PACKAGE.tests.collection; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; -import speiger.src.testers.PACKAGE.utils.MINIMAL_COLLECTION; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPECollectionContainsAnyTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE -{ - public void testContainsAny_empty() { - assertFalse("containsAny(empty) should return false", collection.containsAny(MINIMAL_COLLECTION.of())); - } -#ignore - @CollectionSize.Require(absent = ZERO) - public void testContainsAny_subset() { -#endignore - assertTrue("containsAny(subset) should return true", collection.containsAny(MINIMAL_COLLECTION.of(e0()))); - } - -#ignore - @CollectionSize.Require(ONE) - public void testContainsAny_subSetElement() { -#endignore - assertFalse("containsAny(empty) should return false", collection.containsAny(MINIMAL_COLLECTION.of())); - } - -#ignore - @CollectionSize.Require(ONE) - public void testContainsAny_subSetElements() { -#endignore - assertTrue("containsAny(subset) should return true", collection.containsAny(getSampleElements(5))); - } -} +package speiger.src.testers.PACKAGE.tests.collection; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; +import speiger.src.testers.PACKAGE.utils.MINIMAL_COLLECTION; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPECollectionContainsAnyTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE +{ + public void testContainsAny_empty() { + assertFalse("containsAny(empty) should return false", collection.containsAny(MINIMAL_COLLECTION.of())); + } +#ignore + @CollectionSize.Require(absent = ZERO) + public void testContainsAny_subset() { +#endignore + assertTrue("containsAny(subset) should return true", collection.containsAny(MINIMAL_COLLECTION.of(e0()))); + } + +#ignore + @CollectionSize.Require(ONE) + public void testContainsAny_subSetElement() { +#endignore + assertFalse("containsAny(empty) should return false", collection.containsAny(MINIMAL_COLLECTION.of())); + } + +#ignore + @CollectionSize.Require(ONE) + public void testContainsAny_subSetElements() { +#endignore + assertTrue("containsAny(subset) should return true", collection.containsAny(getSampleElements(5))); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionContainsTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionContainsTester.template index c1e7205..d8a0423 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionContainsTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionContainsTester.template @@ -1,27 +1,27 @@ -package speiger.src.testers.PACKAGE.tests.collection; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPECollectionContainsTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionSize.Require(absent = ZERO) - public void testContains_yes() { - assertTrue("contains(present) should return true", collection.contains(e0())); - } - - public void testContains_no() { - assertFalse("contains(notPresent) should return false", collection.contains(e3())); - } -#endignore -} +package speiger.src.testers.PACKAGE.tests.collection; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPECollectionContainsTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionSize.Require(absent = ZERO) + public void testContains_yes() { + assertTrue("contains(present) should return true", collection.contains(e0())); + } + + public void testContains_no() { + assertFalse("contains(notPresent) should return false", collection.contains(e3())); + } +#endignore +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionCopyTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionCopyTester.template index b96746c..d1ccf0a 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionCopyTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionCopyTester.template @@ -1,38 +1,38 @@ -package speiger.src.testers.PACKAGE.tests.collection; - -import org.junit.Assert; -import org.junit.Ignore; - -import speiger.src.testers.utils.SpecialFeature; -import speiger.src.collections.PACKAGE.collections.COLLECTION; -import speiger.src.collections.PACKAGE.utils.COLLECTIONS; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPECollectionCopyTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE -{ -#ignore - @SpecialFeature.Require(SpecialFeature.COPYING) -#endignore - public void testEquals() { - COLLECTION KEY_GENERIC_TYPE copy = collection.copy(); - if(!(collection instanceof COLLECTIONS.EmptyCollection)) { - Assert.assertFalse("Copied Collection shouldn't match", copy == collection); - } - Assert.assertTrue("Copied Collection contents should match", copy.equals(collection)); - } - -#ignore - @SpecialFeature.Require(absent = SpecialFeature.COPYING) -#endignore - public void testEqualsFail() { - try { - assertNull(collection.copy()); - fail("If Copying isn't supported it should throw a UnsupportedOperationException"); - } - catch(UnsupportedOperationException e) { - //Success - } - } -} +package speiger.src.testers.PACKAGE.tests.collection; + +import org.junit.Assert; +import org.junit.Ignore; + +import speiger.src.testers.utils.SpecialFeature; +import speiger.src.collections.PACKAGE.collections.COLLECTION; +import speiger.src.collections.PACKAGE.utils.COLLECTIONS; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPECollectionCopyTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE +{ +#ignore + @SpecialFeature.Require(SpecialFeature.COPYING) +#endignore + public void testEquals() { + COLLECTION KEY_GENERIC_TYPE copy = collection.copy(); + if(!(collection instanceof COLLECTIONS.EmptyCollection)) { + Assert.assertFalse("Copied Collection shouldn't match", copy == collection); + } + Assert.assertTrue("Copied Collection contents should match", copy.equals(collection)); + } + +#ignore + @SpecialFeature.Require(absent = SpecialFeature.COPYING) +#endignore + public void testEqualsFail() { + try { + assertNull(collection.copy()); + fail("If Copying isn't supported it should throw a UnsupportedOperationException"); + } + catch(UnsupportedOperationException e) { + //Success + } + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionEqualsTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionEqualsTester.template index b516615..cda4a6c 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionEqualsTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionEqualsTester.template @@ -1,24 +1,24 @@ -package speiger.src.testers.PACKAGE.tests.collection; - -import org.junit.Ignore; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPECollectionEqualsTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE -{ - public void testEquals_self() { - assertTrue("An Object should be equal to itself.", collection.equals(collection)); - } - - public void testEquals_null() { - // noinspection ObjectEqualsNull - assertFalse("An object should not be equal to null.", collection.equals(null)); - } - - public void testEquals_notACollection() { - // noinspection EqualsBetweenInconvertibleTypes - assertFalse("A Collection should never equal an object that is not a Collection.", collection.equals("huh?")); - } -} +package speiger.src.testers.PACKAGE.tests.collection; + +import org.junit.Ignore; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPECollectionEqualsTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE +{ + public void testEquals_self() { + assertTrue("An Object should be equal to itself.", collection.equals(collection)); + } + + public void testEquals_null() { + // noinspection ObjectEqualsNull + assertFalse("An object should not be equal to null.", collection.equals(null)); + } + + public void testEquals_notACollection() { + // noinspection EqualsBetweenInconvertibleTypes + assertFalse("A Collection should never equal an object that is not a Collection.", collection.equals("huh?")); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionForEachTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionForEachTester.template index 8a86432..3bfcf89 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionForEachTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionForEachTester.template @@ -1,55 +1,55 @@ -package speiger.src.testers.PACKAGE.tests.collection; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; -#endignore - -import com.google.common.collect.testing.features.CollectionFeature; - -import org.junit.Ignore; - -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; -import speiger.src.testers.PACKAGE.utils.HELPERS; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPECollectionForEachTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(absent = KNOWN_ORDER) - public void testForEachUnknownOrder() { -#endignore - LIST KEY_GENERIC_TYPE elements = new ARRAY_LISTBRACES(); - collection.forEach(elements::add); - HELPERS.assertContentsAnyOrder(elements, createSamplesArray()); - } - -#ignore -@CollectionFeature.Require(absent = KNOWN_ORDER) - public void testForEachExtraUnknownOrder() { -#endignore - LIST KEY_GENERIC_TYPE elements = new ARRAY_LISTBRACES(); - collection.forEach(elements, LIST::add); - HELPERS.assertContentsAnyOrder(elements, createSamplesArray()); - } - -#ignore - @CollectionFeature.Require(KNOWN_ORDER) - public void testForEachKnownOrder() { -#endignore - LIST KEY_GENERIC_TYPE elements = new ARRAY_LISTBRACES(); - collection.forEach(elements::add); - assertEquals("Different ordered iteration", HELPERS.copyToList(getOrderedElements()), elements); - } - -#ignore - @CollectionFeature.Require(KNOWN_ORDER) - public void testForEachExtraKnownOrder() { -#endignore - LIST KEY_GENERIC_TYPE elements = new ARRAY_LISTBRACES(); - collection.forEach(elements, LIST::add); - assertEquals("Different ordered iteration", HELPERS.copyToList(getOrderedElements()), elements); - } -} +package speiger.src.testers.PACKAGE.tests.collection; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; +#endignore + +import com.google.common.collect.testing.features.CollectionFeature; + +import org.junit.Ignore; + +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; +import speiger.src.testers.PACKAGE.utils.HELPERS; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPECollectionForEachTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(absent = KNOWN_ORDER) + public void testForEachUnknownOrder() { +#endignore + LIST KEY_GENERIC_TYPE elements = new ARRAY_LISTBRACES(); + collection.forEach(elements::add); + HELPERS.assertContentsAnyOrder(elements, createSamplesArray()); + } + +#ignore +@CollectionFeature.Require(absent = KNOWN_ORDER) + public void testForEachExtraUnknownOrder() { +#endignore + LIST KEY_GENERIC_TYPE elements = new ARRAY_LISTBRACES(); + collection.forEach(elements, LIST::add); + HELPERS.assertContentsAnyOrder(elements, createSamplesArray()); + } + +#ignore + @CollectionFeature.Require(KNOWN_ORDER) + public void testForEachKnownOrder() { +#endignore + LIST KEY_GENERIC_TYPE elements = new ARRAY_LISTBRACES(); + collection.forEach(elements::add); + assertEquals("Different ordered iteration", HELPERS.copyToList(getOrderedElements()), elements); + } + +#ignore + @CollectionFeature.Require(KNOWN_ORDER) + public void testForEachExtraKnownOrder() { +#endignore + LIST KEY_GENERIC_TYPE elements = new ARRAY_LISTBRACES(); + collection.forEach(elements, LIST::add); + assertEquals("Different ordered iteration", HELPERS.copyToList(getOrderedElements()), elements); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionIteratorTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionIteratorTester.template index 3a64376..2fb0df9 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionIteratorTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionIteratorTester.template @@ -1,161 +1,161 @@ -package speiger.src.testers.PACKAGE.tests.collection; - -#ignore -import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; -import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; -import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ITERATOR_REMOVE; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import java.util.NoSuchElementException; -import java.util.Set; -import java.util.EnumSet; -import java.util.Collections; - -import com.google.common.collect.testing.IteratorFeature; -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import org.junit.Ignore; - -import speiger.src.collections.PACKAGE.collections.ITERABLE; -import speiger.src.collections.PACKAGE.collections.ITERATOR; -import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; -import speiger.src.collections.PACKAGE.utils.LISTS; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; -import speiger.src.testers.PACKAGE.utils.HELPERS; -import speiger.src.testers.PACKAGE.utils.ITERATOR_TESTER; -import speiger.src.testers.PACKAGE.utils.LIST_ITERATOR_TESTER; -import speiger.src.testers.PACKAGE.utils.BIDIRECTIONAL_ITERATOR_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPECollectionIteratorTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE -{ - public void testIterator() { - LIST KEY_GENERIC_TYPE elements = new ARRAY_LISTBRACES(); - for (ITERATOR KEY_GENERIC_TYPE iter = collection.iterator();iter.hasNext();) { // uses iterator() - elements.add(iter.NEXT()); - } - HELPERS.assertContentsAnyOrder(elements, createSamplesArray()); - } - -#ignore - @CollectionFeature.Require(KNOWN_ORDER) - public void testIterationOrdering() { -#endignore - LIST KEY_GENERIC_TYPE elements = new ARRAY_LISTBRACES(); - for (ITERATOR KEY_GENERIC_TYPE iter = collection.iterator();iter.hasNext();) { // uses iterator() - elements.add(iter.NEXT()); - } - LIST KEY_GENERIC_TYPE expected = HELPERS.copyToList(getOrderedElements()); - assertEquals("Different ordered iteration", expected, elements); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_ITERATOR_REMOVE) - @CollectionSize.Require(absent = ZERO) - public void testIterator_removeAffectsBackingCollection() { -#endignore - int originalSize = collection.size(); - ITERATOR KEY_GENERIC_TYPE iterator = collection.iterator(); - KEY_TYPE element = iterator.NEXT(); - assertTrue(collection.contains(element)); // sanity check - iterator.remove(); - assertFalse(collection.contains(element)); - assertEquals(originalSize - 1, collection.size()); - } - -#ignore - @CollectionFeature.Require({ KNOWN_ORDER, SUPPORTS_ITERATOR_REMOVE }) - public void testIterator_knownOrderRemoveSupported() { -#endignore - runIteratorTest(MODIFIABLE, ITERATOR_TESTER.KnownOrder.KNOWN_ORDER, getOrderedElements()); - } - -#ignore - @CollectionFeature.Require(value = KNOWN_ORDER, absent = SUPPORTS_ITERATOR_REMOVE) - public void testIterator_knownOrderRemoveUnsupported() { -#endignore - runIteratorTest(UNMODIFIABLE, ITERATOR_TESTER.KnownOrder.KNOWN_ORDER, getOrderedElements()); - } - -#ignore - @CollectionFeature.Require(absent = KNOWN_ORDER, value = SUPPORTS_ITERATOR_REMOVE) - public void testIterator_unknownOrderRemoveSupported() { -#endignore - runIteratorTest(MODIFIABLE, ITERATOR_TESTER.KnownOrder.UNKNOWN_ORDER, getSampleElements()); - } - -#ignore - @CollectionFeature.Require(absent = { KNOWN_ORDER, SUPPORTS_ITERATOR_REMOVE }) - public void testIterator_unknownOrderRemoveUnsupported() { -#endignore - runIteratorTest(UNMODIFIABLE, ITERATOR_TESTER.KnownOrder.UNKNOWN_ORDER, getSampleElements()); - } - - private void runIteratorTest(Set features, ITERATOR_TESTER.KnownOrder knownOrder, ITERABLE KEY_GENERIC_TYPE elements) { - if(knownOrder == ITERATOR_TESTER.KnownOrder.KNOWN_ORDER && !(collection instanceof LIST) && collection.iterator() instanceof LIST_ITERATOR) { - Set listFeature = features.isEmpty() ? features : EnumSet.copyOf(features); -#ignore - listFeature.retainAll(EnumSet.of(IteratorFeature.SUPPORTS_REMOVE)); -#endignore - new LIST_ITERATOR_TESTER KEY_GENERIC_TYPE(2, LISTS.singleton(INVALID_VALUE), Collections.unmodifiableSet(listFeature), elements, 0) { - @Override - protected LIST_ITERATOR KEY_GENERIC_TYPE newTargetIterator() { - resetCollection(); - return (LIST_ITERATOR KEY_GENERIC_TYPE)collection.iterator(); - } - - @Override - protected void verify(LIST KEY_GENERIC_TYPE elements) { - expectContents(elements); - } - }.test(); - } - if(collection.iterator() instanceof BI_ITERATOR) { - new BIDIRECTIONAL_ITERATOR_TESTER KEY_GENERIC_TYPE(4, features, elements, knownOrder) { - @Override - protected BI_ITERATOR KEY_GENERIC_TYPE newTargetIterator() { - resetCollection(); - return (BI_ITERATOR KEY_GENERIC_TYPE)collection.iterator(); - } - - @Override - protected void verify(LIST KEY_GENERIC_TYPE elements) { - expectContents(elements); - } - }.test(); - return; - } - new ITERATOR_TESTER KEY_GENERIC_TYPE(5, features, elements, knownOrder) { - @Override - protected ITERATOR KEY_GENERIC_TYPE newTargetIterator() { - resetCollection(); - return collection.iterator(); - } - - @Override - protected void verify(LIST KEY_GENERIC_TYPE elements) { - expectContents(elements); - } - }.test(); - } - - public void testIteratorNoSuchElementException() { - ITERATOR KEY_GENERIC_TYPE iterator = collection.iterator(); - while (iterator.hasNext()) { - iterator.NEXT(); - } - - try { - iterator.NEXT(); - fail("iterator.next() should throw NoSuchElementException"); - } catch (NoSuchElementException expected) { - } - } -} +package speiger.src.testers.PACKAGE.tests.collection; + +#ignore +import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; +import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; +import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ITERATOR_REMOVE; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import java.util.NoSuchElementException; +import java.util.Set; +import java.util.EnumSet; +import java.util.Collections; + +import com.google.common.collect.testing.IteratorFeature; +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import org.junit.Ignore; + +import speiger.src.collections.PACKAGE.collections.ITERABLE; +import speiger.src.collections.PACKAGE.collections.ITERATOR; +import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; +import speiger.src.collections.PACKAGE.utils.LISTS; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; +import speiger.src.testers.PACKAGE.utils.HELPERS; +import speiger.src.testers.PACKAGE.utils.ITERATOR_TESTER; +import speiger.src.testers.PACKAGE.utils.LIST_ITERATOR_TESTER; +import speiger.src.testers.PACKAGE.utils.BIDIRECTIONAL_ITERATOR_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPECollectionIteratorTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE +{ + public void testIterator() { + LIST KEY_GENERIC_TYPE elements = new ARRAY_LISTBRACES(); + for (ITERATOR KEY_GENERIC_TYPE iter = collection.iterator();iter.hasNext();) { // uses iterator() + elements.add(iter.NEXT()); + } + HELPERS.assertContentsAnyOrder(elements, createSamplesArray()); + } + +#ignore + @CollectionFeature.Require(KNOWN_ORDER) + public void testIterationOrdering() { +#endignore + LIST KEY_GENERIC_TYPE elements = new ARRAY_LISTBRACES(); + for (ITERATOR KEY_GENERIC_TYPE iter = collection.iterator();iter.hasNext();) { // uses iterator() + elements.add(iter.NEXT()); + } + LIST KEY_GENERIC_TYPE expected = HELPERS.copyToList(getOrderedElements()); + assertEquals("Different ordered iteration", expected, elements); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_ITERATOR_REMOVE) + @CollectionSize.Require(absent = ZERO) + public void testIterator_removeAffectsBackingCollection() { +#endignore + int originalSize = collection.size(); + ITERATOR KEY_GENERIC_TYPE iterator = collection.iterator(); + KEY_TYPE element = iterator.NEXT(); + assertTrue(collection.contains(element)); // sanity check + iterator.remove(); + assertFalse(collection.contains(element)); + assertEquals(originalSize - 1, collection.size()); + } + +#ignore + @CollectionFeature.Require({ KNOWN_ORDER, SUPPORTS_ITERATOR_REMOVE }) + public void testIterator_knownOrderRemoveSupported() { +#endignore + runIteratorTest(MODIFIABLE, ITERATOR_TESTER.KnownOrder.KNOWN_ORDER, getOrderedElements()); + } + +#ignore + @CollectionFeature.Require(value = KNOWN_ORDER, absent = SUPPORTS_ITERATOR_REMOVE) + public void testIterator_knownOrderRemoveUnsupported() { +#endignore + runIteratorTest(UNMODIFIABLE, ITERATOR_TESTER.KnownOrder.KNOWN_ORDER, getOrderedElements()); + } + +#ignore + @CollectionFeature.Require(absent = KNOWN_ORDER, value = SUPPORTS_ITERATOR_REMOVE) + public void testIterator_unknownOrderRemoveSupported() { +#endignore + runIteratorTest(MODIFIABLE, ITERATOR_TESTER.KnownOrder.UNKNOWN_ORDER, getSampleElements()); + } + +#ignore + @CollectionFeature.Require(absent = { KNOWN_ORDER, SUPPORTS_ITERATOR_REMOVE }) + public void testIterator_unknownOrderRemoveUnsupported() { +#endignore + runIteratorTest(UNMODIFIABLE, ITERATOR_TESTER.KnownOrder.UNKNOWN_ORDER, getSampleElements()); + } + + private void runIteratorTest(Set features, ITERATOR_TESTER.KnownOrder knownOrder, ITERABLE KEY_GENERIC_TYPE elements) { + if(knownOrder == ITERATOR_TESTER.KnownOrder.KNOWN_ORDER && !(collection instanceof LIST) && collection.iterator() instanceof LIST_ITERATOR) { + Set listFeature = features.isEmpty() ? features : EnumSet.copyOf(features); +#ignore + listFeature.retainAll(EnumSet.of(IteratorFeature.SUPPORTS_REMOVE)); +#endignore + new LIST_ITERATOR_TESTER KEY_GENERIC_TYPE(2, LISTS.singleton(INVALID_VALUE), Collections.unmodifiableSet(listFeature), elements, 0) { + @Override + protected LIST_ITERATOR KEY_GENERIC_TYPE newTargetIterator() { + resetCollection(); + return (LIST_ITERATOR KEY_GENERIC_TYPE)collection.iterator(); + } + + @Override + protected void verify(LIST KEY_GENERIC_TYPE elements) { + expectContents(elements); + } + }.test(); + } + if(collection.iterator() instanceof BI_ITERATOR) { + new BIDIRECTIONAL_ITERATOR_TESTER KEY_GENERIC_TYPE(4, features, elements, knownOrder) { + @Override + protected BI_ITERATOR KEY_GENERIC_TYPE newTargetIterator() { + resetCollection(); + return (BI_ITERATOR KEY_GENERIC_TYPE)collection.iterator(); + } + + @Override + protected void verify(LIST KEY_GENERIC_TYPE elements) { + expectContents(elements); + } + }.test(); + return; + } + new ITERATOR_TESTER KEY_GENERIC_TYPE(5, features, elements, knownOrder) { + @Override + protected ITERATOR KEY_GENERIC_TYPE newTargetIterator() { + resetCollection(); + return collection.iterator(); + } + + @Override + protected void verify(LIST KEY_GENERIC_TYPE elements) { + expectContents(elements); + } + }.test(); + } + + public void testIteratorNoSuchElementException() { + ITERATOR KEY_GENERIC_TYPE iterator = collection.iterator(); + while (iterator.hasNext()) { + iterator.NEXT(); + } + + try { + iterator.NEXT(); + fail("iterator.next() should throw NoSuchElementException"); + } catch (NoSuchElementException expected) { + } + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionRemoveAllTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionRemoveAllTester.template index 7ead211..f384a75 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionRemoveAllTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionRemoveAllTester.template @@ -1,153 +1,153 @@ -package speiger.src.testers.PACKAGE.tests.collection; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; -import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import java.util.ConcurrentModificationException; - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import org.junit.Ignore; - -import speiger.src.collections.PACKAGE.collections.ITERATOR; -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; -import speiger.src.testers.PACKAGE.utils.HELPERS; -import speiger.src.testers.PACKAGE.utils.MINIMAL_COLLECTION; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPECollectionRemoveAllTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) -#endignore - public void testRemoveAll_emptyCollection() { - assertFalse("removeAll(emptyCollection) should return false", collection.removeAll(MINIMAL_COLLECTION.of())); - expectUnchanged(); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) -#endignore - public void testRemoveAll_nonePresent() { - assertFalse("removeAll(disjointCollection) should return false", collection.removeAll(MINIMAL_COLLECTION.of(e3()))); - expectUnchanged(); - } - - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) -#endignore - public void testRemoveAll_nonePresentFetchRemoved() { - LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); - assertFalse("removeAll(disjointCollection) should return false", collection.removeAll(MINIMAL_COLLECTION.of(e3()), list::add)); - expectUnchanged(); - assertTrue(list.isEmpty()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) -#endignore - public void testRemoveAll_emptyCollectionFetching() { - LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); - assertFalse("removeAll(emptyCollection) should return false", collection.removeAll(MINIMAL_COLLECTION.of(), list::add)); - expectUnchanged(); - assertTrue(list.isEmpty()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRemoveAll_allPresent() { - assertTrue("removeAll(intersectingCollection) should return true", collection.removeAll(MINIMAL_COLLECTION.of(e0()))); - expectMissing(e0()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRemoveAll_somePresent() { - assertTrue("removeAll(intersectingCollection) should return true", collection.removeAll(MINIMAL_COLLECTION.of(e0(), e3()))); - expectMissing(e0()); - } - -#ignore - @CollectionFeature.Require({ SUPPORTS_REMOVE, FAILS_FAST_ON_CONCURRENT_MODIFICATION }) - @CollectionSize.Require(SEVERAL) -#endignore - public void testRemoveAllSomePresentConcurrentWithIteration() { - try { - ITERATOR KEY_GENERIC_TYPE iterator = collection.iterator(); - assertTrue(collection.removeAll(MINIMAL_COLLECTION.of(e0(), e3()))); - iterator.NEXT(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRemoveAll_somePresentLargeCollectionToRemove() { - assertTrue("removeAll(largeIntersectingCollection) should return true", collection.removeAll(MINIMAL_COLLECTION.of(e0(), e0(), e0(), e3(), e3(), e3()))); - expectMissing(e0()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRemoveAll_someFetchRemovedElements() { - LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); - assertTrue("removeAll(largeIntersectingCollection, RemovedElements) should return true", collection.removeAll(MINIMAL_COLLECTION.of(e0(), e0(), e0(), e3(), e3(), e3()), list::add)); - expectMissing(e0()); - HELPERS.assertContentsAnyOrder(list, e0()); - } - -#ignore - @CollectionFeature.Require(absent = SUPPORTS_REMOVE) -#endignore - public void testRemoveAll_unsupportedEmptyCollection() { - try { - assertFalse("removeAll(emptyCollection) should return false or throw UnsupportedOperationException", collection.removeAll(MINIMAL_COLLECTION.of())); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } - -#ignore - @CollectionFeature.Require(absent = SUPPORTS_REMOVE) -#endignore - public void testRemoveAll_unsupportedNonePresent() { - try { - assertFalse("removeAll(disjointCollection) should return false or throw UnsupportedOperationException", collection.removeAll(MINIMAL_COLLECTION.of(e3()))); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } - -#ignore - @CollectionFeature.Require(absent = SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRemoveAll_unsupportedPresent() { - try { - collection.removeAll(MINIMAL_COLLECTION.of(e0())); - fail("removeAll(intersectingCollection) should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - assertTrue(collection.contains(e0())); - } -} +package speiger.src.testers.PACKAGE.tests.collection; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; +import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import java.util.ConcurrentModificationException; + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import org.junit.Ignore; + +import speiger.src.collections.PACKAGE.collections.ITERATOR; +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; +import speiger.src.testers.PACKAGE.utils.HELPERS; +import speiger.src.testers.PACKAGE.utils.MINIMAL_COLLECTION; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPECollectionRemoveAllTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) +#endignore + public void testRemoveAll_emptyCollection() { + assertFalse("removeAll(emptyCollection) should return false", collection.removeAll(MINIMAL_COLLECTION.of())); + expectUnchanged(); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) +#endignore + public void testRemoveAll_nonePresent() { + assertFalse("removeAll(disjointCollection) should return false", collection.removeAll(MINIMAL_COLLECTION.of(e3()))); + expectUnchanged(); + } + + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) +#endignore + public void testRemoveAll_nonePresentFetchRemoved() { + LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); + assertFalse("removeAll(disjointCollection) should return false", collection.removeAll(MINIMAL_COLLECTION.of(e3()), list::add)); + expectUnchanged(); + assertTrue(list.isEmpty()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) +#endignore + public void testRemoveAll_emptyCollectionFetching() { + LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); + assertFalse("removeAll(emptyCollection) should return false", collection.removeAll(MINIMAL_COLLECTION.of(), list::add)); + expectUnchanged(); + assertTrue(list.isEmpty()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRemoveAll_allPresent() { + assertTrue("removeAll(intersectingCollection) should return true", collection.removeAll(MINIMAL_COLLECTION.of(e0()))); + expectMissing(e0()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRemoveAll_somePresent() { + assertTrue("removeAll(intersectingCollection) should return true", collection.removeAll(MINIMAL_COLLECTION.of(e0(), e3()))); + expectMissing(e0()); + } + +#ignore + @CollectionFeature.Require({ SUPPORTS_REMOVE, FAILS_FAST_ON_CONCURRENT_MODIFICATION }) + @CollectionSize.Require(SEVERAL) +#endignore + public void testRemoveAllSomePresentConcurrentWithIteration() { + try { + ITERATOR KEY_GENERIC_TYPE iterator = collection.iterator(); + assertTrue(collection.removeAll(MINIMAL_COLLECTION.of(e0(), e3()))); + iterator.NEXT(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRemoveAll_somePresentLargeCollectionToRemove() { + assertTrue("removeAll(largeIntersectingCollection) should return true", collection.removeAll(MINIMAL_COLLECTION.of(e0(), e0(), e0(), e3(), e3(), e3()))); + expectMissing(e0()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRemoveAll_someFetchRemovedElements() { + LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); + assertTrue("removeAll(largeIntersectingCollection, RemovedElements) should return true", collection.removeAll(MINIMAL_COLLECTION.of(e0(), e0(), e0(), e3(), e3(), e3()), list::add)); + expectMissing(e0()); + HELPERS.assertContentsAnyOrder(list, e0()); + } + +#ignore + @CollectionFeature.Require(absent = SUPPORTS_REMOVE) +#endignore + public void testRemoveAll_unsupportedEmptyCollection() { + try { + assertFalse("removeAll(emptyCollection) should return false or throw UnsupportedOperationException", collection.removeAll(MINIMAL_COLLECTION.of())); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } + +#ignore + @CollectionFeature.Require(absent = SUPPORTS_REMOVE) +#endignore + public void testRemoveAll_unsupportedNonePresent() { + try { + assertFalse("removeAll(disjointCollection) should return false or throw UnsupportedOperationException", collection.removeAll(MINIMAL_COLLECTION.of(e3()))); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } + +#ignore + @CollectionFeature.Require(absent = SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRemoveAll_unsupportedPresent() { + try { + collection.removeAll(MINIMAL_COLLECTION.of(e0())); + fail("removeAll(intersectingCollection) should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + assertTrue(collection.contains(e0())); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionRemoveIfTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionRemoveIfTester.template index a801e60..53e2ded 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionRemoveIfTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionRemoveIfTester.template @@ -1,119 +1,119 @@ -package speiger.src.testers.PACKAGE.tests.collection; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; -import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import java.util.ConcurrentModificationException; -#if TYPE_OBJECT -import java.util.Objects; -#endif - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import org.junit.Ignore; - -import speiger.src.collections.PACKAGE.collections.ITERATOR; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPECollectionRemoveIfTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) -#endignore - public void testRemoveIf_alwaysFalse() { -#if TYPE_OBJECT - assertFalse("remoIf(x -> false) should return false", collection.removeIf(x -> false)); -#else - assertFalse("remoIf(x -> false) should return false", collection.remIf(x -> false)); -#endif - expectUnchanged(); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRemoveIf_sometimesTrue() { - assertTrue("remIf(isEqual(present)) should return true", -#if TYPE_OBJECT - collection.removeIf(T -> Objects.equals(T, e0()))); -#else - collection.remIf(T -> T == e0())); -#endif - expectMissing(samples.e0()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRemoveIf_allPresent() { -#if TYPE_OBJECT - assertTrue("remIf(x -> true) should return true", collection.removeIf(x -> true)); -#else - assertTrue("remIf(x -> true) should return true", collection.remIf(x -> true)); -#endif - expectContents(); - } - -#ignore - @CollectionFeature.Require({ SUPPORTS_REMOVE, FAILS_FAST_ON_CONCURRENT_MODIFICATION }) - @CollectionSize.Require(SEVERAL) -#endignore - public void testRemoveIfSomeMatchesConcurrentWithIteration() { - try { - ITERATOR KEY_GENERIC_TYPE iterator = collection.iterator(); -#if TYPE_OBJECT - assertTrue(collection.removeIf(T -> Objects.equals(T, e0()))); -#else - assertTrue(collection.remIf(T -> T == e0())); -#endif - iterator.NEXT(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#ignore - @CollectionFeature.Require(absent = SUPPORTS_REMOVE) - @CollectionSize.Require(ZERO) -#endignore - public void testRemoveIf_unsupportedEmptyCollection() { - try { - assertFalse("remIf(Predicate) should return false or throw UnsupportedOperationException", -#if TYPE_OBJECT - collection.removeIf(x -> {throw new AssertionError("predicate should never be called");})); -#else - collection.remIf(x -> {throw new AssertionError("predicate should never be called");})); -#endif - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } - -#ignore - @CollectionFeature.Require(absent = SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRemoveIf_alwaysTrueUnsupported() { - try { -#if TYPE_OBJECT - collection.removeIf(x -> true); -#else - collection.remIf(x -> true); - fail("remIf(x -> true) should throw " + "UnsupportedOperationException"); -#endif - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - assertTrue(collection.contains(samples.e0())); - } +package speiger.src.testers.PACKAGE.tests.collection; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; +import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import java.util.ConcurrentModificationException; +#if TYPE_OBJECT +import java.util.Objects; +#endif + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import org.junit.Ignore; + +import speiger.src.collections.PACKAGE.collections.ITERATOR; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPECollectionRemoveIfTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) +#endignore + public void testRemoveIf_alwaysFalse() { +#if TYPE_OBJECT + assertFalse("remoIf(x -> false) should return false", collection.removeIf(x -> false)); +#else + assertFalse("remoIf(x -> false) should return false", collection.remIf(x -> false)); +#endif + expectUnchanged(); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRemoveIf_sometimesTrue() { + assertTrue("remIf(isEqual(present)) should return true", +#if TYPE_OBJECT + collection.removeIf(T -> Objects.equals(T, e0()))); +#else + collection.remIf(T -> T == e0())); +#endif + expectMissing(samples.e0()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRemoveIf_allPresent() { +#if TYPE_OBJECT + assertTrue("remIf(x -> true) should return true", collection.removeIf(x -> true)); +#else + assertTrue("remIf(x -> true) should return true", collection.remIf(x -> true)); +#endif + expectContents(); + } + +#ignore + @CollectionFeature.Require({ SUPPORTS_REMOVE, FAILS_FAST_ON_CONCURRENT_MODIFICATION }) + @CollectionSize.Require(SEVERAL) +#endignore + public void testRemoveIfSomeMatchesConcurrentWithIteration() { + try { + ITERATOR KEY_GENERIC_TYPE iterator = collection.iterator(); +#if TYPE_OBJECT + assertTrue(collection.removeIf(T -> Objects.equals(T, e0()))); +#else + assertTrue(collection.remIf(T -> T == e0())); +#endif + iterator.NEXT(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#ignore + @CollectionFeature.Require(absent = SUPPORTS_REMOVE) + @CollectionSize.Require(ZERO) +#endignore + public void testRemoveIf_unsupportedEmptyCollection() { + try { + assertFalse("remIf(Predicate) should return false or throw UnsupportedOperationException", +#if TYPE_OBJECT + collection.removeIf(x -> {throw new AssertionError("predicate should never be called");})); +#else + collection.remIf(x -> {throw new AssertionError("predicate should never be called");})); +#endif + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } + +#ignore + @CollectionFeature.Require(absent = SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRemoveIf_alwaysTrueUnsupported() { + try { +#if TYPE_OBJECT + collection.removeIf(x -> true); +#else + collection.remIf(x -> true); + fail("remIf(x -> true) should throw " + "UnsupportedOperationException"); +#endif + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + assertTrue(collection.contains(samples.e0())); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionRetainAllTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionRetainAllTester.template index 184f8fd..3f7cbe7 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionRetainAllTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionRetainAllTester.template @@ -1,337 +1,337 @@ -package speiger.src.testers.PACKAGE.tests.collection; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import org.junit.Ignore; - -import speiger.src.collections.PACKAGE.collections.COLLECTION; -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; -import speiger.src.testers.PACKAGE.utils.HELPERS; -import speiger.src.testers.PACKAGE.utils.MINIMAL_COLLECTION; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPECollectionRetainAllTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE -{ - - private class Target { - private final COLLECTION KEY_GENERIC_TYPE toRetain; - private final COLLECTION KEY_GENERIC_TYPE inverse = ARRAY_LIST.wrap(createSamplesArray()); - private final String description; - - private Target(COLLECTION KEY_GENERIC_TYPE toRetain, String description) { - this.toRetain = toRetain; - inverse.removeAll(toRetain); - this.description = description; - } - - @Override - public String toString() { - return description; - } - } - - private Target empty; - private Target disjoint; - private Target superset; - private Target nonEmptyProperSubset; - private Target sameElements; - private Target partialOverlap; - private Target containsDuplicates; - - @Override - public void setUp() throws Exception { - super.setUp(); - - empty = new Target(emptyCollection(), "empty"); - disjoint = new Target(ARRAY_LIST.wrap(e3(), e4()), "disjoint"); - superset = new Target(MINIMAL_COLLECTION.of(e0(), e1(), e2(), e3(), e4()), "superset"); - nonEmptyProperSubset = new Target(MINIMAL_COLLECTION.of(e1()), "subset"); - sameElements = new Target(ARRAY_LIST.wrap(createSamplesArray()), "sameElements"); - containsDuplicates = new Target(MINIMAL_COLLECTION.of(e0(), e0(), e3(), e3()), "containsDuplicates"); - partialOverlap = new Target(MINIMAL_COLLECTION.of(e2(), e3()), "partialOverlap"); - } - - // retainAll(empty) -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ZERO) - public void testRetainAll_emptyPreviouslyEmpty() { - expectReturnsFalse(empty); - expectUnchanged(); - } - - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ZERO) - public void testRetainAllExtra_emptyPreviouslyEmpty() { - expectReturnsFalseExtra(empty); - expectUnchanged(); - } - - @CollectionFeature.Require(absent = SUPPORTS_REMOVE) - @CollectionSize.Require(ZERO) - public void testRetainAll_emptyPreviouslyEmptyUnsupported() { - expectReturnsFalseOrThrows(empty); - expectUnchanged(); - } - - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) - public void testRetainAll_emptyPreviouslyNonEmpty() { - expectReturnsTrue(empty); - expectContents(); - expectMissing(e0(), e1(), e2()); - } - - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) - public void testRetainAllExtra_emptyPreviouslyNonEmpty() { - expectReturnsTrueExtra(empty); - expectContents(); - expectMissing(e0(), e1(), e2()); - } - - @CollectionFeature.Require(absent = SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) - public void testRetainAll_emptyPreviouslyNonEmptyUnsupported() { - expectThrows(empty); - expectUnchanged(); - } - - // retainAll(disjoint) - - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ZERO) - public void testRetainAll_disjointPreviouslyEmpty() { - expectReturnsFalse(disjoint); - expectUnchanged(); - } - - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ZERO) - public void testRetainAllExtra_disjointPreviouslyEmpty() { - expectReturnsFalseExtra(disjoint); - expectUnchanged(); - } - - @CollectionFeature.Require(absent = SUPPORTS_REMOVE) - @CollectionSize.Require(ZERO) - public void testRetainAll_disjointPreviouslyEmptyUnsupported() { - expectReturnsFalseOrThrows(disjoint); - expectUnchanged(); - } -#endignore -#if !TYPE_BOOLEAN -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRetainAll_disjointPreviouslyNonEmpty() { - expectReturnsTrue(disjoint); - expectContents(); - expectMissing(e0(), e1(), e2()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRetainAllExtra_disjointPreviouslyNonEmpty() { - expectReturnsTrueExtra(disjoint); - expectContents(); - expectMissing(e0(), e1(), e2()); - } - -#endif -#ignore - @CollectionFeature.Require(absent = SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) - public void testRetainAll_disjointPreviouslyNonEmptyUnsupported() { - expectThrows(disjoint); - expectUnchanged(); - } - - // retainAll(superset) - - @CollectionFeature.Require(SUPPORTS_REMOVE) - public void testRetainAll_superset() { - expectReturnsFalse(superset); - expectUnchanged(); - } - - @CollectionFeature.Require(SUPPORTS_REMOVE) - public void testRetainAllExtra_superset() { - expectReturnsFalseExtra(superset); - expectUnchanged(); - } - - @CollectionFeature.Require(absent = SUPPORTS_REMOVE) - public void testRetainAll_supersetUnsupported() { - expectReturnsFalseOrThrows(superset); - expectUnchanged(); - } - - // retainAll(subset) - - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = { ZERO, ONE }) - public void testRetainAll_subset() { - expectReturnsTrue(nonEmptyProperSubset); - expectContents(nonEmptyProperSubset.toRetain); - } - - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = { ZERO, ONE }) - public void testRetainAllExtra_subset() { - expectReturnsTrueExtra(nonEmptyProperSubset); - expectContents(nonEmptyProperSubset.toRetain); - } - - @CollectionFeature.Require(absent = SUPPORTS_REMOVE) - @CollectionSize.Require(absent = { ZERO, ONE }) - public void testRetainAll_subsetUnsupported() { - expectThrows(nonEmptyProperSubset); - expectUnchanged(); - } - - // retainAll(sameElements) - - @CollectionFeature.Require(SUPPORTS_REMOVE) - public void testRetainAll_sameElements() { - expectReturnsFalse(sameElements); - expectUnchanged(); - } - - @CollectionFeature.Require(SUPPORTS_REMOVE) - public void testRetainAllExtra_sameElements() { - expectReturnsFalseExtra(sameElements); - expectUnchanged(); - } - - @CollectionFeature.Require(absent = SUPPORTS_REMOVE) - public void testRetainAll_sameElementsUnsupported() { - expectReturnsFalseOrThrows(sameElements); - expectUnchanged(); - } - - // retainAll(partialOverlap) - - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = { ZERO, ONE }) - public void testRetainAll_partialOverlap() { - expectReturnsTrue(partialOverlap); - expectContents(e2()); - } - - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = { ZERO, ONE }) - public void testRetainAllExtra_partialOverlap() { - expectReturnsTrueExtra(partialOverlap); - expectContents(e2()); - } - - @CollectionFeature.Require(absent = SUPPORTS_REMOVE) - @CollectionSize.Require(absent = { ZERO, ONE }) - public void testRetainAll_partialOverlapUnsupported() { - expectThrows(partialOverlap); - expectUnchanged(); - } - - // retainAll(containsDuplicates) - - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ONE) - public void testRetainAll_containsDuplicatesSizeOne() { - expectReturnsFalse(containsDuplicates); - expectContents(e0()); - } - - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ONE) - public void testRetainAllExtra_containsDuplicatesSizeOne() { - expectReturnsFalseExtra(containsDuplicates); - expectContents(e0()); - } - - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = { ZERO, ONE }) - public void testRetainAll_containsDuplicatesSizeSeveral() { - expectReturnsTrue(containsDuplicates); - expectContents(e0()); - } - - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = { ZERO, ONE }) - public void testRetainAllExtra_containsDuplicatesSizeSeveral() { - expectReturnsTrueExtra(containsDuplicates); - expectContents(e0()); - } - - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ZERO) - public void testRetainAll_nullCollectionReferenceEmptySubject() { - try { - collection.retainAll(null); - // Returning successfully is not ideal, but tolerated. - } catch (NullPointerException tolerated) { - } - } - - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) - public void testRetainAll_nullCollectionReferenceNonEmptySubject() { - try { - collection.retainAll(null); - fail("retainAll(null) should throw NullPointerException"); - } catch (NullPointerException expected) { - } - } - -#endignore - private void expectReturnsTrue(Target target) { - String message = String.format("retainAll(%s) should return true", target); - assertTrue(message, collection.retainAll(target.toRetain)); - } - - private void expectReturnsTrueExtra(Target target) { - String message = String.format("retainAll(%s, Removed) should return true", target); - LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); - assertTrue(message, collection.retainAll(target.toRetain, list::add)); - HELPERS.assertEqualIgnoringOrder(target.inverse, list); - } - - private void expectReturnsFalse(Target target) { - String message = String.format("retainAll(%s) should return false", target); - assertFalse(message, collection.retainAll(target.toRetain)); - } - - private void expectReturnsFalseExtra(Target target) { - String message = String.format("retainAll(%s, Removed) should return false", target); - assertFalse(message, collection.retainAll(target.toRetain, T -> {})); - } - - private void expectThrows(Target target) { - try { - collection.retainAll(target.toRetain); - fail(String.format("retainAll(%s) should throw", target)); - } catch (UnsupportedOperationException expected) { - } - } - - private void expectReturnsFalseOrThrows(Target target) { - String message = String.format("retainAll(%s) should return false or throw", target); - try { - assertFalse(message, collection.retainAll(target.toRetain)); - } catch (UnsupportedOperationException tolerated) { - } - } -} +package speiger.src.testers.PACKAGE.tests.collection; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import org.junit.Ignore; + +import speiger.src.collections.PACKAGE.collections.COLLECTION; +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; +import speiger.src.testers.PACKAGE.utils.HELPERS; +import speiger.src.testers.PACKAGE.utils.MINIMAL_COLLECTION; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPECollectionRetainAllTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE +{ + + private class Target { + private final COLLECTION KEY_GENERIC_TYPE toRetain; + private final COLLECTION KEY_GENERIC_TYPE inverse = ARRAY_LIST.wrap(createSamplesArray()); + private final String description; + + private Target(COLLECTION KEY_GENERIC_TYPE toRetain, String description) { + this.toRetain = toRetain; + inverse.removeAll(toRetain); + this.description = description; + } + + @Override + public String toString() { + return description; + } + } + + private Target empty; + private Target disjoint; + private Target superset; + private Target nonEmptyProperSubset; + private Target sameElements; + private Target partialOverlap; + private Target containsDuplicates; + + @Override + public void setUp() throws Exception { + super.setUp(); + + empty = new Target(emptyCollection(), "empty"); + disjoint = new Target(ARRAY_LIST.wrap(e3(), e4()), "disjoint"); + superset = new Target(MINIMAL_COLLECTION.of(e0(), e1(), e2(), e3(), e4()), "superset"); + nonEmptyProperSubset = new Target(MINIMAL_COLLECTION.of(e1()), "subset"); + sameElements = new Target(ARRAY_LIST.wrap(createSamplesArray()), "sameElements"); + containsDuplicates = new Target(MINIMAL_COLLECTION.of(e0(), e0(), e3(), e3()), "containsDuplicates"); + partialOverlap = new Target(MINIMAL_COLLECTION.of(e2(), e3()), "partialOverlap"); + } + + // retainAll(empty) +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ZERO) + public void testRetainAll_emptyPreviouslyEmpty() { + expectReturnsFalse(empty); + expectUnchanged(); + } + + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ZERO) + public void testRetainAllExtra_emptyPreviouslyEmpty() { + expectReturnsFalseExtra(empty); + expectUnchanged(); + } + + @CollectionFeature.Require(absent = SUPPORTS_REMOVE) + @CollectionSize.Require(ZERO) + public void testRetainAll_emptyPreviouslyEmptyUnsupported() { + expectReturnsFalseOrThrows(empty); + expectUnchanged(); + } + + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) + public void testRetainAll_emptyPreviouslyNonEmpty() { + expectReturnsTrue(empty); + expectContents(); + expectMissing(e0(), e1(), e2()); + } + + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) + public void testRetainAllExtra_emptyPreviouslyNonEmpty() { + expectReturnsTrueExtra(empty); + expectContents(); + expectMissing(e0(), e1(), e2()); + } + + @CollectionFeature.Require(absent = SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) + public void testRetainAll_emptyPreviouslyNonEmptyUnsupported() { + expectThrows(empty); + expectUnchanged(); + } + + // retainAll(disjoint) + + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ZERO) + public void testRetainAll_disjointPreviouslyEmpty() { + expectReturnsFalse(disjoint); + expectUnchanged(); + } + + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ZERO) + public void testRetainAllExtra_disjointPreviouslyEmpty() { + expectReturnsFalseExtra(disjoint); + expectUnchanged(); + } + + @CollectionFeature.Require(absent = SUPPORTS_REMOVE) + @CollectionSize.Require(ZERO) + public void testRetainAll_disjointPreviouslyEmptyUnsupported() { + expectReturnsFalseOrThrows(disjoint); + expectUnchanged(); + } +#endignore +#if !TYPE_BOOLEAN +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRetainAll_disjointPreviouslyNonEmpty() { + expectReturnsTrue(disjoint); + expectContents(); + expectMissing(e0(), e1(), e2()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRetainAllExtra_disjointPreviouslyNonEmpty() { + expectReturnsTrueExtra(disjoint); + expectContents(); + expectMissing(e0(), e1(), e2()); + } + +#endif +#ignore + @CollectionFeature.Require(absent = SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) + public void testRetainAll_disjointPreviouslyNonEmptyUnsupported() { + expectThrows(disjoint); + expectUnchanged(); + } + + // retainAll(superset) + + @CollectionFeature.Require(SUPPORTS_REMOVE) + public void testRetainAll_superset() { + expectReturnsFalse(superset); + expectUnchanged(); + } + + @CollectionFeature.Require(SUPPORTS_REMOVE) + public void testRetainAllExtra_superset() { + expectReturnsFalseExtra(superset); + expectUnchanged(); + } + + @CollectionFeature.Require(absent = SUPPORTS_REMOVE) + public void testRetainAll_supersetUnsupported() { + expectReturnsFalseOrThrows(superset); + expectUnchanged(); + } + + // retainAll(subset) + + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = { ZERO, ONE }) + public void testRetainAll_subset() { + expectReturnsTrue(nonEmptyProperSubset); + expectContents(nonEmptyProperSubset.toRetain); + } + + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = { ZERO, ONE }) + public void testRetainAllExtra_subset() { + expectReturnsTrueExtra(nonEmptyProperSubset); + expectContents(nonEmptyProperSubset.toRetain); + } + + @CollectionFeature.Require(absent = SUPPORTS_REMOVE) + @CollectionSize.Require(absent = { ZERO, ONE }) + public void testRetainAll_subsetUnsupported() { + expectThrows(nonEmptyProperSubset); + expectUnchanged(); + } + + // retainAll(sameElements) + + @CollectionFeature.Require(SUPPORTS_REMOVE) + public void testRetainAll_sameElements() { + expectReturnsFalse(sameElements); + expectUnchanged(); + } + + @CollectionFeature.Require(SUPPORTS_REMOVE) + public void testRetainAllExtra_sameElements() { + expectReturnsFalseExtra(sameElements); + expectUnchanged(); + } + + @CollectionFeature.Require(absent = SUPPORTS_REMOVE) + public void testRetainAll_sameElementsUnsupported() { + expectReturnsFalseOrThrows(sameElements); + expectUnchanged(); + } + + // retainAll(partialOverlap) + + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = { ZERO, ONE }) + public void testRetainAll_partialOverlap() { + expectReturnsTrue(partialOverlap); + expectContents(e2()); + } + + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = { ZERO, ONE }) + public void testRetainAllExtra_partialOverlap() { + expectReturnsTrueExtra(partialOverlap); + expectContents(e2()); + } + + @CollectionFeature.Require(absent = SUPPORTS_REMOVE) + @CollectionSize.Require(absent = { ZERO, ONE }) + public void testRetainAll_partialOverlapUnsupported() { + expectThrows(partialOverlap); + expectUnchanged(); + } + + // retainAll(containsDuplicates) + + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ONE) + public void testRetainAll_containsDuplicatesSizeOne() { + expectReturnsFalse(containsDuplicates); + expectContents(e0()); + } + + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ONE) + public void testRetainAllExtra_containsDuplicatesSizeOne() { + expectReturnsFalseExtra(containsDuplicates); + expectContents(e0()); + } + + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = { ZERO, ONE }) + public void testRetainAll_containsDuplicatesSizeSeveral() { + expectReturnsTrue(containsDuplicates); + expectContents(e0()); + } + + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = { ZERO, ONE }) + public void testRetainAllExtra_containsDuplicatesSizeSeveral() { + expectReturnsTrueExtra(containsDuplicates); + expectContents(e0()); + } + + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ZERO) + public void testRetainAll_nullCollectionReferenceEmptySubject() { + try { + collection.retainAll(null); + // Returning successfully is not ideal, but tolerated. + } catch (NullPointerException tolerated) { + } + } + + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) + public void testRetainAll_nullCollectionReferenceNonEmptySubject() { + try { + collection.retainAll(null); + fail("retainAll(null) should throw NullPointerException"); + } catch (NullPointerException expected) { + } + } + +#endignore + private void expectReturnsTrue(Target target) { + String message = String.format("retainAll(%s) should return true", target); + assertTrue(message, collection.retainAll(target.toRetain)); + } + + private void expectReturnsTrueExtra(Target target) { + String message = String.format("retainAll(%s, Removed) should return true", target); + LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); + assertTrue(message, collection.retainAll(target.toRetain, list::add)); + HELPERS.assertEqualIgnoringOrder(target.inverse, list); + } + + private void expectReturnsFalse(Target target) { + String message = String.format("retainAll(%s) should return false", target); + assertFalse(message, collection.retainAll(target.toRetain)); + } + + private void expectReturnsFalseExtra(Target target) { + String message = String.format("retainAll(%s, Removed) should return false", target); + assertFalse(message, collection.retainAll(target.toRetain, T -> {})); + } + + private void expectThrows(Target target) { + try { + collection.retainAll(target.toRetain); + fail(String.format("retainAll(%s) should throw", target)); + } catch (UnsupportedOperationException expected) { + } + } + + private void expectReturnsFalseOrThrows(Target target) { + String message = String.format("retainAll(%s) should return false or throw", target); + try { + assertFalse(message, collection.retainAll(target.toRetain)); + } catch (UnsupportedOperationException tolerated) { + } + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionStreamTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionStreamTester.template index a5508d6..5a06d9a 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionStreamTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/collection/CollectionStreamTester.template @@ -1,59 +1,59 @@ -package speiger.src.testers.PACKAGE.tests.collection; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; -#endignore - -import com.google.common.collect.testing.features.CollectionFeature; - -import org.junit.Ignore; - -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -#if !JDK_TYPE -import speiger.src.collections.utils.SanityChecks; -#endif -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; -import speiger.src.testers.PACKAGE.utils.HELPERS; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPECollectionStreamTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(absent = KNOWN_ORDER) - public void testStreamToArrayUnknownOrder() { -#endignore - synchronized (collection) { - HELPERS.assertContentsAnyOrder(getSampleElements(), unwrap(collection.primitiveStream().toArray())); - } - } - -#ignore - @CollectionFeature.Require(KNOWN_ORDER) - public void testStreamToArrayKnownOrder() { -#endignore - synchronized (collection) { - assertEquals(getOrderedElements(), ARRAY_LIST.wrap(unwrap(collection.primitiveStream().toArray()))); - } - } - - public void testStreamCount() { - synchronized (collection) { - assertEquals(getNumElements(), collection.primitiveStream().count()); - } - } - -#if JDK_TYPE - public KEY_TYPE[] unwrap(KEY_TYPE[] input) { - return input; - } -#else - public KEY_TYPE[] unwrap(KEY_JAVA_TYPE[] input) { - KEY_TYPE[] other = NEW_KEY_ARRAY(input.length); - for(int i = 0,m=input.length;i false)); - } - - public void testIterableCount_AllFound() { - assertEquals("Expected All to be found", getNumElements(), collection.count(T -> true)); - } - -#ignore - @CollectionSize.Require(absent = CollectionSize.ZERO) -#endignore - public void testIterableCount_FindFirst() - { - assertEquals("First element should be found", 1, collection.count(T -> KEY_EQUALS(T, e0()))); - } - -#ignore - @CollectionSize.Require(CollectionSize.SEVERAL) -#endignore - public void testIterableCount_FindLast() { - assertEquals("Last element should be found", 1, collection.count(T -> KEY_EQUALS(T, e2()))); - } +package speiger.src.testers.PACKAGE.tests.iterable; + +#if TYPE_OBJECT +import java.util.Objects; + +#endif +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEIterableCountTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE +{ + public void testIterableCount_null() { + try { + collection.count(null); + fail("This should throw a NullPointerException"); + } catch (NullPointerException e) { + } + } + + public void testIterableCount_NoneFound() { + assertEquals("Expected none to be found", 0, collection.count(T -> false)); + } + + public void testIterableCount_AllFound() { + assertEquals("Expected All to be found", getNumElements(), collection.count(T -> true)); + } + +#ignore + @CollectionSize.Require(absent = CollectionSize.ZERO) +#endignore + public void testIterableCount_FindFirst() + { + assertEquals("First element should be found", 1, collection.count(T -> KEY_EQUALS(T, e0()))); + } + +#ignore + @CollectionSize.Require(CollectionSize.SEVERAL) +#endignore + public void testIterableCount_FindLast() { + assertEquals("Last element should be found", 1, collection.count(T -> KEY_EQUALS(T, e2()))); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableDistinctTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableDistinctTester.template index 8e7c0b5..3592eb4 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableDistinctTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableDistinctTester.template @@ -1,24 +1,24 @@ -package speiger.src.testers.PACKAGE.tests.iterable; - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEIterableDistinctTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionSize.Require(CollectionSize.SEVERAL) -#endignore - public void testDistinct() - { - ArrayWithDuplicate KEY_GENERIC_TYPE duplicate = createArrayWithDuplicateElement(); - resetContainer(primitiveGenerator.create(duplicate.elements)); - LIST KEY_GENERIC_TYPE list = collection.distinct().pourAsList(); - assertEquals("Distinct should remove duplicate elements", list.indexOf(duplicate.duplicate), list.lastIndexOf(duplicate.duplicate)); - } -} +package speiger.src.testers.PACKAGE.tests.iterable; + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEIterableDistinctTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionSize.Require(CollectionSize.SEVERAL) +#endignore + public void testDistinct() + { + ArrayWithDuplicate KEY_GENERIC_TYPE duplicate = createArrayWithDuplicateElement(); + resetContainer(primitiveGenerator.create(duplicate.elements)); + LIST KEY_GENERIC_TYPE list = collection.distinct().pourAsList(); + assertEquals("Distinct should remove duplicate elements", list.indexOf(duplicate.duplicate), list.lastIndexOf(duplicate.duplicate)); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableFilterTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableFilterTester.template index cb2efdb..9cd5ef6 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableFilterTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableFilterTester.template @@ -1,52 +1,52 @@ -package speiger.src.testers.PACKAGE.tests.iterable; - -#if TYPE_OBJECT -import java.util.Objects; - -#endif -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.sets.SET; -import speiger.src.collections.PACKAGE.utils.SETS; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEIterableFilterTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE -{ - public void testIterableFilter_missingElement() { - assertTrue(expectMissing(collection.filter(T -> KEY_EQUALS_NOT(T, e0())).pourAsSet(), e0())); - } - -#ignore - @CollectionSize.Require(absent = CollectionSize.ZERO) -#endignore - public void testIterableFilter_filterElement() { - assertFalse(expectMissing(SETS.singleton(e0()), collection.filter(T -> KEY_EQUALS(T, e0())).pourAsSet().TO_ARRAY())); - } - -#ignore - @CollectionSize.Require(CollectionSize.ONE) -#endignore - public void testIterableFilter_filterMissing() { - assertTrue(collection.filter(T -> KEY_EQUALS(T, e1())).pourAsList().isEmpty()); - } - -#ignore - @CollectionSize.Require(CollectionSize.SEVERAL) -#endignore - public void testIterableFilter_filterSeveral() { - assertTrue(expectMissing(SETS.singleton(e1()), collection.filter(T -> KEY_EQUALS_NOT(T, e1())).pourAsSet().TO_ARRAY())); - } - - protected boolean expectMissing(SET KEY_GENERIC_TYPE set, KEY_OBJECT_TYPE...elements) - { - for(KEY_OBJECT_TYPE element : elements) - { - if(set.contains(element)) return false; - } - return true; - } -} +package speiger.src.testers.PACKAGE.tests.iterable; + +#if TYPE_OBJECT +import java.util.Objects; + +#endif +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.sets.SET; +import speiger.src.collections.PACKAGE.utils.SETS; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEIterableFilterTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE +{ + public void testIterableFilter_missingElement() { + assertTrue(expectMissing(collection.filter(T -> KEY_EQUALS_NOT(T, e0())).pourAsSet(), e0())); + } + +#ignore + @CollectionSize.Require(absent = CollectionSize.ZERO) +#endignore + public void testIterableFilter_filterElement() { + assertFalse(expectMissing(SETS.singleton(e0()), collection.filter(T -> KEY_EQUALS(T, e0())).pourAsSet().TO_ARRAY())); + } + +#ignore + @CollectionSize.Require(CollectionSize.ONE) +#endignore + public void testIterableFilter_filterMissing() { + assertTrue(collection.filter(T -> KEY_EQUALS(T, e1())).pourAsList().isEmpty()); + } + +#ignore + @CollectionSize.Require(CollectionSize.SEVERAL) +#endignore + public void testIterableFilter_filterSeveral() { + assertTrue(expectMissing(SETS.singleton(e1()), collection.filter(T -> KEY_EQUALS_NOT(T, e1())).pourAsSet().TO_ARRAY())); + } + + protected boolean expectMissing(SET KEY_GENERIC_TYPE set, KEY_OBJECT_TYPE...elements) + { + for(KEY_OBJECT_TYPE element : elements) + { + if(set.contains(element)) return false; + } + return true; + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableFindFirstTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableFindFirstTester.template index a096c13..c84d013 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableFindFirstTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableFindFirstTester.template @@ -1,43 +1,43 @@ -package speiger.src.testers.PACKAGE.tests.iterable; - -#if TYPE_OBJECT -import java.util.Objects; - -#endif -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEIterableFindFirstTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE -{ - public void testIterableFindFirst_null() { - try { - container.findFirst(null); - fail("This should throw a NullPointerException"); - } - catch (NullPointerException e) { - } - } - -#ignore - @CollectionSize.Require(absent = CollectionSize.ZERO) -#endignore - public void testIterableFindFirst_FindFirstElements() { - assertEquals("First Element should be found", e0(), container.findFirst(T -> KEY_EQUALS(T, e0()))); - } - - public void testIterableFindFirst_FindNothing() { - assertEquals("No element should be found", EMPTY_KEY_VALUE, container.findFirst(T -> KEY_EQUALS(T, e4()))); - } - -#ignore - @CollectionSize.Require(CollectionSize.SEVERAL) -#endignore - public void testIterableFindFirst_FindLastElement() { - assertEquals("Last Element should be found", e2(), container.findFirst(T -> KEY_EQUALS(T, e2()))); - } -} +package speiger.src.testers.PACKAGE.tests.iterable; + +#if TYPE_OBJECT +import java.util.Objects; + +#endif +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEIterableFindFirstTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE +{ + public void testIterableFindFirst_null() { + try { + container.findFirst(null); + fail("This should throw a NullPointerException"); + } + catch (NullPointerException e) { + } + } + +#ignore + @CollectionSize.Require(absent = CollectionSize.ZERO) +#endignore + public void testIterableFindFirst_FindFirstElements() { + assertEquals("First Element should be found", e0(), container.findFirst(T -> KEY_EQUALS(T, e0()))); + } + + public void testIterableFindFirst_FindNothing() { + assertEquals("No element should be found", EMPTY_KEY_VALUE, container.findFirst(T -> KEY_EQUALS(T, e4()))); + } + +#ignore + @CollectionSize.Require(CollectionSize.SEVERAL) +#endignore + public void testIterableFindFirst_FindLastElement() { + assertEquals("Last Element should be found", e2(), container.findFirst(T -> KEY_EQUALS(T, e2()))); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableLimitTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableLimitTester.template index 7e189a6..e65a0b7 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableLimitTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableLimitTester.template @@ -1,25 +1,25 @@ -package speiger.src.testers.PACKAGE.tests.iterable; - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEIterableLimitTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionSize.Require(absent = CollectionSize.ZERO) -#endignore - public void testIterableLimit() { - LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(collection); - list.REMOVE(list.size()-1); - LIST KEY_GENERIC_TYPE result = collection.limit(getNumElements()-1).pourAsList(); - assertEquals(list.size(), result.size()); - assertEquals("Limit does not retain the iteration order", list, result); - } -} +package speiger.src.testers.PACKAGE.tests.iterable; + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEIterableLimitTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionSize.Require(absent = CollectionSize.ZERO) +#endignore + public void testIterableLimit() { + LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(collection); + list.REMOVE(list.size()-1); + LIST KEY_GENERIC_TYPE result = collection.limit(getNumElements()-1).pourAsList(); + assertEquals(list.size(), result.size()); + assertEquals("Limit does not retain the iteration order", list, result); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableMapTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableMapTester.template index de3ac30..9bad959 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableMapTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableMapTester.template @@ -1,132 +1,132 @@ -package speiger.src.testers.PACKAGE.tests.iterable; - -#if TYPE_OBJECT -import java.util.Objects; -#endif - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionFeature; - -#if TYPE_OBJECT -import speiger.src.collections.chars.utils.CharArrays; -#endif -import speiger.src.collections.objects.lists.ObjectArrayList; -import speiger.src.collections.objects.lists.ObjectList; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; -import speiger.src.testers.PACKAGE.utils.HELPERS; -#if !TYPE_OBJECT -import speiger.src.testers.objects.utils.ObjectHelpers; -#endif - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEIterableMapTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE -{ - public void testIterableMap_ToString() { - assertEquals(HELPERS.copyToList(collection).toString(), collection.map(CLASS_OBJECT_TYPE::toString).pourAsList().toString()); - } -#if !TYPE_OBJECT - -#ignore - @CollectionFeature.Require(CollectionFeature.KNOWN_ORDER) -#endignore - public void testIterableMap_Collection() { - ObjectList result = new ObjectArrayList<>(); - for(KEY_TYPE entry : getOrderedElements()) { - result.addAll(toRange((int)entry)); - } - assertEquals(result, collection.flatMap(T -> ObjectArrayList.wrap(toRange((int)T))).pourAsList()); - } - -#ignore - @CollectionFeature.Require(CollectionFeature.KNOWN_ORDER) -#endignore - public void testIterableMap_Array() { - ObjectList result = new ObjectArrayList<>(); - for(KEY_TYPE entry : getOrderedElements()) { - result.addAll(toRange((int)entry)); - } - assertEquals(result, collection.arrayflatMap(T -> toRange((int)T)).pourAsList()); - } - -#ignore - @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) -#endignore - public void testIterableMap_CollectionUnordered() { - ObjectList result = new ObjectArrayList<>(); - for(KEY_TYPE entry : getOrderedElements()) { - result.addAll(toRange((int)entry)); - } - ObjectHelpers.assertEqualIgnoringOrder(result, collection.flatMap(T -> ObjectArrayList.wrap(toRange((int)T))).pourAsList()); - } - -#ignore - @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) -#endignore - public void testIterableMap_ArrayUnordered() { - ObjectList result = new ObjectArrayList<>(); - for(KEY_TYPE entry : getOrderedElements()) { - result.addAll(toRange((int)entry)); - } - ObjectHelpers.assertEqualIgnoringOrder(result, collection.arrayflatMap(T -> toRange((int)T)).pourAsList()); - } - - private Integer[] toRange(int range) { - Integer[] result = new Integer[range]; - for(int i = 0;i result = new ObjectArrayList<>(); - for(KEY_TYPE entry : getOrderedElements()) { - result.addAll(toRange(entry)); - } - assertEquals(result, collection.flatMap(T -> ObjectArrayList.wrap(toRange(T))).pourAsList()); - } - -#ignore - @CollectionFeature.Require(CollectionFeature.KNOWN_ORDER) -#endignore - public void testIterableMap_Array() { - ObjectList result = new ObjectArrayList<>(); - for(KEY_TYPE entry : getOrderedElements()) { - result.addAll(toRange(entry)); - } - assertEquals(result, collection.arrayflatMap(this::toRange).pourAsList()); - } - -#ignore - @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) -#endignore - public void testIterableMap_CollectionUnordered() { - ObjectList result = new ObjectArrayList<>(); - for(KEY_TYPE entry : getOrderedElements()) { - result.addAll(toRange(entry)); - } - ObjectHelpers.assertEqualIgnoringOrder(result, collection.flatMap(T -> ObjectArrayList.wrap(toRange(T))).pourAsList()); - } - -#ignore - @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) -#endignore - public void testIterableMap_ArrayUnordered() { - ObjectList result = new ObjectArrayList<>(); - for(KEY_TYPE entry : getOrderedElements()) { - result.addAll(toRange(entry)); - } - ObjectHelpers.assertEqualIgnoringOrder(result, collection.arrayflatMap(this::toRange).pourAsList()); - } - - private Character[] toRange(T obj) { - return CharArrays.wrap(Objects.toString(obj).toCharArray()); - } -#endif -} +package speiger.src.testers.PACKAGE.tests.iterable; + +#if TYPE_OBJECT +import java.util.Objects; +#endif + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionFeature; + +#if TYPE_OBJECT +import speiger.src.collections.chars.utils.CharArrays; +#endif +import speiger.src.collections.objects.lists.ObjectArrayList; +import speiger.src.collections.objects.lists.ObjectList; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; +import speiger.src.testers.PACKAGE.utils.HELPERS; +#if !TYPE_OBJECT +import speiger.src.testers.objects.utils.ObjectHelpers; +#endif + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEIterableMapTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE +{ + public void testIterableMap_ToString() { + assertEquals(HELPERS.copyToList(collection).toString(), collection.map(CLASS_OBJECT_TYPE::toString).pourAsList().toString()); + } +#if !TYPE_OBJECT + +#ignore + @CollectionFeature.Require(CollectionFeature.KNOWN_ORDER) +#endignore + public void testIterableMap_Collection() { + ObjectList result = new ObjectArrayList<>(); + for(KEY_TYPE entry : getOrderedElements()) { + result.addAll(toRange((int)entry)); + } + assertEquals(result, collection.flatMap(T -> ObjectArrayList.wrap(toRange((int)T))).pourAsList()); + } + +#ignore + @CollectionFeature.Require(CollectionFeature.KNOWN_ORDER) +#endignore + public void testIterableMap_Array() { + ObjectList result = new ObjectArrayList<>(); + for(KEY_TYPE entry : getOrderedElements()) { + result.addAll(toRange((int)entry)); + } + assertEquals(result, collection.arrayflatMap(T -> toRange((int)T)).pourAsList()); + } + +#ignore + @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) +#endignore + public void testIterableMap_CollectionUnordered() { + ObjectList result = new ObjectArrayList<>(); + for(KEY_TYPE entry : getOrderedElements()) { + result.addAll(toRange((int)entry)); + } + ObjectHelpers.assertEqualIgnoringOrder(result, collection.flatMap(T -> ObjectArrayList.wrap(toRange((int)T))).pourAsList()); + } + +#ignore + @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) +#endignore + public void testIterableMap_ArrayUnordered() { + ObjectList result = new ObjectArrayList<>(); + for(KEY_TYPE entry : getOrderedElements()) { + result.addAll(toRange((int)entry)); + } + ObjectHelpers.assertEqualIgnoringOrder(result, collection.arrayflatMap(T -> toRange((int)T)).pourAsList()); + } + + private Integer[] toRange(int range) { + Integer[] result = new Integer[range]; + for(int i = 0;i result = new ObjectArrayList<>(); + for(KEY_TYPE entry : getOrderedElements()) { + result.addAll(toRange(entry)); + } + assertEquals(result, collection.flatMap(T -> ObjectArrayList.wrap(toRange(T))).pourAsList()); + } + +#ignore + @CollectionFeature.Require(CollectionFeature.KNOWN_ORDER) +#endignore + public void testIterableMap_Array() { + ObjectList result = new ObjectArrayList<>(); + for(KEY_TYPE entry : getOrderedElements()) { + result.addAll(toRange(entry)); + } + assertEquals(result, collection.arrayflatMap(this::toRange).pourAsList()); + } + +#ignore + @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) +#endignore + public void testIterableMap_CollectionUnordered() { + ObjectList result = new ObjectArrayList<>(); + for(KEY_TYPE entry : getOrderedElements()) { + result.addAll(toRange(entry)); + } + ObjectHelpers.assertEqualIgnoringOrder(result, collection.flatMap(T -> ObjectArrayList.wrap(toRange(T))).pourAsList()); + } + +#ignore + @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) +#endignore + public void testIterableMap_ArrayUnordered() { + ObjectList result = new ObjectArrayList<>(); + for(KEY_TYPE entry : getOrderedElements()) { + result.addAll(toRange(entry)); + } + ObjectHelpers.assertEqualIgnoringOrder(result, collection.arrayflatMap(this::toRange).pourAsList()); + } + + private Character[] toRange(T obj) { + return CharArrays.wrap(Objects.toString(obj).toCharArray()); + } +#endif +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableMatchesTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableMatchesTester.template index 8c188e1..2b77a03 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableMatchesTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableMatchesTester.template @@ -1,107 +1,107 @@ -package speiger.src.testers.PACKAGE.tests.iterable; - -#if TYPE_OBJECT -import java.util.Objects; - -#endif -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.sets.HASH_SET; -import speiger.src.collections.PACKAGE.sets.SET; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEIterableMatchesTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE -{ - public void testIterableMatch_AnyNull() { - try { - collection.matchesAny(null); - fail("MatchesAny should throw a NullPointException"); - } - catch (NullPointerException e) { - } - } - -#ignore - @CollectionSize.Require(absent = CollectionSize.ZERO) -#endignore - public void testIterableMatch_AnyFoundFirstElement() { - assertTrue("Element ["+e0()+"] should be found", collection.matchesAny(T -> KEY_EQUALS(T, e0()))); - } - -#ignore - @CollectionSize.Require(CollectionSize.SEVERAL) -#endignore - public void testIterableMatch_AnyFoundLastElement() { - assertTrue("Element ["+e2()+"] should be found", collection.matchesAny(T -> KEY_EQUALS(T, e2()))); - } - - public void testIterableMatch_AnyFoundNoElement() { - assertFalse("Element ["+e4()+"] should not be found", collection.matchesAny(T -> KEY_EQUALS(T, e4()))); - } - - public void testIterableMatch_NoneNull() { - try { - collection.matchesNone(null); - fail("MatchesNone should throw a NullPointException"); - } - catch (NullPointerException e) { - } - } - -#ignore - @CollectionSize.Require(absent = CollectionSize.ZERO) -#endignore - public void testIterableMatch_NoneFoundFirstElement() { - assertFalse("Element ["+e0()+"] should not be found", collection.matchesNone(T -> KEY_EQUALS(T, e0()))); - } - -#ignore - @CollectionSize.Require(CollectionSize.SEVERAL) -#endignore - public void testIterableMatch_NoneFoundLastElement() { - assertFalse("Element ["+e2()+"] should not be found", collection.matchesNone(T -> KEY_EQUALS(T, e2()))); - } - - public void testIterableMatch_NoneFoundNoElement() { - assertTrue("Element ["+e4()+"] should not be found", collection.matchesNone(T -> KEY_EQUALS(T, e4()))); - } - - public void testIterableMatch_AllNull() { - try { - collection.matchesAll(null); - fail("MatchesAny should throw a NullPointException"); - } - catch (NullPointerException e) { - } - } - - public void testIterableMatch_AllFoundAllElements() { - SET KEY_GENERIC_TYPE set = new HASH_SETBRACES(collection); - assertTrue("All elements should be found", collection.matchesAll(set::contains)); - } - -#ignore - @CollectionSize.Require(absent = CollectionSize.ZERO) -#endignore - public void testIterableMatch_AllFoundNone() { - assertFalse("It should not find anything", collection.matchesAll(T -> false)); - } - -#ignore - @CollectionSize.Require(CollectionSize.ZERO) -#endignore - public void testIterableMatch_AllFoundNoneEmpty() { - assertTrue("Empty Collections should return true even if all have to be found", collection.matchesAll(T -> false)); - } - -#ignore - @CollectionSize.Require(CollectionSize.SEVERAL) -#endignore - public void testIterableMatches_AllPartical() { - assertFalse("Even if some elements were found, it should return false", collection.matchesAll(T -> KEY_EQUALS(T, e0()))); - } -} +package speiger.src.testers.PACKAGE.tests.iterable; + +#if TYPE_OBJECT +import java.util.Objects; + +#endif +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.sets.HASH_SET; +import speiger.src.collections.PACKAGE.sets.SET; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEIterableMatchesTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE +{ + public void testIterableMatch_AnyNull() { + try { + collection.matchesAny(null); + fail("MatchesAny should throw a NullPointException"); + } + catch (NullPointerException e) { + } + } + +#ignore + @CollectionSize.Require(absent = CollectionSize.ZERO) +#endignore + public void testIterableMatch_AnyFoundFirstElement() { + assertTrue("Element ["+e0()+"] should be found", collection.matchesAny(T -> KEY_EQUALS(T, e0()))); + } + +#ignore + @CollectionSize.Require(CollectionSize.SEVERAL) +#endignore + public void testIterableMatch_AnyFoundLastElement() { + assertTrue("Element ["+e2()+"] should be found", collection.matchesAny(T -> KEY_EQUALS(T, e2()))); + } + + public void testIterableMatch_AnyFoundNoElement() { + assertFalse("Element ["+e4()+"] should not be found", collection.matchesAny(T -> KEY_EQUALS(T, e4()))); + } + + public void testIterableMatch_NoneNull() { + try { + collection.matchesNone(null); + fail("MatchesNone should throw a NullPointException"); + } + catch (NullPointerException e) { + } + } + +#ignore + @CollectionSize.Require(absent = CollectionSize.ZERO) +#endignore + public void testIterableMatch_NoneFoundFirstElement() { + assertFalse("Element ["+e0()+"] should not be found", collection.matchesNone(T -> KEY_EQUALS(T, e0()))); + } + +#ignore + @CollectionSize.Require(CollectionSize.SEVERAL) +#endignore + public void testIterableMatch_NoneFoundLastElement() { + assertFalse("Element ["+e2()+"] should not be found", collection.matchesNone(T -> KEY_EQUALS(T, e2()))); + } + + public void testIterableMatch_NoneFoundNoElement() { + assertTrue("Element ["+e4()+"] should not be found", collection.matchesNone(T -> KEY_EQUALS(T, e4()))); + } + + public void testIterableMatch_AllNull() { + try { + collection.matchesAll(null); + fail("MatchesAny should throw a NullPointException"); + } + catch (NullPointerException e) { + } + } + + public void testIterableMatch_AllFoundAllElements() { + SET KEY_GENERIC_TYPE set = new HASH_SETBRACES(collection); + assertTrue("All elements should be found", collection.matchesAll(set::contains)); + } + +#ignore + @CollectionSize.Require(absent = CollectionSize.ZERO) +#endignore + public void testIterableMatch_AllFoundNone() { + assertFalse("It should not find anything", collection.matchesAll(T -> false)); + } + +#ignore + @CollectionSize.Require(CollectionSize.ZERO) +#endignore + public void testIterableMatch_AllFoundNoneEmpty() { + assertTrue("Empty Collections should return true even if all have to be found", collection.matchesAll(T -> false)); + } + +#ignore + @CollectionSize.Require(CollectionSize.SEVERAL) +#endignore + public void testIterableMatches_AllPartical() { + assertFalse("Even if some elements were found, it should return false", collection.matchesAll(T -> KEY_EQUALS(T, e0()))); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterablePeekTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterablePeekTester.template index fcd7696..f7b7c2f 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterablePeekTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterablePeekTester.template @@ -1,19 +1,19 @@ -package speiger.src.testers.PACKAGE.tests.iterable; - -import org.junit.Ignore; - -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEIterablePeekTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE -{ - public void testIterablePeek() { - LIST KEY_GENERIC_TYPE peeked = new ARRAY_LISTBRACES(); - LIST KEY_GENERIC_TYPE result = new ARRAY_LISTBRACES(); - collection.peek(peeked::add).forEach(result::add); - assertEquals("Collections should match since peek is just a preview of foreach", result, peeked); - } -} +package speiger.src.testers.PACKAGE.tests.iterable; + +import org.junit.Ignore; + +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEIterablePeekTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE +{ + public void testIterablePeek() { + LIST KEY_GENERIC_TYPE peeked = new ARRAY_LISTBRACES(); + LIST KEY_GENERIC_TYPE result = new ARRAY_LISTBRACES(); + collection.peek(peeked::add).forEach(result::add); + assertEquals("Collections should match since peek is just a preview of foreach", result, peeked); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableReduceTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableReduceTester.template index ffc5a7b..4335ede 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableReduceTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableReduceTester.template @@ -1,78 +1,78 @@ -package speiger.src.testers.PACKAGE.tests.iterable; - -#if TYPE_OBJECT -import java.util.Objects; - -#endif -import org.junit.Ignore; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEIterableReduceTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE -{ - public void testIterableReduce_Null() { - try { - collection.reduce(null); - fail("This should crash"); - } catch (NullPointerException e) { - } - } - - public void testIterableReduce_extraNull() { - try { - collection.reduce(EMPTY_KEY_VALUE, null); - fail("This should crash"); - } catch (NullPointerException e) { - } - } - - public void testIterableReduce() { - assertEquals("The sum of the collection should match", getSum(), collection.reduce(this::sum)); - } - - public void testIterableExtraReduce() { -#if TYPE_OBJECT - assertEquals("The sum of the collection should match", getObjectSum(), collection.reduce(new StringBuilder(), this::sum).toString()); -#else - assertEquals("The sum of the collection should match", getSum(), collection.reduce(EMPTY_KEY_VALUE, this::sum)); -#endif - } - - public KEY_TYPE getSum() - { - KEY_TYPE result = EMPTY_KEY_VALUE; - for(KEY_TYPE key : collection) - { - result = sum(result, key); - } - return result; - } - - public KEY_TYPE sum(KEY_TYPE key, KEY_TYPE value) - { -#if TYPE_BYTE || TYPE_SHORT || TYPE_CHAR - return (KEY_TYPE)(key + value); -#else if TYPE_OBJECT - return value; -#else - return key + value; -#endif - } - -#if TYPE_OBJECT - public StringBuilder sum(StringBuilder builder, T value) { - return builder.append(Objects.toString(value)); - } - - public String getObjectSum() { - StringBuilder builder = new StringBuilder(); - for(T key : collection) - { - builder = sum(builder, key); - } - return builder.toString(); - } -#endif -} +package speiger.src.testers.PACKAGE.tests.iterable; + +#if TYPE_OBJECT +import java.util.Objects; + +#endif +import org.junit.Ignore; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEIterableReduceTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE +{ + public void testIterableReduce_Null() { + try { + collection.reduce(null); + fail("This should crash"); + } catch (NullPointerException e) { + } + } + + public void testIterableReduce_extraNull() { + try { + collection.reduce(EMPTY_KEY_VALUE, null); + fail("This should crash"); + } catch (NullPointerException e) { + } + } + + public void testIterableReduce() { + assertEquals("The sum of the collection should match", getSum(), collection.reduce(this::sum)); + } + + public void testIterableExtraReduce() { +#if TYPE_OBJECT + assertEquals("The sum of the collection should match", getObjectSum(), collection.reduce(new StringBuilder(), this::sum).toString()); +#else + assertEquals("The sum of the collection should match", getSum(), collection.reduce(EMPTY_KEY_VALUE, this::sum)); +#endif + } + + public KEY_TYPE getSum() + { + KEY_TYPE result = EMPTY_KEY_VALUE; + for(KEY_TYPE key : collection) + { + result = sum(result, key); + } + return result; + } + + public KEY_TYPE sum(KEY_TYPE key, KEY_TYPE value) + { +#if TYPE_BYTE || TYPE_SHORT || TYPE_CHAR + return (KEY_TYPE)(key + value); +#else if TYPE_OBJECT + return value; +#else + return key + value; +#endif + } + +#if TYPE_OBJECT + public StringBuilder sum(StringBuilder builder, T value) { + return builder.append(Objects.toString(value)); + } + + public String getObjectSum() { + StringBuilder builder = new StringBuilder(); + for(T key : collection) + { + builder = sum(builder, key); + } + return builder.toString(); + } +#endif +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableSortedTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableSortedTester.template index fc20fa5..6a96d15 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableSortedTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/iterable/IterableSortedTester.template @@ -1,43 +1,43 @@ -package speiger.src.testers.PACKAGE.tests.iterable; - -import org.junit.Ignore; - -#if TYPE_OBJECT -import java.util.Comparator; -import java.util.Map; -#endif - -import com.google.common.collect.testing.features.CollectionFeature; - -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; -import speiger.src.testers.utils.SpecialFeature; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEIterableSortedTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) - @SpecialFeature.Require(absent = SpecialFeature.MAP_ENTRY) -#endignore - public void testIterableSorted() { - LIST KEY_GENERIC_TYPE expected = new ARRAY_LISTBRACES(collection); - expected.sort(null); - assertEquals("Elements were expected to be sorted", expected, collection.sorted(null).pourAsList()); - } - -#if TYPE_OBJECT -#ignore - @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) - @SpecialFeature.Require(SpecialFeature.MAP_ENTRY) -#endignore - public void testIterableSortedEntry() { - ObjectList expected = new ObjectArrayList<>(collection); - Comparator comparator = Comparator.comparing(T -> (Comparable)((Map.Entry)T).getKey()); - expected.sort(comparator); - assertEquals("Elements were expected to be sorted", expected, collection.sorted(comparator).pourAsList()); - } -#endif -} +package speiger.src.testers.PACKAGE.tests.iterable; + +import org.junit.Ignore; + +#if TYPE_OBJECT +import java.util.Comparator; +import java.util.Map; +#endif + +import com.google.common.collect.testing.features.CollectionFeature; + +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_COLLECTION_TESTER; +import speiger.src.testers.utils.SpecialFeature; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEIterableSortedTester KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) + @SpecialFeature.Require(absent = SpecialFeature.MAP_ENTRY) +#endignore + public void testIterableSorted() { + LIST KEY_GENERIC_TYPE expected = new ARRAY_LISTBRACES(collection); + expected.sort(null); + assertEquals("Elements were expected to be sorted", expected, collection.sorted(null).pourAsList()); + } + +#if TYPE_OBJECT +#ignore + @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) + @SpecialFeature.Require(SpecialFeature.MAP_ENTRY) +#endignore + public void testIterableSortedEntry() { + ObjectList expected = new ObjectArrayList<>(collection); + Comparator comparator = Comparator.comparing(T -> (Comparable)((Map.Entry)T).getKey()); + expected.sort(comparator); + assertEquals("Elements were expected to be sorted", expected, collection.sorted(comparator).pourAsList()); + } +#endif +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAbsentTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAbsentTester.template index a52f19e..e3015f2 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAbsentTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAbsentTester.template @@ -1,60 +1,60 @@ -package speiger.src.testers.PACKAGE.tests.list; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; -import static com.google.common.collect.testing.features.CollectionSize.ONE; -#endignore - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListAbsentTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) - @CollectionSize.Require(ONE) -#endignore - public void testIfAbsent() { - assertTrue("addIfAbsent(absent) should return true", getList().addIfAbsent(e1())); - expectAdded(e1()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) - @CollectionSize.Require(ONE) -#endignore - public void testIfPresent() { - assertFalse("addIfAbsent(present) should return false", getList().addIfAbsent(e0())); - expectUnchanged(); - } - -#ignore - @CollectionFeature.Require(absent = SUPPORTS_ADD) - @CollectionSize.Require(ONE) -#endignore - public void test_IfAbsentUnsupported() { - try { - assertFalse("addIfAbsent(absent) should return false", getList().addIfAbsent(e1())); - } catch (UnsupportedOperationException e) { - //Success - } - } - -#ignore - @CollectionFeature.Require(absent = SUPPORTS_ADD) - @CollectionSize.Require(ONE) -#endignore - public void test_IfPresentUnsupported() { - try { - assertFalse("addIfAbsent(present) should return false", getList().addIfAbsent(e0())); - } catch (UnsupportedOperationException e) { - //Success - } - } -} +package speiger.src.testers.PACKAGE.tests.list; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; +import static com.google.common.collect.testing.features.CollectionSize.ONE; +#endignore + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListAbsentTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) + @CollectionSize.Require(ONE) +#endignore + public void testIfAbsent() { + assertTrue("addIfAbsent(absent) should return true", getList().addIfAbsent(e1())); + expectAdded(e1()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) + @CollectionSize.Require(ONE) +#endignore + public void testIfPresent() { + assertFalse("addIfAbsent(present) should return false", getList().addIfAbsent(e0())); + expectUnchanged(); + } + +#ignore + @CollectionFeature.Require(absent = SUPPORTS_ADD) + @CollectionSize.Require(ONE) +#endignore + public void test_IfAbsentUnsupported() { + try { + assertFalse("addIfAbsent(absent) should return false", getList().addIfAbsent(e1())); + } catch (UnsupportedOperationException e) { + //Success + } + } + +#ignore + @CollectionFeature.Require(absent = SUPPORTS_ADD) + @CollectionSize.Require(ONE) +#endignore + public void test_IfPresentUnsupported() { + try { + assertFalse("addIfAbsent(present) should return false", getList().addIfAbsent(e0())); + } catch (UnsupportedOperationException e) { + //Success + } + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAddAllArrayAtIndexTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAddAllArrayAtIndexTester.template index 1c86ab2..de87a37 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAddAllArrayAtIndexTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAddAllArrayAtIndexTester.template @@ -1,194 +1,194 @@ -package speiger.src.testers.PACKAGE.tests.list; - -import org.junit.Ignore; - -#if !TYPE_BOOLEAN -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; -#endignore -#endif -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX; -#endignore - -#if !TYPE_BOOLEAN -import com.google.common.collect.testing.features.CollectionFeature; -#endif -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.ListFeature; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListAddAllArrayAtIndexTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddAllArrayAtIndex_supportedAllPresent() { - getList().addElements(0, createArray(e0())); - expectAddedIndex(0, e0()); - } - -#ignore - @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddAllArrayAtIndex_unsupportedAllPresent() { - try { - getList().addElements(0, createArray(e0())); - fail("addAll(n, allPresent) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddAllArrayAtIndex_supportedSomePresent() { - getList().addElements(0, createArray(e0(), e3())); - expectAddedIndex(0, e0(), e3()); - } - -#ignore - @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddAllArrayAtIndex_unsupportedSomePresent() { - try { - getList().addElements(0, createArray(e0(), e3())); - fail("addAll(n, allPresent) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - expectMissing(e3()); - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) -#endignore - public void testAddAllArrayAtIndex_supportedNothing() { - getList().addElements(0, emptyArray()); - expectUnchanged(); - } - -#ignore - @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) -#endignore - public void testAddAllArrayAtIndex_unsupportedNothing() { - try { - getList().addElements(0, emptyArray()); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) -#endignore - public void testAddAllArrayAtIndex_withDuplicates() { - getList().addElements(0, createArray(e0(), e1(), e0(), e1())); - expectAddedIndex(0, e0(), e1(), e0(), e1()); - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) - @CollectionSize.Require(absent = { ZERO, ONE }) -#endignore - public void testAddAllArrayAtIndex_middle() { - getList().addElements(getNumElements() / 2, createDisjointArray()); - expectAdded(getNumElements() / 2, createDisjointCollection()); - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddAllArrayAtIndex_end() { - getList().addElements(getNumElements(), createDisjointArray()); - expectAdded(getNumElements(), createDisjointCollection()); - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) -#endignore - public void testAddAllArrayAtIndex_nullCollectionReference() { - try { -#if TYPE_OBJECT - getList().addElements(0, (T[])null); -#else - getList().addElements(0, null); -#endif - fail("addElements(n, null) should throw"); - } catch (NullPointerException expected) { - } - expectUnchanged(); - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) -#endignore - public void testAddAllArrayAtIndex_negative() { - try { - getList().addElements(-1, createArray(e3())); - fail("addElements(-1, e) should throw"); - } catch (IndexOutOfBoundsException expected) { - } - expectUnchanged(); - expectMissing(e3()); - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) -#endignore - public void testAddAllArrayAtIndex_tooLarge() { - try { - getList().addElements(getNumElements() + 1, createArray(e3())); - fail("addElements(size + 1, e) should throw"); - } catch (IndexOutOfBoundsException expected) { - } - expectUnchanged(); - expectMissing(e3()); - } - -#if !TYPE_BOOLEAN -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) -#endignore - public void testAddAllArray_supportedToLargeOffset() { - try { - getList().addElements(0, createDisjointArray(), 5, 2); - } catch (IndexOutOfBoundsException e) { - } - expectUnchanged(); - expectMissing(e3(), e4()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) -#endignore - public void testAddAllArray_supportedToSmallOffset() { - try { - getList().addElements(0, createDisjointArray(), -1, 2); - } catch (IndexOutOfBoundsException e) { - } - expectUnchanged(); - expectMissing(e3(), e4()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) -#endignore - public void testAddAllArray_supportedAddSubArray() { - getList().addElements(0, createDisjointArray(), 0, 1); - expectAddedIndex(0, e3()); - expectMissing(e4()); - } -#endif +package speiger.src.testers.PACKAGE.tests.list; + +import org.junit.Ignore; + +#if !TYPE_BOOLEAN +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; +#endignore +#endif +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX; +#endignore + +#if !TYPE_BOOLEAN +import com.google.common.collect.testing.features.CollectionFeature; +#endif +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.ListFeature; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListAddAllArrayAtIndexTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddAllArrayAtIndex_supportedAllPresent() { + getList().addElements(0, createArray(e0())); + expectAddedIndex(0, e0()); + } + +#ignore + @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddAllArrayAtIndex_unsupportedAllPresent() { + try { + getList().addElements(0, createArray(e0())); + fail("addAll(n, allPresent) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddAllArrayAtIndex_supportedSomePresent() { + getList().addElements(0, createArray(e0(), e3())); + expectAddedIndex(0, e0(), e3()); + } + +#ignore + @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddAllArrayAtIndex_unsupportedSomePresent() { + try { + getList().addElements(0, createArray(e0(), e3())); + fail("addAll(n, allPresent) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + expectMissing(e3()); + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) +#endignore + public void testAddAllArrayAtIndex_supportedNothing() { + getList().addElements(0, emptyArray()); + expectUnchanged(); + } + +#ignore + @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) +#endignore + public void testAddAllArrayAtIndex_unsupportedNothing() { + try { + getList().addElements(0, emptyArray()); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) +#endignore + public void testAddAllArrayAtIndex_withDuplicates() { + getList().addElements(0, createArray(e0(), e1(), e0(), e1())); + expectAddedIndex(0, e0(), e1(), e0(), e1()); + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) + @CollectionSize.Require(absent = { ZERO, ONE }) +#endignore + public void testAddAllArrayAtIndex_middle() { + getList().addElements(getNumElements() / 2, createDisjointArray()); + expectAdded(getNumElements() / 2, createDisjointCollection()); + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddAllArrayAtIndex_end() { + getList().addElements(getNumElements(), createDisjointArray()); + expectAdded(getNumElements(), createDisjointCollection()); + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) +#endignore + public void testAddAllArrayAtIndex_nullCollectionReference() { + try { +#if TYPE_OBJECT + getList().addElements(0, (T[])null); +#else + getList().addElements(0, null); +#endif + fail("addElements(n, null) should throw"); + } catch (NullPointerException expected) { + } + expectUnchanged(); + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) +#endignore + public void testAddAllArrayAtIndex_negative() { + try { + getList().addElements(-1, createArray(e3())); + fail("addElements(-1, e) should throw"); + } catch (IndexOutOfBoundsException expected) { + } + expectUnchanged(); + expectMissing(e3()); + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) +#endignore + public void testAddAllArrayAtIndex_tooLarge() { + try { + getList().addElements(getNumElements() + 1, createArray(e3())); + fail("addElements(size + 1, e) should throw"); + } catch (IndexOutOfBoundsException expected) { + } + expectUnchanged(); + expectMissing(e3()); + } + +#if !TYPE_BOOLEAN +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) +#endignore + public void testAddAllArray_supportedToLargeOffset() { + try { + getList().addElements(0, createDisjointArray(), 5, 2); + } catch (IndexOutOfBoundsException e) { + } + expectUnchanged(); + expectMissing(e3(), e4()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) +#endignore + public void testAddAllArray_supportedToSmallOffset() { + try { + getList().addElements(0, createDisjointArray(), -1, 2); + } catch (IndexOutOfBoundsException e) { + } + expectUnchanged(); + expectMissing(e3(), e4()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) +#endignore + public void testAddAllArray_supportedAddSubArray() { + getList().addElements(0, createDisjointArray(), 0, 1); + expectAddedIndex(0, e3()); + expectMissing(e4()); + } +#endif } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAddAllAtIndexTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAddAllAtIndexTester.template index b737861..b065547 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAddAllAtIndexTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAddAllAtIndexTester.template @@ -1,167 +1,167 @@ -package speiger.src.testers.PACKAGE.tests.list; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX; -#endignore - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.ListFeature; - -import speiger.src.collections.PACKAGE.collections.COLLECTION; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; -import speiger.src.testers.PACKAGE.utils.MINIMAL_COLLECTION; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListAddAllAtIndexTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddAllAtIndex_supportedAllPresent() { - assertTrue("addAll(n, allPresent) should return true", getList().addAll(0, MINIMAL_COLLECTION.of(e0()))); - expectAddedIndex(0, e0()); - } - -#ignore - @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddAllAtIndex_unsupportedAllPresent() { - try { - getList().addAll(0, MINIMAL_COLLECTION.of(e0())); - fail("addAll(n, allPresent) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddAllAtIndex_supportedSomePresent() { - assertTrue("addAll(n, allPresent) should return true", getList().addAll(0, MINIMAL_COLLECTION.of(e0(), e3()))); - expectAddedIndex(0, e0(), e3()); - } - -#ignore - @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddAllAtIndex_unsupportedSomePresent() { - try { - getList().addAll(0, MINIMAL_COLLECTION.of(e0(), e3())); - fail("addAll(n, allPresent) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - expectMissing(e3()); - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) -#endignore - public void testAddAllAtIndex_supportedNothing() { - assertFalse("addAll(n, nothing) should return false", getList().addAll(0, emptyCollection())); - expectUnchanged(); - } - -#ignore - @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) -#endignore - public void testAddAllAtIndex_unsupportedNothing() { - try { - assertFalse("addAll(n, nothing) should return false or throw", getList().addAll(0, emptyCollection())); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) -#endignore - public void testAddAllAtIndex_withDuplicates() { - MINIMAL_COLLECTION KEY_GENERIC_TYPE elementsToAdd = MINIMAL_COLLECTION.of(e0(), e1(), e0(), e1()); - assertTrue("addAll(n, hasDuplicates) should return true", getList().addAll(0, elementsToAdd)); - expectAddedIndex(0, e0(), e1(), e0(), e1()); - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) - @CollectionSize.Require(absent = { ZERO, ONE }) -#endignore - public void testAddAllAtIndex_middle() { - assertTrue("addAll(middle, disjoint) should return true", getList().addAll(getNumElements() / 2, createDisjointCollection())); - expectAdded(getNumElements() / 2, createDisjointCollection()); - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddAllAtIndex_end() { - assertTrue("addAll(end, disjoint) should return true", getList().addAll(getNumElements(), createDisjointCollection())); - expectAdded(getNumElements(), createDisjointCollection()); - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) -#endignore - public void testAddAllAtIndex_nullCollectionReference() { - try { - getList().addAll(0, (COLLECTION KEY_GENERIC_TYPE)null); - fail("addAll(n, null) should throw"); - } catch (NullPointerException expected) { - } - expectUnchanged(); - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) -#endignore - public void testAddAllAtIndex_nullListReference() { - try { - getList().addAll(0, (LIST KEY_GENERIC_TYPE)null); - fail("addAll(n, null) should throw"); - } catch (NullPointerException expected) { - } - expectUnchanged(); - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) -#endignore - public void testAddAllAtIndex_negative() { - try { - getList().addAll(-1, MINIMAL_COLLECTION.of(e3())); - fail("addAll(-1, e) should throw"); - } catch (IndexOutOfBoundsException expected) { - } - expectUnchanged(); -#if !TYPE_BOOLEAN - expectMissing(e3()); -#endif - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) -#endignore - public void testAddAllAtIndex_tooLarge() { - try { - getList().addAll(getNumElements() + 1, MINIMAL_COLLECTION.of(e3())); - fail("addAll(size + 1, e) should throw"); - } catch (IndexOutOfBoundsException expected) { - } - expectUnchanged(); -#if !TYPE_BOOLEAN - expectMissing(e3()); -#endif - } -} +package speiger.src.testers.PACKAGE.tests.list; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX; +#endignore + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.ListFeature; + +import speiger.src.collections.PACKAGE.collections.COLLECTION; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; +import speiger.src.testers.PACKAGE.utils.MINIMAL_COLLECTION; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListAddAllAtIndexTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddAllAtIndex_supportedAllPresent() { + assertTrue("addAll(n, allPresent) should return true", getList().addAll(0, MINIMAL_COLLECTION.of(e0()))); + expectAddedIndex(0, e0()); + } + +#ignore + @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddAllAtIndex_unsupportedAllPresent() { + try { + getList().addAll(0, MINIMAL_COLLECTION.of(e0())); + fail("addAll(n, allPresent) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddAllAtIndex_supportedSomePresent() { + assertTrue("addAll(n, allPresent) should return true", getList().addAll(0, MINIMAL_COLLECTION.of(e0(), e3()))); + expectAddedIndex(0, e0(), e3()); + } + +#ignore + @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddAllAtIndex_unsupportedSomePresent() { + try { + getList().addAll(0, MINIMAL_COLLECTION.of(e0(), e3())); + fail("addAll(n, allPresent) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + expectMissing(e3()); + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) +#endignore + public void testAddAllAtIndex_supportedNothing() { + assertFalse("addAll(n, nothing) should return false", getList().addAll(0, emptyCollection())); + expectUnchanged(); + } + +#ignore + @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) +#endignore + public void testAddAllAtIndex_unsupportedNothing() { + try { + assertFalse("addAll(n, nothing) should return false or throw", getList().addAll(0, emptyCollection())); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) +#endignore + public void testAddAllAtIndex_withDuplicates() { + MINIMAL_COLLECTION KEY_GENERIC_TYPE elementsToAdd = MINIMAL_COLLECTION.of(e0(), e1(), e0(), e1()); + assertTrue("addAll(n, hasDuplicates) should return true", getList().addAll(0, elementsToAdd)); + expectAddedIndex(0, e0(), e1(), e0(), e1()); + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) + @CollectionSize.Require(absent = { ZERO, ONE }) +#endignore + public void testAddAllAtIndex_middle() { + assertTrue("addAll(middle, disjoint) should return true", getList().addAll(getNumElements() / 2, createDisjointCollection())); + expectAdded(getNumElements() / 2, createDisjointCollection()); + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddAllAtIndex_end() { + assertTrue("addAll(end, disjoint) should return true", getList().addAll(getNumElements(), createDisjointCollection())); + expectAdded(getNumElements(), createDisjointCollection()); + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) +#endignore + public void testAddAllAtIndex_nullCollectionReference() { + try { + getList().addAll(0, (COLLECTION KEY_GENERIC_TYPE)null); + fail("addAll(n, null) should throw"); + } catch (NullPointerException expected) { + } + expectUnchanged(); + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) +#endignore + public void testAddAllAtIndex_nullListReference() { + try { + getList().addAll(0, (LIST KEY_GENERIC_TYPE)null); + fail("addAll(n, null) should throw"); + } catch (NullPointerException expected) { + } + expectUnchanged(); + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) +#endignore + public void testAddAllAtIndex_negative() { + try { + getList().addAll(-1, MINIMAL_COLLECTION.of(e3())); + fail("addAll(-1, e) should throw"); + } catch (IndexOutOfBoundsException expected) { + } + expectUnchanged(); +#if !TYPE_BOOLEAN + expectMissing(e3()); +#endif + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) +#endignore + public void testAddAllAtIndex_tooLarge() { + try { + getList().addAll(getNumElements() + 1, MINIMAL_COLLECTION.of(e3())); + fail("addAll(size + 1, e) should throw"); + } catch (IndexOutOfBoundsException expected) { + } + expectUnchanged(); +#if !TYPE_BOOLEAN + expectMissing(e3()); +#endif + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAddAllListAtIndexTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAddAllListAtIndexTester.template index b280776..cae09bd 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAddAllListAtIndexTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAddAllListAtIndexTester.template @@ -1,155 +1,155 @@ -package speiger.src.testers.PACKAGE.tests.list; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX; -#endignore - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.ListFeature; - -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListAddAllListAtIndexTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddAllListAtIndex_supportedAllPresent() { - assertTrue("addAll(n, allPresent) should return true", getList().addAll(0, ARRAY_LIST.wrap(e0()))); - expectAddedIndex(0, e0()); - } - -#ignore - @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddAllListAtIndex_unsupportedAllPresent() { - try { - getList().addAll(0, ARRAY_LIST.wrap(e0())); - fail("addAll(n, allPresent) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddAllListAtIndex_supportedSomePresent() { - assertTrue("addAll(n, allPresent) should return true", getList().addAll(0, ARRAY_LIST.wrap(e0(), e3()))); - expectAddedIndex(0, e0(), e3()); - } - -#ignore - @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddAllListAtIndex_unsupportedSomePresent() { - try { - getList().addAll(0, ARRAY_LIST.wrap(e0(), e3())); - fail("addAll(n, allPresent) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); -#if !TYPE_BOOLEAN - expectMissing(e3()); -#endif - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) -#endignore - public void testAddAllListAtIndex_supportedNothing() { - assertFalse("addAll(n, nothing) should return false", getList().addAll(0, new ARRAY_LISTBRACES())); - expectUnchanged(); - } - -#ignore - @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) -#endignore - public void testAddAllListAtIndex_unsupportedNothing() { - try { - assertFalse("addAll(n, nothing) should return false or throw", getList().addAll(0, new ARRAY_LISTBRACES())); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) -#endignore - public void testAddAllListAtIndex_withDuplicates() { - assertTrue("addAll(n, hasDuplicates) should return true", getList().addAll(0, ARRAY_LIST.wrap(e0(), e1(), e0(), e1()))); - expectAddedIndex(0, e0(), e1(), e0(), e1()); - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) - @CollectionSize.Require(absent = { ZERO, ONE }) -#endignore - public void testAddAllListAtIndex_middle() { - assertTrue("addAll(middle, disjoint) should return true", getList().addAll(getNumElements() / 2, new ARRAY_LISTBRACES(createDisjointCollection()))); - expectAdded(getNumElements() / 2, createDisjointCollection()); - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddAllListAtIndex_end() { - assertTrue("addAll(end, disjoint) should return true", getList().addAll(getNumElements(), new ARRAY_LISTBRACES(createDisjointCollection()))); - expectAdded(getNumElements(), createDisjointCollection()); - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) -#endignore - public void testAddAllListAtIndex_nullListReference() { - try { - getList().addAll(0, (LIST KEY_GENERIC_TYPE)null); - fail("addAll(n, null) should throw"); - } catch (NullPointerException expected) { - } - expectUnchanged(); - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) -#endignore - public void testAddAllListAtIndex_negative() { - try { - getList().addAll(-1, ARRAY_LIST.wrap(e3())); - fail("addAll(-1, e) should throw"); - } catch (IndexOutOfBoundsException expected) { - } - expectUnchanged(); -#if !TYPE_BOOLEAN - expectMissing(e3()); -#endif - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) -#endignore - public void testAddAllListAtIndex_tooLarge() { - try { - getList().addAll(getNumElements() + 1, ARRAY_LIST.wrap(e3())); - fail("addAll(size + 1, e) should throw"); - } catch (IndexOutOfBoundsException expected) { - } - expectUnchanged(); -#if !TYPE_BOOLEAN - expectMissing(e3()); -#endif - } -} +package speiger.src.testers.PACKAGE.tests.list; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX; +#endignore + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.ListFeature; + +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListAddAllListAtIndexTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddAllListAtIndex_supportedAllPresent() { + assertTrue("addAll(n, allPresent) should return true", getList().addAll(0, ARRAY_LIST.wrap(e0()))); + expectAddedIndex(0, e0()); + } + +#ignore + @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddAllListAtIndex_unsupportedAllPresent() { + try { + getList().addAll(0, ARRAY_LIST.wrap(e0())); + fail("addAll(n, allPresent) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddAllListAtIndex_supportedSomePresent() { + assertTrue("addAll(n, allPresent) should return true", getList().addAll(0, ARRAY_LIST.wrap(e0(), e3()))); + expectAddedIndex(0, e0(), e3()); + } + +#ignore + @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddAllListAtIndex_unsupportedSomePresent() { + try { + getList().addAll(0, ARRAY_LIST.wrap(e0(), e3())); + fail("addAll(n, allPresent) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); +#if !TYPE_BOOLEAN + expectMissing(e3()); +#endif + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) +#endignore + public void testAddAllListAtIndex_supportedNothing() { + assertFalse("addAll(n, nothing) should return false", getList().addAll(0, new ARRAY_LISTBRACES())); + expectUnchanged(); + } + +#ignore + @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) +#endignore + public void testAddAllListAtIndex_unsupportedNothing() { + try { + assertFalse("addAll(n, nothing) should return false or throw", getList().addAll(0, new ARRAY_LISTBRACES())); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) +#endignore + public void testAddAllListAtIndex_withDuplicates() { + assertTrue("addAll(n, hasDuplicates) should return true", getList().addAll(0, ARRAY_LIST.wrap(e0(), e1(), e0(), e1()))); + expectAddedIndex(0, e0(), e1(), e0(), e1()); + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) + @CollectionSize.Require(absent = { ZERO, ONE }) +#endignore + public void testAddAllListAtIndex_middle() { + assertTrue("addAll(middle, disjoint) should return true", getList().addAll(getNumElements() / 2, new ARRAY_LISTBRACES(createDisjointCollection()))); + expectAdded(getNumElements() / 2, createDisjointCollection()); + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddAllListAtIndex_end() { + assertTrue("addAll(end, disjoint) should return true", getList().addAll(getNumElements(), new ARRAY_LISTBRACES(createDisjointCollection()))); + expectAdded(getNumElements(), createDisjointCollection()); + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) +#endignore + public void testAddAllListAtIndex_nullListReference() { + try { + getList().addAll(0, (LIST KEY_GENERIC_TYPE)null); + fail("addAll(n, null) should throw"); + } catch (NullPointerException expected) { + } + expectUnchanged(); + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) +#endignore + public void testAddAllListAtIndex_negative() { + try { + getList().addAll(-1, ARRAY_LIST.wrap(e3())); + fail("addAll(-1, e) should throw"); + } catch (IndexOutOfBoundsException expected) { + } + expectUnchanged(); +#if !TYPE_BOOLEAN + expectMissing(e3()); +#endif + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) +#endignore + public void testAddAllListAtIndex_tooLarge() { + try { + getList().addAll(getNumElements() + 1, ARRAY_LIST.wrap(e3())); + fail("addAll(size + 1, e) should throw"); + } catch (IndexOutOfBoundsException expected) { + } + expectUnchanged(); +#if !TYPE_BOOLEAN + expectMissing(e3()); +#endif + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAddAllTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAddAllTester.template index 9fc394f..7fa7737 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAddAllTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAddAllTester.template @@ -1,115 +1,115 @@ -package speiger.src.testers.PACKAGE.tests.list; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.collections.COLLECTION; -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; -import speiger.src.testers.PACKAGE.utils.MINIMAL_COLLECTION; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListAddAllTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddAll_supportedAllPresent() { - assertTrue("addAll(allPresent) should return true", getList().addAll(MINIMAL_COLLECTION.of(e0()))); - expectAdded(e0()); - } - -#ignore - @CollectionFeature.Require(absent = SUPPORTS_ADD) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddAll_unsupportedAllPresent() { - try { - getList().addAll(MINIMAL_COLLECTION.of(e0())); - fail("addAll(allPresent) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) -#endignore - public void testAddAll_withDuplicates() { - MINIMAL_COLLECTION KEY_GENERIC_TYPE elementsToAdd = MINIMAL_COLLECTION.of(e0(), e1(), e0(), e1()); - assertTrue("addAll(hasDuplicates) should return true", getList().addAll(elementsToAdd)); - expectAdded(e0(), e1(), e0(), e1()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddAllListCollection_supportedAllPresent() { - assertTrue("addAll(allPresent) should return true", getList().addAll((COLLECTION KEY_GENERIC_TYPE)ARRAY_LIST.wrap(e0()))); - expectAdded(e0()); - } - -#ignore - @CollectionFeature.Require(absent = SUPPORTS_ADD) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddAllListCollection_unsupportedAllPresent() { - try { - getList().addAll((COLLECTION KEY_GENERIC_TYPE)ARRAY_LIST.wrap(e0())); - fail("addAll(allPresent) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) -#endignore - public void testAddAllListCollection_withDuplicates() { - COLLECTION KEY_GENERIC_TYPE elementsToAdd = ARRAY_LIST.wrap(e0(), e1(), e0(), e1()); - assertTrue("addAll(hasDuplicates) should return true", getList().addAll(elementsToAdd)); - expectAdded(e0(), e1(), e0(), e1()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddAllList_supportedAllPresent() { - assertTrue("addAll(allPresent) should return true", getList().addAll(ARRAY_LIST.wrap(e0()))); - expectAdded(e0()); - } - -#ignore - @CollectionFeature.Require(absent = SUPPORTS_ADD) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddAllList_unsupportedAllPresent() { - try { - getList().addAll(ARRAY_LIST.wrap(e0())); - fail("addAll(allPresent) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) -#endignore - public void testAddAllList_withDuplicates() { - LIST KEY_GENERIC_TYPE elementsToAdd = ARRAY_LIST.wrap(e0(), e1(), e0(), e1()); - assertTrue("addAll(hasDuplicates) should return true", getList().addAll(elementsToAdd)); - expectAdded(e0(), e1(), e0(), e1()); - } -} +package speiger.src.testers.PACKAGE.tests.list; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.collections.COLLECTION; +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; +import speiger.src.testers.PACKAGE.utils.MINIMAL_COLLECTION; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListAddAllTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddAll_supportedAllPresent() { + assertTrue("addAll(allPresent) should return true", getList().addAll(MINIMAL_COLLECTION.of(e0()))); + expectAdded(e0()); + } + +#ignore + @CollectionFeature.Require(absent = SUPPORTS_ADD) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddAll_unsupportedAllPresent() { + try { + getList().addAll(MINIMAL_COLLECTION.of(e0())); + fail("addAll(allPresent) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) +#endignore + public void testAddAll_withDuplicates() { + MINIMAL_COLLECTION KEY_GENERIC_TYPE elementsToAdd = MINIMAL_COLLECTION.of(e0(), e1(), e0(), e1()); + assertTrue("addAll(hasDuplicates) should return true", getList().addAll(elementsToAdd)); + expectAdded(e0(), e1(), e0(), e1()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddAllListCollection_supportedAllPresent() { + assertTrue("addAll(allPresent) should return true", getList().addAll((COLLECTION KEY_GENERIC_TYPE)ARRAY_LIST.wrap(e0()))); + expectAdded(e0()); + } + +#ignore + @CollectionFeature.Require(absent = SUPPORTS_ADD) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddAllListCollection_unsupportedAllPresent() { + try { + getList().addAll((COLLECTION KEY_GENERIC_TYPE)ARRAY_LIST.wrap(e0())); + fail("addAll(allPresent) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) +#endignore + public void testAddAllListCollection_withDuplicates() { + COLLECTION KEY_GENERIC_TYPE elementsToAdd = ARRAY_LIST.wrap(e0(), e1(), e0(), e1()); + assertTrue("addAll(hasDuplicates) should return true", getList().addAll(elementsToAdd)); + expectAdded(e0(), e1(), e0(), e1()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddAllList_supportedAllPresent() { + assertTrue("addAll(allPresent) should return true", getList().addAll(ARRAY_LIST.wrap(e0()))); + expectAdded(e0()); + } + +#ignore + @CollectionFeature.Require(absent = SUPPORTS_ADD) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddAllList_unsupportedAllPresent() { + try { + getList().addAll(ARRAY_LIST.wrap(e0())); + fail("addAll(allPresent) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) +#endignore + public void testAddAllList_withDuplicates() { + LIST KEY_GENERIC_TYPE elementsToAdd = ARRAY_LIST.wrap(e0(), e1(), e0(), e1()); + assertTrue("addAll(hasDuplicates) should return true", getList().addAll(elementsToAdd)); + expectAdded(e0(), e1(), e0(), e1()); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAddAtIndexTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAddAtIndexTester.template index 1076151..ffd29f3 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAddAtIndexTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAddAtIndexTester.template @@ -1,112 +1,112 @@ -package speiger.src.testers.PACKAGE.tests.list; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX; -#endignore - -import java.util.ConcurrentModificationException; - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.ListFeature; - -import speiger.src.collections.PACKAGE.collections.ITERATOR; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListAddAtIndexTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) - public void testAddAtIndex_supportedPresent() { - getList().add(0, e0()); - expectAddedIndex(0, e0()); - } - - @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) - public void testAddAtIndex_unsupportedPresent() { - try { - getList().add(0, e0()); - fail("add(n, present) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } - - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) - public void testAddAtIndex_supportedNotPresent() { - getList().add(0, e3()); - expectAddedIndex(0, e3()); - } - - @CollectionFeature.Require(FAILS_FAST_ON_CONCURRENT_MODIFICATION) - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) -#endignore - public void testAddAtIndexConcurrentWithIteration() { - try { - ITERATOR KEY_GENERIC_TYPE iterator = collection.iterator(); - getList().add(0, e3()); - iterator.NEXT(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#ignore - @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) - public void testAddAtIndex_unsupportedNotPresent() { - try { - getList().add(0, e3()); - fail("add(n, notPresent) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - expectMissing(e3()); - } - - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) - @CollectionSize.Require(absent = { ZERO, ONE }) - public void testAddAtIndex_middle() { - getList().add(getNumElements() / 2, e3()); - expectAddedIndex(getNumElements() / 2, e3()); - } - - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) - public void testAddAtIndex_end() { - getList().add(getNumElements(), e3()); - expectAddedIndex(getNumElements(), e3()); - } - - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) - public void testAddAtIndex_negative() { - try { - getList().add(-1, e3()); - fail("add(-1, e) should throw"); - } catch (IndexOutOfBoundsException expected) { - } - expectUnchanged(); - expectMissing(e3()); - } - - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) - public void testAddAtIndex_tooLarge() { - try { - getList().add(getNumElements() + 1, e3()); - fail("add(size + 1, e) should throw"); - } catch (IndexOutOfBoundsException expected) { - } - expectUnchanged(); - expectMissing(e3()); - } -#endignore -} +package speiger.src.testers.PACKAGE.tests.list; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX; +#endignore + +import java.util.ConcurrentModificationException; + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.ListFeature; + +import speiger.src.collections.PACKAGE.collections.ITERATOR; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListAddAtIndexTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) + public void testAddAtIndex_supportedPresent() { + getList().add(0, e0()); + expectAddedIndex(0, e0()); + } + + @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) + public void testAddAtIndex_unsupportedPresent() { + try { + getList().add(0, e0()); + fail("add(n, present) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } + + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) + public void testAddAtIndex_supportedNotPresent() { + getList().add(0, e3()); + expectAddedIndex(0, e3()); + } + + @CollectionFeature.Require(FAILS_FAST_ON_CONCURRENT_MODIFICATION) + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) +#endignore + public void testAddAtIndexConcurrentWithIteration() { + try { + ITERATOR KEY_GENERIC_TYPE iterator = collection.iterator(); + getList().add(0, e3()); + iterator.NEXT(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#ignore + @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) + public void testAddAtIndex_unsupportedNotPresent() { + try { + getList().add(0, e3()); + fail("add(n, notPresent) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + expectMissing(e3()); + } + + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) + @CollectionSize.Require(absent = { ZERO, ONE }) + public void testAddAtIndex_middle() { + getList().add(getNumElements() / 2, e3()); + expectAddedIndex(getNumElements() / 2, e3()); + } + + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) + public void testAddAtIndex_end() { + getList().add(getNumElements(), e3()); + expectAddedIndex(getNumElements(), e3()); + } + + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) + public void testAddAtIndex_negative() { + try { + getList().add(-1, e3()); + fail("add(-1, e) should throw"); + } catch (IndexOutOfBoundsException expected) { + } + expectUnchanged(); + expectMissing(e3()); + } + + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) + public void testAddAtIndex_tooLarge() { + try { + getList().add(getNumElements() + 1, e3()); + fail("add(size + 1, e) should throw"); + } catch (IndexOutOfBoundsException expected) { + } + expectUnchanged(); + expectMissing(e3()); + } +#endignore +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAddTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAddTester.template index 8b45ca8..d9c4d85 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAddTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListAddTester.template @@ -1,37 +1,37 @@ -package speiger.src.testers.PACKAGE.tests.list; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListAddTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) - @CollectionSize.Require(absent = ZERO) - public void testAdd_supportedPresent() { - assertTrue("add(present) should return true", getList().add(e0())); - expectAdded(e0()); - } - - @CollectionFeature.Require(absent = SUPPORTS_ADD) - @CollectionSize.Require(absent = ZERO) - public void testAdd_unsupportedPresent() { - try { - getList().add(e0()); - fail("add(present) should throw"); - } catch (UnsupportedOperationException expected) { - } - } -#endignore +package speiger.src.testers.PACKAGE.tests.list; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListAddTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) + @CollectionSize.Require(absent = ZERO) + public void testAdd_supportedPresent() { + assertTrue("add(present) should return true", getList().add(e0())); + expectAdded(e0()); + } + + @CollectionFeature.Require(absent = SUPPORTS_ADD) + @CollectionSize.Require(absent = ZERO) + public void testAdd_unsupportedPresent() { + try { + getList().add(e0()); + fail("add(present) should throw"); + } catch (UnsupportedOperationException expected) { + } + } +#endignore } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListCreationTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListCreationTester.template index 4221000..2350d99 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListCreationTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListCreationTester.template @@ -1,30 +1,30 @@ -package speiger.src.testers.PACKAGE.tests.list; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.REJECTS_DUPLICATES_AT_CREATION; -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListCreationTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(absent = REJECTS_DUPLICATES_AT_CREATION) - @CollectionSize.Require(absent = { ZERO, ONE }) -#endignore - public void testCreateWithDuplicates() { - KEY_TYPE[] array = createSamplesArray(); - array[1] = e0(); - collection = primitiveGenerator.create(array); - expectContents(array); - } -} +package speiger.src.testers.PACKAGE.tests.list; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.REJECTS_DUPLICATES_AT_CREATION; +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListCreationTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(absent = REJECTS_DUPLICATES_AT_CREATION) + @CollectionSize.Require(absent = { ZERO, ONE }) +#endignore + public void testCreateWithDuplicates() { + KEY_TYPE[] array = createSamplesArray(); + array[1] = e0(); + collection = primitiveGenerator.create(array); + expectContents(array); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListExtractElementsTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListExtractElementsTester.template index 9029ef0..c8bceaf 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListExtractElementsTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListExtractElementsTester.template @@ -1,86 +1,86 @@ -package speiger.src.testers.PACKAGE.tests.list; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import org.junit.Ignore; - -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListExtractElementsTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = {ZERO}) -#endignore - public void testRemoveElements() { -#if TYPE_OBJECT - assertArrayEquals("The Extracted Elements should be present", getSampleElements(1).TO_ARRAY(), getList().extractElements(0, 1, Object.class)); -#else - assertArrayEquals("The Extracted Elements should be present", getSampleElements(1).TO_ARRAY(), getList().extractElements(0, 1)); -#endif - expectMissing(e0()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = {ZERO}) -#endignore - public void testRemove_FromToLow() { - try { -#if TYPE_OBJECT - getList().extractElements(-1, 1, Object.class); -#else - getList().extractElements(-1, 1); -#endif - fail("extractElements(toLow, high) should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - } - expectUnchanged(); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = {ZERO}) -#endignore - public void testRemove_toToHigh() { - try { -#if TYPE_OBJECT - getList().extractElements(0, getNumElements()+1, Object.class); -#else - getList().extractElements(0, getNumElements()+1); -#endif - fail("extractElements(low, toHigh) should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - } - expectUnchanged(); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = {ZERO}) -#endignore - public void testRemove_mixedUp() { - try { -#if TYPE_OBJECT - getList().extractElements(1, 0, Object.class); -#else - getList().extractElements(1, 0); -#endif - } catch (IndexOutOfBoundsException e) { - } - expectUnchanged(); - } - - private static void assertArrayEquals(String message, KEY_OBJECT_TYPE[] expected, KEY_OBJECT_TYPE[] actual) { - assertEquals(message, ARRAY_LIST.wrap(expected), ARRAY_LIST.wrap(actual)); - } +package speiger.src.testers.PACKAGE.tests.list; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import org.junit.Ignore; + +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListExtractElementsTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = {ZERO}) +#endignore + public void testRemoveElements() { +#if TYPE_OBJECT + assertArrayEquals("The Extracted Elements should be present", getSampleElements(1).TO_ARRAY(), getList().extractElements(0, 1, Object.class)); +#else + assertArrayEquals("The Extracted Elements should be present", getSampleElements(1).TO_ARRAY(), getList().extractElements(0, 1)); +#endif + expectMissing(e0()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = {ZERO}) +#endignore + public void testRemove_FromToLow() { + try { +#if TYPE_OBJECT + getList().extractElements(-1, 1, Object.class); +#else + getList().extractElements(-1, 1); +#endif + fail("extractElements(toLow, high) should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + } + expectUnchanged(); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = {ZERO}) +#endignore + public void testRemove_toToHigh() { + try { +#if TYPE_OBJECT + getList().extractElements(0, getNumElements()+1, Object.class); +#else + getList().extractElements(0, getNumElements()+1); +#endif + fail("extractElements(low, toHigh) should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + } + expectUnchanged(); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = {ZERO}) +#endignore + public void testRemove_mixedUp() { + try { +#if TYPE_OBJECT + getList().extractElements(1, 0, Object.class); +#else + getList().extractElements(1, 0); +#endif + } catch (IndexOutOfBoundsException e) { + } + expectUnchanged(); + } + + private static void assertArrayEquals(String message, KEY_OBJECT_TYPE[] expected, KEY_OBJECT_TYPE[] actual) { + assertEquals(message, ARRAY_LIST.wrap(expected), ARRAY_LIST.wrap(actual)); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListFillBufferTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListFillBufferTester.template index 34bc94c..edb567b 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListFillBufferTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListFillBufferTester.template @@ -1,23 +1,23 @@ -package speiger.src.testers.PACKAGE.tests.list; - -import org.junit.Ignore; - -import java.nio.JAVA_BUFFER; - -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListFillBufferTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ - public void testFillBuffer() { - JAVA_BUFFER buffer = JAVA_BUFFER.allocate(getNumElements()); - getList().fillBuffer(buffer); - assertArrayEquals("Fill Buffer elements should equal", getSampleElements().TO_ARRAY(), buffer.array()); - } - - private static void assertArrayEquals(String message, KEY_TYPE[] expected, KEY_TYPE[] actual) { - assertEquals(message, ARRAY_LIST.wrap(expected), ARRAY_LIST.wrap(actual)); - } -} +package speiger.src.testers.PACKAGE.tests.list; + +import org.junit.Ignore; + +import java.nio.JAVA_BUFFER; + +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListFillBufferTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ + public void testFillBuffer() { + JAVA_BUFFER buffer = JAVA_BUFFER.allocate(getNumElements()); + getList().fillBuffer(buffer); + assertArrayEquals("Fill Buffer elements should equal", getSampleElements().TO_ARRAY(), buffer.array()); + } + + private static void assertArrayEquals(String message, KEY_TYPE[] expected, KEY_TYPE[] actual) { + assertEquals(message, ARRAY_LIST.wrap(expected), ARRAY_LIST.wrap(actual)); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListGetElementsTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListGetElementsTester.template index ace29a1..61a78df 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListGetElementsTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListGetElementsTester.template @@ -1,90 +1,90 @@ -package speiger.src.testers.PACKAGE.tests.list; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListGetElementsTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testGetElements_valid() { - KEY_OBJECT_TYPE[] samples = getSampleElements(2).TO_ARRAY(); - assertArrayEquals("getElements(from, result) should match", samples, getList().getElements(0, NEW_KEY_ARRAY(2))); - } - -#ignore - @CollectionSize.Require(absent = ZERO) -#endignore - public void testGetElements_validSmallerArray() { - KEY_OBJECT_TYPE[] samples = getSampleElements(2).TO_ARRAY(); - samples[1] = EMPTY_KEY_VALUE; - assertArrayEquals("getElements(from, result) should match", samples, getList().getElements(0, NEW_KEY_ARRAY(2), 0, 1)); - } - - public void testGetElements_outputToLarge() { - try { - getList().getElements(0, NEW_KEY_ARRAY(10)); - fail("getElements(from, output) should have thrown a IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - } - } - - public void testGetElements_offsetToSmall() { - try { - getList().getElements(0, NEW_KEY_ARRAY(2), -1, 2); - fail("getElements(from, output, offset, length) should have thrown a IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - //success - } - } - - public void testGetElements_offsetToLarge() { - try { - getList().getElements(0, NEW_KEY_ARRAY(2), 10, 2); - fail("getElements(from, output, offset, length) should have thrown a IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - //success - } - } - - public void testGetElements_lengthExceedingArray() { - try { - getList().getElements(0, NEW_KEY_ARRAY(2), 0, 10); - fail("getElements(from, output, offset, length) should have thrown a IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - //success - } - } - - public void testGet_negative() { - try { - getList().getElements(-1, NEW_KEY_ARRAY(2)); - fail("getElements(-1) should throw"); - } catch (IndexOutOfBoundsException expected) { - } - } - - public void testGet_tooLarge() { - try { - getList().getElements(getNumElements(), NEW_KEY_ARRAY(2)); - fail("get(size) should throw"); - } catch (IndexOutOfBoundsException expected) { - } - } - - private static void assertArrayEquals(String message, KEY_OBJECT_TYPE[] expected, KEY_OBJECT_TYPE[] actual) { - assertEquals(message, ARRAY_LIST.wrap(expected), ARRAY_LIST.wrap(actual)); - } -} +package speiger.src.testers.PACKAGE.tests.list; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListGetElementsTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testGetElements_valid() { + KEY_OBJECT_TYPE[] samples = getSampleElements(2).TO_ARRAY(); + assertArrayEquals("getElements(from, result) should match", samples, getList().getElements(0, NEW_KEY_ARRAY(2))); + } + +#ignore + @CollectionSize.Require(absent = ZERO) +#endignore + public void testGetElements_validSmallerArray() { + KEY_OBJECT_TYPE[] samples = getSampleElements(2).TO_ARRAY(); + samples[1] = EMPTY_KEY_VALUE; + assertArrayEquals("getElements(from, result) should match", samples, getList().getElements(0, NEW_KEY_ARRAY(2), 0, 1)); + } + + public void testGetElements_outputToLarge() { + try { + getList().getElements(0, NEW_KEY_ARRAY(10)); + fail("getElements(from, output) should have thrown a IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + } + } + + public void testGetElements_offsetToSmall() { + try { + getList().getElements(0, NEW_KEY_ARRAY(2), -1, 2); + fail("getElements(from, output, offset, length) should have thrown a IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + //success + } + } + + public void testGetElements_offsetToLarge() { + try { + getList().getElements(0, NEW_KEY_ARRAY(2), 10, 2); + fail("getElements(from, output, offset, length) should have thrown a IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + //success + } + } + + public void testGetElements_lengthExceedingArray() { + try { + getList().getElements(0, NEW_KEY_ARRAY(2), 0, 10); + fail("getElements(from, output, offset, length) should have thrown a IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + //success + } + } + + public void testGet_negative() { + try { + getList().getElements(-1, NEW_KEY_ARRAY(2)); + fail("getElements(-1) should throw"); + } catch (IndexOutOfBoundsException expected) { + } + } + + public void testGet_tooLarge() { + try { + getList().getElements(getNumElements(), NEW_KEY_ARRAY(2)); + fail("get(size) should throw"); + } catch (IndexOutOfBoundsException expected) { + } + } + + private static void assertArrayEquals(String message, KEY_OBJECT_TYPE[] expected, KEY_OBJECT_TYPE[] actual) { + assertEquals(message, ARRAY_LIST.wrap(expected), ARRAY_LIST.wrap(actual)); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListGetTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListGetTester.template index 764ff5b..eaa2ce9 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListGetTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListGetTester.template @@ -1,35 +1,35 @@ -package speiger.src.testers.PACKAGE.tests.list; - -import org.junit.Ignore; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListGetTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ - public void testGet_valid() { - expectContents(createOrderedArray()); - } - - public void testGet_validList() { - expectContents(getOrderedElements()); - } - - public void testGet_negative() { - try { - getList().GET_KEY(-1); - fail("get(-1) should throw"); - } catch (IndexOutOfBoundsException expected) { - } - } - - public void testGet_tooLarge() { - try { - getList().GET_KEY(getNumElements()); - fail("get(size) should throw"); - } catch (IndexOutOfBoundsException expected) { - } - } - -} +package speiger.src.testers.PACKAGE.tests.list; + +import org.junit.Ignore; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListGetTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ + public void testGet_valid() { + expectContents(createOrderedArray()); + } + + public void testGet_validList() { + expectContents(getOrderedElements()); + } + + public void testGet_negative() { + try { + getList().GET_KEY(-1); + fail("get(-1) should throw"); + } catch (IndexOutOfBoundsException expected) { + } + } + + public void testGet_tooLarge() { + try { + getList().GET_KEY(getNumElements()); + fail("get(size) should throw"); + } catch (IndexOutOfBoundsException expected) { + } + } + +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListIndexOfTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListIndexOfTester.template index 83d3db2..a4343e0 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListIndexOfTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListIndexOfTester.template @@ -1,40 +1,40 @@ -package speiger.src.testers.PACKAGE.tests.list; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.REJECTS_DUPLICATES_AT_CREATION; -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_INDEX_OF_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListIndexOfTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_INDEX_OF_TESTER KEY_GENERIC_TYPE -{ - @Override - protected int find(KEY_TYPE o) { - return getList().indexOf(o); - } - - @Override - protected String getMethodName() { - return "indexOf"; - } - -#ignore - @CollectionFeature.Require(absent = REJECTS_DUPLICATES_AT_CREATION) - @CollectionSize.Require(absent = { ZERO, ONE }) -#endignore - public void testIndexOf_duplicate() { - KEY_TYPE[] array = createSamplesArray(); - array[getNumElements() / 2] = e0(); - collection = primitiveGenerator.create(array); - assertEquals("indexOf(duplicate) should return index of first occurrence", 0, getList().indexOf(e0())); - } -} +package speiger.src.testers.PACKAGE.tests.list; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.REJECTS_DUPLICATES_AT_CREATION; +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_INDEX_OF_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListIndexOfTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_INDEX_OF_TESTER KEY_GENERIC_TYPE +{ + @Override + protected int find(KEY_TYPE o) { + return getList().indexOf(o); + } + + @Override + protected String getMethodName() { + return "indexOf"; + } + +#ignore + @CollectionFeature.Require(absent = REJECTS_DUPLICATES_AT_CREATION) + @CollectionSize.Require(absent = { ZERO, ONE }) +#endignore + public void testIndexOf_duplicate() { + KEY_TYPE[] array = createSamplesArray(); + array[getNumElements() / 2] = e0(); + collection = primitiveGenerator.create(array); + assertEquals("indexOf(duplicate) should return index of first occurrence", 0, getList().indexOf(e0())); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListLastIndexOfTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListLastIndexOfTester.template index 53a2a03..ed96522 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListLastIndexOfTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListLastIndexOfTester.template @@ -1,40 +1,40 @@ -package speiger.src.testers.PACKAGE.tests.list; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.REJECTS_DUPLICATES_AT_CREATION; -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_INDEX_OF_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListLastIndexOfTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_INDEX_OF_TESTER KEY_GENERIC_TYPE -{ - @Override - protected int find(KEY_TYPE o) { - return getList().lastIndexOf(o); - } - - @Override - protected String getMethodName() { - return "lastIndexOf"; - } - -#ignore - @CollectionFeature.Require(absent = REJECTS_DUPLICATES_AT_CREATION) - @CollectionSize.Require(absent = { ZERO, ONE }) -#endignore - public void testLastIndexOf_duplicate() { - KEY_TYPE[] array = createSamplesArray(); - array[getNumElements() / 2] = e0(); - collection = primitiveGenerator.create(array); - assertEquals("lastIndexOf(duplicate) should return index of last occurrence", getNumElements() / 2, getList().lastIndexOf(e0())); - } +package speiger.src.testers.PACKAGE.tests.list; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.REJECTS_DUPLICATES_AT_CREATION; +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_INDEX_OF_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListLastIndexOfTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_INDEX_OF_TESTER KEY_GENERIC_TYPE +{ + @Override + protected int find(KEY_TYPE o) { + return getList().lastIndexOf(o); + } + + @Override + protected String getMethodName() { + return "lastIndexOf"; + } + +#ignore + @CollectionFeature.Require(absent = REJECTS_DUPLICATES_AT_CREATION) + @CollectionSize.Require(absent = { ZERO, ONE }) +#endignore + public void testLastIndexOf_duplicate() { + KEY_TYPE[] array = createSamplesArray(); + array[getNumElements() / 2] = e0(); + collection = primitiveGenerator.create(array); + assertEquals("lastIndexOf(duplicate) should return index of last occurrence", getNumElements() / 2, getList().lastIndexOf(e0())); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListListIteratorTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListListIteratorTester.template index f84fe29..9253658 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListListIteratorTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListListIteratorTester.template @@ -1,73 +1,73 @@ -package speiger.src.testers.PACKAGE.tests.list; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; -import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; -#endignore - -import java.util.Set; - -import com.google.common.collect.testing.IteratorFeature; - -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; -import speiger.src.collections.PACKAGE.utils.LISTS; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; -import speiger.src.testers.PACKAGE.utils.HELPERS; -import speiger.src.testers.PACKAGE.utils.LIST_ITERATOR_TESTER; - -import speiger.src.testers.utils.SpecialFeature; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListListIteratorTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ -#ignore - @SpecialFeature.Require(absent = SpecialFeature.ITERATOR_MODIFIABLE) - public void testListIterator_unmodifiable() { - runListIteratorTest(UNMODIFIABLE); - } - - @SpecialFeature.Require(SpecialFeature.ITERATOR_MODIFIABLE) - public void testListIterator_fullyModifiable() { - runListIteratorTest(MODIFIABLE); - } -#endignore - - private void runListIteratorTest(Set features) { - new LIST_ITERATOR_TESTER KEY_GENERIC_TYPE(4, LISTS.singleton(e4()), features, HELPERS.copyToList(getOrderedElements()), 0) { - @Override - protected LIST_ITERATOR KEY_GENERIC_TYPE newTargetIterator() { - resetCollection(); - return getList().listIterator(); - } - - @Override - protected void verify(LIST KEY_GENERIC_TYPE elements) { - expectContents(elements); - } - }.test(); - } - - public void testListIterator_tooLow() { - try { - getList().listIterator(-1); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - } - - public void testListIterator_tooHigh() { - try { - getList().listIterator(getNumElements() + 1); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - } - - public void testListIterator_atSize() { - getList().listIterator(getNumElements()); - } -} +package speiger.src.testers.PACKAGE.tests.list; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; +import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; +#endignore + +import java.util.Set; + +import com.google.common.collect.testing.IteratorFeature; + +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; +import speiger.src.collections.PACKAGE.utils.LISTS; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; +import speiger.src.testers.PACKAGE.utils.HELPERS; +import speiger.src.testers.PACKAGE.utils.LIST_ITERATOR_TESTER; + +import speiger.src.testers.utils.SpecialFeature; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListListIteratorTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ +#ignore + @SpecialFeature.Require(absent = SpecialFeature.ITERATOR_MODIFIABLE) + public void testListIterator_unmodifiable() { + runListIteratorTest(UNMODIFIABLE); + } + + @SpecialFeature.Require(SpecialFeature.ITERATOR_MODIFIABLE) + public void testListIterator_fullyModifiable() { + runListIteratorTest(MODIFIABLE); + } +#endignore + + private void runListIteratorTest(Set features) { + new LIST_ITERATOR_TESTER KEY_GENERIC_TYPE(4, LISTS.singleton(e4()), features, HELPERS.copyToList(getOrderedElements()), 0) { + @Override + protected LIST_ITERATOR KEY_GENERIC_TYPE newTargetIterator() { + resetCollection(); + return getList().listIterator(); + } + + @Override + protected void verify(LIST KEY_GENERIC_TYPE elements) { + expectContents(elements); + } + }.test(); + } + + public void testListIterator_tooLow() { + try { + getList().listIterator(-1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + } + + public void testListIterator_tooHigh() { + try { + getList().listIterator(getNumElements() + 1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + } + + public void testListIterator_atSize() { + getList().listIterator(getNumElements()); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListPresentTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListPresentTester.template index ca0edf7..6f1253a 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListPresentTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListPresentTester.template @@ -1,54 +1,54 @@ -package speiger.src.testers.PACKAGE.tests.list; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; -import static com.google.common.collect.testing.features.CollectionSize.ONE; -#endignore - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListPresentTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) - @CollectionSize.Require(ONE) - public void testIfAbsent() { - assertFalse("addIfPresent(absent) should return false", getList().addIfPresent(e1())); - expectUnchanged(); - } - - @CollectionFeature.Require(SUPPORTS_ADD) - @CollectionSize.Require(ONE) - public void testIfPresent() { - assertTrue("addIfPresent(present) should return true", getList().addIfPresent(e0())); - expectAdded(e0()); - } - - @CollectionFeature.Require(absent = SUPPORTS_ADD) - @CollectionSize.Require(ONE) - public void test_IfAbsentUnsupported() { - try { - assertFalse("addIfPresent(absent) should return false", getList().addIfPresent(e1())); - } catch (UnsupportedOperationException e) { - //Success - } - } - - @CollectionFeature.Require(absent = SUPPORTS_ADD) - @CollectionSize.Require(ONE) - public void test_IfPresentUnsupported() { - try { - assertFalse("addIfPresent(present) should return false", getList().addIfPresent(e0())); - } catch (UnsupportedOperationException e) { - //Success - } - } -#endignore -} +package speiger.src.testers.PACKAGE.tests.list; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; +import static com.google.common.collect.testing.features.CollectionSize.ONE; +#endignore + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListPresentTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) + @CollectionSize.Require(ONE) + public void testIfAbsent() { + assertFalse("addIfPresent(absent) should return false", getList().addIfPresent(e1())); + expectUnchanged(); + } + + @CollectionFeature.Require(SUPPORTS_ADD) + @CollectionSize.Require(ONE) + public void testIfPresent() { + assertTrue("addIfPresent(present) should return true", getList().addIfPresent(e0())); + expectAdded(e0()); + } + + @CollectionFeature.Require(absent = SUPPORTS_ADD) + @CollectionSize.Require(ONE) + public void test_IfAbsentUnsupported() { + try { + assertFalse("addIfPresent(absent) should return false", getList().addIfPresent(e1())); + } catch (UnsupportedOperationException e) { + //Success + } + } + + @CollectionFeature.Require(absent = SUPPORTS_ADD) + @CollectionSize.Require(ONE) + public void test_IfPresentUnsupported() { + try { + assertFalse("addIfPresent(present) should return false", getList().addIfPresent(e0())); + } catch (UnsupportedOperationException e) { + //Success + } + } +#endignore +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListRemoveAllTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListRemoveAllTester.template index 2d7c3b8..1f7e97d 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListRemoveAllTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListRemoveAllTester.template @@ -1,32 +1,32 @@ -package speiger.src.testers.PACKAGE.tests.list; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; -import speiger.src.testers.PACKAGE.utils.MINIMAL_COLLECTION; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListRemoveAllTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = { ZERO, ONE }) -#endignore - public void testRemoveAll_duplicate() { - ArrayWithDuplicate KEY_GENERIC_TYPE arrayAndDuplicate = createArrayWithDuplicateElement(); - collection = primitiveGenerator.create(arrayAndDuplicate.elements); - KEY_TYPE duplicate = arrayAndDuplicate.duplicate; - assertTrue("removeAll(intersectingCollection) should return true", getList().removeAll(MINIMAL_COLLECTION.of(duplicate))); - assertFalse("after removeAll(e), a collection should not contain e even if it initially contained e more than once.", getList().contains(duplicate)); - } -} +package speiger.src.testers.PACKAGE.tests.list; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; +import speiger.src.testers.PACKAGE.utils.MINIMAL_COLLECTION; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListRemoveAllTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = { ZERO, ONE }) +#endignore + public void testRemoveAll_duplicate() { + ArrayWithDuplicate KEY_GENERIC_TYPE arrayAndDuplicate = createArrayWithDuplicateElement(); + collection = primitiveGenerator.create(arrayAndDuplicate.elements); + KEY_TYPE duplicate = arrayAndDuplicate.duplicate; + assertTrue("removeAll(intersectingCollection) should return true", getList().removeAll(MINIMAL_COLLECTION.of(duplicate))); + assertFalse("after removeAll(e), a collection should not contain e even if it initially contained e more than once.", getList().contains(duplicate)); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListRemoveAtIndexTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListRemoveAtIndexTester.template index e3bd423..40053cc 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListRemoveAtIndexTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListRemoveAtIndexTester.template @@ -1,106 +1,106 @@ -package speiger.src.testers.PACKAGE.tests.list; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_REMOVE_WITH_INDEX; -#endignore - -import java.util.ConcurrentModificationException; - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.ListFeature; - -import speiger.src.collections.PACKAGE.collections.ITERATOR; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; -import speiger.src.testers.PACKAGE.utils.HELPERS; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListRemoveAtIndexTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ -#ignore - @ListFeature.Require(absent = SUPPORTS_REMOVE_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRemoveAtIndex_unsupported() { - try { - getList().REMOVE(0); - fail("remove(i) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } - -#ignore - @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) -#endignore - public void testRemoveAtIndex_negative() { - try { - getList().REMOVE(-1); - fail("remove(-1) should throw"); - } catch (IndexOutOfBoundsException expected) { - } - expectUnchanged(); - } - -#ignore - @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) -#endignore - public void testRemoveAtIndex_tooLarge() { - try { - getList().REMOVE(getNumElements()); - fail("remove(size) should throw"); - } catch (IndexOutOfBoundsException expected) { - } - expectUnchanged(); - } - -#ignore - @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) - public void testRemoveAtIndex_first() { - runRemoveTest(0); - } - - @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) - @CollectionSize.Require(absent = { ZERO, ONE }) - public void testRemoveAtIndex_middle() { - runRemoveTest(getNumElements() / 2); - } - - @CollectionFeature.Require(FAILS_FAST_ON_CONCURRENT_MODIFICATION) - @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRemoveAtIndexConcurrentWithIteration() { - try { - ITERATOR KEY_GENERIC_TYPE iterator = collection.iterator(); - getList().REMOVE(getNumElements() / 2); - iterator.NEXT(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#ignore - @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRemoveAtIndex_last() { - runRemoveTest(getNumElements() - 1); - } - - private void runRemoveTest(int index) { - assertEquals(String.format("remove(%d) should return the element at index %d", index, index), getList().GET_KEY(index), getList().REMOVE(index)); - LIST KEY_GENERIC_TYPE expected = HELPERS.copyToList(createSamplesArray()); - expected.REMOVE(index); - expectContents(expected); - } -} +package speiger.src.testers.PACKAGE.tests.list; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_REMOVE_WITH_INDEX; +#endignore + +import java.util.ConcurrentModificationException; + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.ListFeature; + +import speiger.src.collections.PACKAGE.collections.ITERATOR; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; +import speiger.src.testers.PACKAGE.utils.HELPERS; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListRemoveAtIndexTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ +#ignore + @ListFeature.Require(absent = SUPPORTS_REMOVE_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRemoveAtIndex_unsupported() { + try { + getList().REMOVE(0); + fail("remove(i) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } + +#ignore + @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) +#endignore + public void testRemoveAtIndex_negative() { + try { + getList().REMOVE(-1); + fail("remove(-1) should throw"); + } catch (IndexOutOfBoundsException expected) { + } + expectUnchanged(); + } + +#ignore + @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) +#endignore + public void testRemoveAtIndex_tooLarge() { + try { + getList().REMOVE(getNumElements()); + fail("remove(size) should throw"); + } catch (IndexOutOfBoundsException expected) { + } + expectUnchanged(); + } + +#ignore + @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) + public void testRemoveAtIndex_first() { + runRemoveTest(0); + } + + @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) + @CollectionSize.Require(absent = { ZERO, ONE }) + public void testRemoveAtIndex_middle() { + runRemoveTest(getNumElements() / 2); + } + + @CollectionFeature.Require(FAILS_FAST_ON_CONCURRENT_MODIFICATION) + @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRemoveAtIndexConcurrentWithIteration() { + try { + ITERATOR KEY_GENERIC_TYPE iterator = collection.iterator(); + getList().REMOVE(getNumElements() / 2); + iterator.NEXT(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#ignore + @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRemoveAtIndex_last() { + runRemoveTest(getNumElements() - 1); + } + + private void runRemoveTest(int index) { + assertEquals(String.format("remove(%d) should return the element at index %d", index, index), getList().GET_KEY(index), getList().REMOVE(index)); + LIST KEY_GENERIC_TYPE expected = HELPERS.copyToList(createSamplesArray()); + expected.REMOVE(index); + expectContents(expected); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListRemoveElementsTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListRemoveElementsTester.template index 765879f..39108cb 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListRemoveElementsTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListRemoveElementsTester.template @@ -1,59 +1,59 @@ -package speiger.src.testers.PACKAGE.tests.list; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListRemoveElementsTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = {ZERO}) - public void testRemoveElements() { - getList().removeElements(0, 1); - expectMissing(e0()); - } - - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = {ZERO}) - public void testRemove_FromToLow() { - try { - getList().removeElements(-1, 1); - fail("removeElements(toLow, high) should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - } - expectUnchanged(); - } - - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = {ZERO}) - public void testRemove_toToHigh() { - try { - getList().removeElements(0, getNumElements()+1); - fail("removeElements(low, toHigh) should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - } - expectUnchanged(); - } - - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = {ZERO}) - public void testRemove_mixedUp() { - try { - getList().removeElements(1, 0); - } catch (IndexOutOfBoundsException e) { - } - expectUnchanged(); - } -#endignore +package speiger.src.testers.PACKAGE.tests.list; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListRemoveElementsTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = {ZERO}) + public void testRemoveElements() { + getList().removeElements(0, 1); + expectMissing(e0()); + } + + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = {ZERO}) + public void testRemove_FromToLow() { + try { + getList().removeElements(-1, 1); + fail("removeElements(toLow, high) should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + } + expectUnchanged(); + } + + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = {ZERO}) + public void testRemove_toToHigh() { + try { + getList().removeElements(0, getNumElements()+1); + fail("removeElements(low, toHigh) should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + } + expectUnchanged(); + } + + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = {ZERO}) + public void testRemove_mixedUp() { + try { + getList().removeElements(1, 0); + } catch (IndexOutOfBoundsException e) { + } + expectUnchanged(); + } +#endignore } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListRemoveTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListRemoveTester.template index 8a4afdb..6758018 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListRemoveTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListRemoveTester.template @@ -1,40 +1,40 @@ -package speiger.src.testers.PACKAGE.tests.list; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListRemoveTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = {ZERO, ONE}) -#endignore - public void testRemove_duplicate() { - ArrayWithDuplicate KEY_GENERIC_TYPE arrayAndDuplicate = createArrayWithDuplicateElement(); - collection = primitiveGenerator.create(arrayAndDuplicate.elements); - KEY_TYPE duplicate = arrayAndDuplicate.duplicate; - - int firstIndex = getList().indexOf(duplicate); - int initialSize = getList().size(); -#if TYPE_OBJECT - assertTrue("remove(present) should return true", getList().remove(duplicate)); -#else - assertTrue("remove(present) should return true", getList().REMOVE_KEY(duplicate)); -#endif - assertTrue("After remove(duplicate), a list should still contain the duplicate element", getList().contains(duplicate)); - assertFalse("remove(duplicate) should remove the first instance of the " + "duplicate element in the list", firstIndex == getList().indexOf(duplicate)); - assertEquals("remove(present) should decrease the size of a list by one.", initialSize - 1, getList().size()); - } -} +package speiger.src.testers.PACKAGE.tests.list; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListRemoveTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = {ZERO, ONE}) +#endignore + public void testRemove_duplicate() { + ArrayWithDuplicate KEY_GENERIC_TYPE arrayAndDuplicate = createArrayWithDuplicateElement(); + collection = primitiveGenerator.create(arrayAndDuplicate.elements); + KEY_TYPE duplicate = arrayAndDuplicate.duplicate; + + int firstIndex = getList().indexOf(duplicate); + int initialSize = getList().size(); +#if TYPE_OBJECT + assertTrue("remove(present) should return true", getList().remove(duplicate)); +#else + assertTrue("remove(present) should return true", getList().REMOVE_KEY(duplicate)); +#endif + assertTrue("After remove(duplicate), a list should still contain the duplicate element", getList().contains(duplicate)); + assertFalse("remove(duplicate) should remove the first instance of the " + "duplicate element in the list", firstIndex == getList().indexOf(duplicate)); + assertEquals("remove(present) should decrease the size of a list by one.", initialSize - 1, getList().size()); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListReplaceAllTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListReplaceAllTester.template index 6c56c70..9d575d1 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListReplaceAllTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListReplaceAllTester.template @@ -1,72 +1,72 @@ -package speiger.src.testers.PACKAGE.tests.list; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_SET; -#endignore - -import java.util.Arrays; -#if TYPE_OBJECT -import java.util.Objects; -#endif - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.ListFeature; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListReplaceAllTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ -#ignore - @ListFeature.Require(SUPPORTS_SET) -#endignore - public void testReplaceAll() { -#if TYPE_OBJECT - getList().replaceAll(e -> samples.e3()); -#else - getList().REPLACE(e -> samples.e3()); -#endif - KEY_TYPE[] array = NEW_KEY_ARRAY(getNumElements()); - Arrays.fill(array, samples.e3()); - expectContents(array); - } - -#ignore - @ListFeature.Require(SUPPORTS_SET) -#endignore - public void testReplaceAll_changesSome() { -#if TYPE_OBJECT - getList().replaceAll(e -> Objects.equals(e, samples.e0()) ? samples.e3() : e); -#else - getList().REPLACE(e -> e == samples.e0() ? samples.e3() : e); -#endif - KEY_TYPE[] expected = createSamplesArray(); - for (int i = 0; i < expected.length; i++) { - if (KEY_EQUALS(expected[i], samples.e0())) { - expected[i] = samples.e3(); - } - } - expectContents(expected); - } - -#ignore - @CollectionSize.Require(absent = ZERO) - @ListFeature.Require(absent = SUPPORTS_SET) -#endignore - public void testReplaceAll_unsupported() { - try { -#if TYPE_OBJECT - getList().replaceAll(e -> e); -#else - getList().REPLACE(e -> e); -#endif - fail("replaceAll() should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } -} +package speiger.src.testers.PACKAGE.tests.list; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_SET; +#endignore + +import java.util.Arrays; +#if TYPE_OBJECT +import java.util.Objects; +#endif + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.ListFeature; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListReplaceAllTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ +#ignore + @ListFeature.Require(SUPPORTS_SET) +#endignore + public void testReplaceAll() { +#if TYPE_OBJECT + getList().replaceAll(e -> samples.e3()); +#else + getList().REPLACE(e -> samples.e3()); +#endif + KEY_TYPE[] array = NEW_KEY_ARRAY(getNumElements()); + Arrays.fill(array, samples.e3()); + expectContents(array); + } + +#ignore + @ListFeature.Require(SUPPORTS_SET) +#endignore + public void testReplaceAll_changesSome() { +#if TYPE_OBJECT + getList().replaceAll(e -> Objects.equals(e, samples.e0()) ? samples.e3() : e); +#else + getList().REPLACE(e -> e == samples.e0() ? samples.e3() : e); +#endif + KEY_TYPE[] expected = createSamplesArray(); + for (int i = 0; i < expected.length; i++) { + if (KEY_EQUALS(expected[i], samples.e0())) { + expected[i] = samples.e3(); + } + } + expectContents(expected); + } + +#ignore + @CollectionSize.Require(absent = ZERO) + @ListFeature.Require(absent = SUPPORTS_SET) +#endignore + public void testReplaceAll_unsupported() { + try { +#if TYPE_OBJECT + getList().replaceAll(e -> e); +#else + getList().REPLACE(e -> e); +#endif + fail("replaceAll() should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListRetainAllTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListRetainAllTester.template index 9b209b7..24418b3 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListRetainAllTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListRetainAllTester.template @@ -1,59 +1,59 @@ -package speiger.src.testers.PACKAGE.tests.list; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; -import speiger.src.testers.PACKAGE.utils.HELPERS; -import speiger.src.testers.PACKAGE.utils.MINIMAL_COLLECTION; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListRetainAllTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = { ZERO, ONE }) -#endignore - public void testRetainAll_duplicatesKept() { - KEY_TYPE[] array = createSamplesArray(); - array[1] = e0(); - collection = primitiveGenerator.create(array); - assertFalse("containsDuplicates.retainAll(superset) should return false", collection.retainAll(MINIMAL_COLLECTION.of(createSamplesArray()))); - expectContents(array); - } - -#ignore - @SuppressWarnings("unchecked") - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testRetainAll_duplicatesRemoved() { - KEY_TYPE[] array = createSamplesArray(); - array[1] = e0(); - collection = primitiveGenerator.create(array); - assertTrue("containsDuplicates.retainAll(subset) should return true", collection.retainAll(MINIMAL_COLLECTION.of(e2()))); - expectContents(e2()); - } - -#ignore - @SuppressWarnings("unchecked") - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testRetainAll_countIgnored() { - resetContainer(primitiveGenerator.create(createArray(e0(), e2(), e1(), e0()))); - assertTrue(getList().retainAll(ARRAY_LIST.wrap(e0(), e1()))); - HELPERS.assertContentsInOrder(getList(), e0(), e1(), e0()); - } -} +package speiger.src.testers.PACKAGE.tests.list; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; +import speiger.src.testers.PACKAGE.utils.HELPERS; +import speiger.src.testers.PACKAGE.utils.MINIMAL_COLLECTION; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListRetainAllTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = { ZERO, ONE }) +#endignore + public void testRetainAll_duplicatesKept() { + KEY_TYPE[] array = createSamplesArray(); + array[1] = e0(); + collection = primitiveGenerator.create(array); + assertFalse("containsDuplicates.retainAll(superset) should return false", collection.retainAll(MINIMAL_COLLECTION.of(createSamplesArray()))); + expectContents(array); + } + +#ignore + @SuppressWarnings("unchecked") + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testRetainAll_duplicatesRemoved() { + KEY_TYPE[] array = createSamplesArray(); + array[1] = e0(); + collection = primitiveGenerator.create(array); + assertTrue("containsDuplicates.retainAll(subset) should return true", collection.retainAll(MINIMAL_COLLECTION.of(e2()))); + expectContents(e2()); + } + +#ignore + @SuppressWarnings("unchecked") + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testRetainAll_countIgnored() { + resetContainer(primitiveGenerator.create(createArray(e0(), e2(), e1(), e0()))); + assertTrue(getList().retainAll(ARRAY_LIST.wrap(e0(), e1()))); + HELPERS.assertContentsInOrder(getList(), e0(), e1(), e0()); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListSetTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListSetTester.template index 78b3e70..0206cef 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListSetTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListSetTester.template @@ -1,83 +1,83 @@ -package speiger.src.testers.PACKAGE.tests.list; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_SET; -#endignore - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.ListFeature; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListSetTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ -#ignore - @ListFeature.Require(SUPPORTS_SET) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testSet() { - doTestSet(e3()); - } - - private void doTestSet(KEY_TYPE newValue) { - int index = aValidIndex(); - KEY_TYPE initialValue = getList().GET_KEY(index); - assertEquals("set(i, x) should return the old element at position i.", initialValue, getList().set(index, newValue)); - assertEquals("After set(i, x), get(i) should return x", newValue, getList().GET_KEY(index)); - assertEquals("set() should not change the size of a list.", getNumElements(), getList().size()); - } - -#ignore - @ListFeature.Require(SUPPORTS_SET) - public void testSet_indexTooLow() { - try { - getList().set(-1, e3()); - fail("set(-1) should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException expected) { - } - expectUnchanged(); - } - - @ListFeature.Require(SUPPORTS_SET) - public void testSet_indexTooHigh() { - int index = getNumElements(); - try { - getList().set(index, e3()); - fail("set(size) should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException expected) { - } - expectUnchanged(); - } - - @CollectionSize.Require(absent = ZERO) - @ListFeature.Require(absent = SUPPORTS_SET) - public void testSet_unsupported() { - try { - getList().set(aValidIndex(), e3()); - fail("set() should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } - - @CollectionSize.Require(ZERO) - @ListFeature.Require(absent = SUPPORTS_SET) - public void testSet_unsupportedByEmptyList() { - try { - getList().set(0, e3()); - fail("set() should throw UnsupportedOperationException or IndexOutOfBoundsException"); - } catch (UnsupportedOperationException | IndexOutOfBoundsException tolerated) { - } - expectUnchanged(); - } -#endignore - - private int aValidIndex() { - return getList().size() / 2; - } -} +package speiger.src.testers.PACKAGE.tests.list; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_SET; +#endignore + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.ListFeature; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListSetTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ +#ignore + @ListFeature.Require(SUPPORTS_SET) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testSet() { + doTestSet(e3()); + } + + private void doTestSet(KEY_TYPE newValue) { + int index = aValidIndex(); + KEY_TYPE initialValue = getList().GET_KEY(index); + assertEquals("set(i, x) should return the old element at position i.", initialValue, getList().set(index, newValue)); + assertEquals("After set(i, x), get(i) should return x", newValue, getList().GET_KEY(index)); + assertEquals("set() should not change the size of a list.", getNumElements(), getList().size()); + } + +#ignore + @ListFeature.Require(SUPPORTS_SET) + public void testSet_indexTooLow() { + try { + getList().set(-1, e3()); + fail("set(-1) should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException expected) { + } + expectUnchanged(); + } + + @ListFeature.Require(SUPPORTS_SET) + public void testSet_indexTooHigh() { + int index = getNumElements(); + try { + getList().set(index, e3()); + fail("set(size) should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException expected) { + } + expectUnchanged(); + } + + @CollectionSize.Require(absent = ZERO) + @ListFeature.Require(absent = SUPPORTS_SET) + public void testSet_unsupported() { + try { + getList().set(aValidIndex(), e3()); + fail("set() should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } + + @CollectionSize.Require(ZERO) + @ListFeature.Require(absent = SUPPORTS_SET) + public void testSet_unsupportedByEmptyList() { + try { + getList().set(0, e3()); + fail("set() should throw UnsupportedOperationException or IndexOutOfBoundsException"); + } catch (UnsupportedOperationException | IndexOutOfBoundsException tolerated) { + } + expectUnchanged(); + } +#endignore + + private int aValidIndex() { + return getList().size() / 2; + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListSortTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListSortTester.template index 2122557..5074caf 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListSortTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListSortTester.template @@ -1,102 +1,102 @@ -package speiger.src.testers.PACKAGE.tests.list; - -#if TYPE_OBJECT -import java.util.Comparator; -#endif - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.ListFeature; - -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.utils.LISTS; -import speiger.src.collections.utils.SanityChecks; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListSortTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ -#ignore - @ListFeature.Require(ListFeature.SUPPORTS_SET) - @CollectionSize.Require(CollectionSize.SEVERAL) -#endignore - public void testStableSort() { - KEY_TYPE[] keys = collection.TO_ARRAY(NEW_KEY_ARRAY(collection.size())); - SanityChecks.getRandom().setSeed(212121212L); - LISTS.shuffle(getList()); - assertFalse(getList().equals(ARRAY_LIST.wrap(keys))); - getList().sort(null); - assertEquals(ARRAY_LIST.wrap(keys), getList()); - } - -#ignore - @ListFeature.Require(ListFeature.SUPPORTS_SET) - @CollectionSize.Require(CollectionSize.SEVERAL) -#endignore - public void testStableSort_Comparator() { - KEY_TYPE[] keys = collection.TO_ARRAY(NEW_KEY_ARRAY(collection.size())); - SanityChecks.getRandom().setSeed(212121212L); - LISTS.shuffle(getList()); - assertFalse(getList().equals(ARRAY_LIST.wrap(keys))); -#if TYPE_OBJECT - getList().sort((Comparator)Comparator.naturalOrder()); -#else - getList().sort(CLASS_TYPE::compare); -#endif - assertEquals(ARRAY_LIST.wrap(keys), getList()); - } - -#ignore - @ListFeature.Require(absent = ListFeature.SUPPORTS_SET) -#endignore - public void testStableSort_Null() { - try { - getList().sort(null); - } - catch(UnsupportedOperationException e) { - } - } - -#ignore - @ListFeature.Require(ListFeature.SUPPORTS_SET) - @CollectionSize.Require(CollectionSize.SEVERAL) -#endignore - public void testUnstableSort() { - KEY_TYPE[] keys = collection.TO_ARRAY(NEW_KEY_ARRAY(collection.size())); - SanityChecks.getRandom().setSeed(212121212L); - LISTS.shuffle(getList()); - assertFalse(getList().equals(ARRAY_LIST.wrap(keys))); - getList().unstableSort(null); - assertEquals(ARRAY_LIST.wrap(keys), getList()); - } - -#ignore - @ListFeature.Require(ListFeature.SUPPORTS_SET) - @CollectionSize.Require(CollectionSize.SEVERAL) -#endignore - public void testUnstableSort_Comparator() { - KEY_TYPE[] keys = collection.TO_ARRAY(NEW_KEY_ARRAY(collection.size())); - SanityChecks.getRandom().setSeed(212121212L); - LISTS.shuffle(getList()); - assertFalse(getList().equals(ARRAY_LIST.wrap(keys))); -#if TYPE_OBJECT - getList().unstableSort((Comparator)Comparator.naturalOrder()); -#else - getList().unstableSort(CLASS_TYPE::compare); -#endif - assertEquals(ARRAY_LIST.wrap(keys), getList()); - } - -#ignore - @ListFeature.Require(absent = ListFeature.SUPPORTS_SET) -#endignore - public void testUnstableSort_Null() { - try { - getList().unstableSort(null); - } - catch(UnsupportedOperationException e) { - } - } +package speiger.src.testers.PACKAGE.tests.list; + +#if TYPE_OBJECT +import java.util.Comparator; +#endif + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.ListFeature; + +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.utils.LISTS; +import speiger.src.collections.utils.SanityChecks; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListSortTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ +#ignore + @ListFeature.Require(ListFeature.SUPPORTS_SET) + @CollectionSize.Require(CollectionSize.SEVERAL) +#endignore + public void testStableSort() { + KEY_TYPE[] keys = collection.TO_ARRAY(NEW_KEY_ARRAY(collection.size())); + SanityChecks.getRandom().setSeed(212121212L); + LISTS.shuffle(getList()); + assertFalse(getList().equals(ARRAY_LIST.wrap(keys))); + getList().sort(null); + assertEquals(ARRAY_LIST.wrap(keys), getList()); + } + +#ignore + @ListFeature.Require(ListFeature.SUPPORTS_SET) + @CollectionSize.Require(CollectionSize.SEVERAL) +#endignore + public void testStableSort_Comparator() { + KEY_TYPE[] keys = collection.TO_ARRAY(NEW_KEY_ARRAY(collection.size())); + SanityChecks.getRandom().setSeed(212121212L); + LISTS.shuffle(getList()); + assertFalse(getList().equals(ARRAY_LIST.wrap(keys))); +#if TYPE_OBJECT + getList().sort((Comparator)Comparator.naturalOrder()); +#else + getList().sort(CLASS_TYPE::compare); +#endif + assertEquals(ARRAY_LIST.wrap(keys), getList()); + } + +#ignore + @ListFeature.Require(absent = ListFeature.SUPPORTS_SET) +#endignore + public void testStableSort_Null() { + try { + getList().sort(null); + } + catch(UnsupportedOperationException e) { + } + } + +#ignore + @ListFeature.Require(ListFeature.SUPPORTS_SET) + @CollectionSize.Require(CollectionSize.SEVERAL) +#endignore + public void testUnstableSort() { + KEY_TYPE[] keys = collection.TO_ARRAY(NEW_KEY_ARRAY(collection.size())); + SanityChecks.getRandom().setSeed(212121212L); + LISTS.shuffle(getList()); + assertFalse(getList().equals(ARRAY_LIST.wrap(keys))); + getList().unstableSort(null); + assertEquals(ARRAY_LIST.wrap(keys), getList()); + } + +#ignore + @ListFeature.Require(ListFeature.SUPPORTS_SET) + @CollectionSize.Require(CollectionSize.SEVERAL) +#endignore + public void testUnstableSort_Comparator() { + KEY_TYPE[] keys = collection.TO_ARRAY(NEW_KEY_ARRAY(collection.size())); + SanityChecks.getRandom().setSeed(212121212L); + LISTS.shuffle(getList()); + assertFalse(getList().equals(ARRAY_LIST.wrap(keys))); +#if TYPE_OBJECT + getList().unstableSort((Comparator)Comparator.naturalOrder()); +#else + getList().unstableSort(CLASS_TYPE::compare); +#endif + assertEquals(ARRAY_LIST.wrap(keys), getList()); + } + +#ignore + @ListFeature.Require(absent = ListFeature.SUPPORTS_SET) +#endignore + public void testUnstableSort_Null() { + try { + getList().unstableSort(null); + } + catch(UnsupportedOperationException e) { + } + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListSubListTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListSubListTester.template index fb9502f..0f54985 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListSubListTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListSubListTester.template @@ -1,309 +1,309 @@ -package speiger.src.testers.PACKAGE.tests.list; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS; -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX; -import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_REMOVE_WITH_INDEX; -import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_SET; -#endignore - -import java.util.Arrays; -import java.util.Collections; - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.ListFeature; -import com.google.common.testing.SerializableTester; - -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.collections.PACKAGE.utils.LISTS; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; -import speiger.src.testers.PACKAGE.utils.HELPERS; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListSubListTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ - public void testSubList_startNegative() { - try { - getList().subList(-1, 0); - fail("subList(-1, 0) should throw"); - } catch (IndexOutOfBoundsException expected) { - } - } - - public void testSubList_endTooLarge() { - try { - getList().subList(0, getNumElements() + 1); - fail("subList(0, size + 1) should throw"); - } catch (IndexOutOfBoundsException expected) { - } - } - - public void testSubList_startGreaterThanEnd() { - try { - getList().subList(1, 0); - fail("subList(1, 0) should throw"); - } catch (IndexOutOfBoundsException expected) { - } catch (IllegalArgumentException expected) { - } - } - - public void testSubList_empty() { - assertEquals("subList(0, 0) should be empty", LISTS.empty(), getList().subList(0, 0)); - } - - public void testSubList_entireList() { - assertEquals("subList(0, size) should be equal to the original list", getList(), getList().subList(0, getNumElements())); - } - -#ignore - @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testSubList_subListRemoveAffectsOriginal() { - LIST KEY_GENERIC_TYPE subList = getList().subList(0, 1); - subList.REMOVE(0); - expectContents(ARRAY_LIST.wrap(createSamplesArray()).subList(1, getNumElements())); - } - -#ignore - @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testSubList_subListClearAffectsOriginal() { - LIST KEY_GENERIC_TYPE subList = getList().subList(0, 1); - subList.clear(); - expectContents(ARRAY_LIST.wrap(createSamplesArray()).subList(1, getNumElements())); - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) -#endignore - public void testSubList_subListAddAffectsOriginal() { - LIST KEY_GENERIC_TYPE subList = getList().subList(0, 0); - subList.add(e3()); - expectAddedIndex(0, e3()); - } - -#ignore - @ListFeature.Require(SUPPORTS_SET) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testSubList_subListSetAffectsOriginal() { - LIST KEY_GENERIC_TYPE subList = getList().subList(0, 1); - subList.set(0, e3()); - LIST KEY_GENERIC_TYPE expected = HELPERS.copyToList(createSamplesArray()); - expected.set(0, e3()); - expectContents(expected); - } - -#ignore - @ListFeature.Require(SUPPORTS_SET) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testSubList_originalListSetAffectsSubList() { - LIST KEY_GENERIC_TYPE subList = getList().subList(0, 1); - getList().set(0, e3()); - assertEquals("A set() call to a list after a sublist has been created should be reflected in the sublist", LISTS.singleton(e3()), subList); - } - -#ignore - @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) - @CollectionSize.Require(absent = { ZERO, ONE }) -#endignore - public void testSubList_subListRemoveAffectsOriginalLargeList() { - LIST KEY_GENERIC_TYPE subList = getList().subList(1, 3); -#if TYPE_OBJECT - subList.remove(e2()); -#else - subList.REMOVE_KEY(e2()); -#endif - LIST KEY_GENERIC_TYPE expected = HELPERS.copyToList(createSamplesArray()); - expected.REMOVE(2); - expectContents(expected); - } - -#ignore - @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) - @CollectionSize.Require(absent = { ZERO, ONE }) -#endignore - public void testSubList_subListAddAtIndexAffectsOriginalLargeList() { - LIST KEY_GENERIC_TYPE subList = getList().subList(2, 3); - subList.add(0, e3()); - expectAddedIndex(2, e3()); - } - -#ignore - @ListFeature.Require(SUPPORTS_SET) - @CollectionSize.Require(absent = { ZERO, ONE }) -#endignore - public void testSubList_subListSetAffectsOriginalLargeList() { - LIST KEY_GENERIC_TYPE subList = getList().subList(1, 2); - subList.set(0, e3()); - LIST KEY_GENERIC_TYPE expected = HELPERS.copyToList(createSamplesArray()); - expected.set(1, e3()); - expectContents(expected); - } - -#ignore - @ListFeature.Require(SUPPORTS_SET) - @CollectionSize.Require(absent = { ZERO, ONE }) -#endignore - public void testSubList_originalListSetAffectsSubListLargeList() { - LIST KEY_GENERIC_TYPE subList = getList().subList(1, 3); - getList().set(1, e3()); - assertEquals("A set() call to a list after a sublist has been created " + "should be reflected in the sublist", - Arrays.asList(e3(), e2()), subList); - } - - public void testSubList_ofSubListEmpty() { - LIST KEY_GENERIC_TYPE subList = getList().subList(0, 0).subList(0, 0); - assertEquals("subList(0, 0).subList(0, 0) should be an empty list", LISTS.empty(), subList); - } - - @CollectionSize.Require(absent = { ZERO, ONE }) - public void testSubList_ofSubListNonEmpty() { - LIST KEY_GENERIC_TYPE subList = getList().subList(0, 2).subList(1, 2); - assertEquals("subList(0, 2).subList(1, 2) " + "should be a single-element list of the element at index 1", - Collections.singletonList(getOrderedElements().GET_KEY(1)), subList); - } - -#ignore - @CollectionSize.Require(absent = { ZERO }) -#endignore - public void testSubList_size() { - LIST KEY_GENERIC_TYPE list = getList(); - int size = getNumElements(); - assertEquals(size, list.subList(0, size).size()); - assertEquals(size - 1, list.subList(0, size - 1).size()); - assertEquals(size - 1, list.subList(1, size).size()); - assertEquals(0, list.subList(size, size).size()); - assertEquals(0, list.subList(0, 0).size()); - } - -#ignore - @CollectionSize.Require(absent = { ZERO }) -#endignore - public void testSubList_isEmpty() { - LIST KEY_GENERIC_TYPE list = getList(); - int size = getNumElements(); - for (LIST KEY_GENERIC_TYPE subList : Arrays.asList(list.subList(0, size), list.subList(0, size - 1), list.subList(1, size), - list.subList(0, 0), list.subList(size, size))) { - assertEquals(subList.size() == 0, subList.isEmpty()); - } - } - -#ignore - @CollectionSize.Require(absent = { ZERO, ONE }) -#endignore - public void testSubList_get() { - LIST KEY_GENERIC_TYPE list = getList(); - int size = getNumElements(); - LIST KEY_GENERIC_TYPE copy = list.subList(0, size); - LIST KEY_GENERIC_TYPE head = list.subList(0, size - 1); - LIST KEY_GENERIC_TYPE tail = list.subList(1, size); - assertEquals(list.GET_KEY(0), copy.GET_KEY(0)); - assertEquals(list.GET_KEY(size - 1), copy.GET_KEY(size - 1)); - assertEquals(list.GET_KEY(1), tail.GET_KEY(0)); - assertEquals(list.GET_KEY(size - 1), tail.GET_KEY(size - 2)); - assertEquals(list.GET_KEY(0), head.GET_KEY(0)); - assertEquals(list.GET_KEY(size - 2), head.GET_KEY(size - 2)); - for (LIST KEY_GENERIC_TYPE subList : Arrays.asList(copy, head, tail)) { - for (int index : Arrays.asList(-1, subList.size())) { - try { - subList.GET_KEY(index); - fail("expected IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException expected) { - } - } - } - } - -#ignore - @CollectionSize.Require(absent = { ZERO, ONE }) -#endignore - public void testSubList_contains() { - LIST KEY_GENERIC_TYPE list = getList(); - int size = getNumElements(); - LIST KEY_GENERIC_TYPE copy = list.subList(0, size); - LIST KEY_GENERIC_TYPE head = list.subList(0, size - 1); - LIST KEY_GENERIC_TYPE tail = list.subList(1, size); - assertTrue(copy.contains(list.GET_KEY(0))); - assertTrue(head.contains(list.GET_KEY(0))); - assertTrue(tail.contains(list.GET_KEY(1))); - // The following assumes all elements are distinct. - assertTrue(copy.contains(list.GET_KEY(size - 1))); - assertTrue(head.contains(list.GET_KEY(size - 2))); - assertTrue(tail.contains(list.GET_KEY(size - 1))); - assertFalse(head.contains(list.GET_KEY(size - 1))); - assertFalse(tail.contains(list.GET_KEY(0))); - } - -#ignore - @CollectionSize.Require(absent = { ZERO, ONE }) -#endignore - public void testSubList_indexOf() { - LIST KEY_GENERIC_TYPE list = getList(); - int size = getNumElements(); - LIST KEY_GENERIC_TYPE copy = list.subList(0, size); - LIST KEY_GENERIC_TYPE head = list.subList(0, size - 1); - LIST KEY_GENERIC_TYPE tail = list.subList(1, size); - assertEquals(0, copy.indexOf(list.GET_KEY(0))); - assertEquals(0, head.indexOf(list.GET_KEY(0))); - assertEquals(0, tail.indexOf(list.GET_KEY(1))); - // The following assumes all elements are distinct. - assertEquals(size - 1, copy.indexOf(list.GET_KEY(size - 1))); - assertEquals(size - 2, head.indexOf(list.GET_KEY(size - 2))); - assertEquals(size - 2, tail.indexOf(list.GET_KEY(size - 1))); - assertEquals(-1, head.indexOf(list.GET_KEY(size - 1))); - assertEquals(-1, tail.indexOf(list.GET_KEY(0))); - } - -#ignore - @CollectionSize.Require(absent = { ZERO, ONE }) -#endignore - public void testSubList_lastIndexOf() { - LIST KEY_GENERIC_TYPE list = getList(); - int size = list.size(); - LIST KEY_GENERIC_TYPE copy = list.subList(0, size); - LIST KEY_GENERIC_TYPE head = list.subList(0, size - 1); - LIST KEY_GENERIC_TYPE tail = list.subList(1, size); - assertEquals(size - 1, copy.lastIndexOf(list.GET_KEY(size - 1))); - assertEquals(size - 2, head.lastIndexOf(list.GET_KEY(size - 2))); - assertEquals(size - 2, tail.lastIndexOf(list.GET_KEY(size - 1))); - // The following assumes all elements are distinct. - assertEquals(0, copy.lastIndexOf(list.GET_KEY(0))); - assertEquals(0, head.lastIndexOf(list.GET_KEY(0))); - assertEquals(0, tail.lastIndexOf(list.GET_KEY(1))); - assertEquals(-1, head.lastIndexOf(list.GET_KEY(size - 1))); - assertEquals(-1, tail.lastIndexOf(list.GET_KEY(0))); - } - -#ignore - @CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS) -#endignore - public void testReserializeWholeSubList() { - SerializableTester.reserializeAndAssert(getList().subList(0, getNumElements())); - } - -#ignore - @CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS) -#endignore - public void testReserializeEmptySubList() { - SerializableTester.reserializeAndAssert(getList().subList(0, 0)); - } - -#ignore - @CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS) - @CollectionSize.Require(absent = { ZERO, ONE }) -#endignore - public void testReserializeSubList() { - SerializableTester.reserializeAndAssert(getList().subList(0, 2)); - } -} +package speiger.src.testers.PACKAGE.tests.list; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS; +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX; +import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_REMOVE_WITH_INDEX; +import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_SET; +#endignore + +import java.util.Arrays; +import java.util.Collections; + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.ListFeature; +import com.google.common.testing.SerializableTester; + +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.collections.PACKAGE.utils.LISTS; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; +import speiger.src.testers.PACKAGE.utils.HELPERS; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListSubListTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ + public void testSubList_startNegative() { + try { + getList().subList(-1, 0); + fail("subList(-1, 0) should throw"); + } catch (IndexOutOfBoundsException expected) { + } + } + + public void testSubList_endTooLarge() { + try { + getList().subList(0, getNumElements() + 1); + fail("subList(0, size + 1) should throw"); + } catch (IndexOutOfBoundsException expected) { + } + } + + public void testSubList_startGreaterThanEnd() { + try { + getList().subList(1, 0); + fail("subList(1, 0) should throw"); + } catch (IndexOutOfBoundsException expected) { + } catch (IllegalArgumentException expected) { + } + } + + public void testSubList_empty() { + assertEquals("subList(0, 0) should be empty", LISTS.empty(), getList().subList(0, 0)); + } + + public void testSubList_entireList() { + assertEquals("subList(0, size) should be equal to the original list", getList(), getList().subList(0, getNumElements())); + } + +#ignore + @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testSubList_subListRemoveAffectsOriginal() { + LIST KEY_GENERIC_TYPE subList = getList().subList(0, 1); + subList.REMOVE(0); + expectContents(ARRAY_LIST.wrap(createSamplesArray()).subList(1, getNumElements())); + } + +#ignore + @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testSubList_subListClearAffectsOriginal() { + LIST KEY_GENERIC_TYPE subList = getList().subList(0, 1); + subList.clear(); + expectContents(ARRAY_LIST.wrap(createSamplesArray()).subList(1, getNumElements())); + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) +#endignore + public void testSubList_subListAddAffectsOriginal() { + LIST KEY_GENERIC_TYPE subList = getList().subList(0, 0); + subList.add(e3()); + expectAddedIndex(0, e3()); + } + +#ignore + @ListFeature.Require(SUPPORTS_SET) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testSubList_subListSetAffectsOriginal() { + LIST KEY_GENERIC_TYPE subList = getList().subList(0, 1); + subList.set(0, e3()); + LIST KEY_GENERIC_TYPE expected = HELPERS.copyToList(createSamplesArray()); + expected.set(0, e3()); + expectContents(expected); + } + +#ignore + @ListFeature.Require(SUPPORTS_SET) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testSubList_originalListSetAffectsSubList() { + LIST KEY_GENERIC_TYPE subList = getList().subList(0, 1); + getList().set(0, e3()); + assertEquals("A set() call to a list after a sublist has been created should be reflected in the sublist", LISTS.singleton(e3()), subList); + } + +#ignore + @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) + @CollectionSize.Require(absent = { ZERO, ONE }) +#endignore + public void testSubList_subListRemoveAffectsOriginalLargeList() { + LIST KEY_GENERIC_TYPE subList = getList().subList(1, 3); +#if TYPE_OBJECT + subList.remove(e2()); +#else + subList.REMOVE_KEY(e2()); +#endif + LIST KEY_GENERIC_TYPE expected = HELPERS.copyToList(createSamplesArray()); + expected.REMOVE(2); + expectContents(expected); + } + +#ignore + @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) + @CollectionSize.Require(absent = { ZERO, ONE }) +#endignore + public void testSubList_subListAddAtIndexAffectsOriginalLargeList() { + LIST KEY_GENERIC_TYPE subList = getList().subList(2, 3); + subList.add(0, e3()); + expectAddedIndex(2, e3()); + } + +#ignore + @ListFeature.Require(SUPPORTS_SET) + @CollectionSize.Require(absent = { ZERO, ONE }) +#endignore + public void testSubList_subListSetAffectsOriginalLargeList() { + LIST KEY_GENERIC_TYPE subList = getList().subList(1, 2); + subList.set(0, e3()); + LIST KEY_GENERIC_TYPE expected = HELPERS.copyToList(createSamplesArray()); + expected.set(1, e3()); + expectContents(expected); + } + +#ignore + @ListFeature.Require(SUPPORTS_SET) + @CollectionSize.Require(absent = { ZERO, ONE }) +#endignore + public void testSubList_originalListSetAffectsSubListLargeList() { + LIST KEY_GENERIC_TYPE subList = getList().subList(1, 3); + getList().set(1, e3()); + assertEquals("A set() call to a list after a sublist has been created " + "should be reflected in the sublist", + Arrays.asList(e3(), e2()), subList); + } + + public void testSubList_ofSubListEmpty() { + LIST KEY_GENERIC_TYPE subList = getList().subList(0, 0).subList(0, 0); + assertEquals("subList(0, 0).subList(0, 0) should be an empty list", LISTS.empty(), subList); + } + + @CollectionSize.Require(absent = { ZERO, ONE }) + public void testSubList_ofSubListNonEmpty() { + LIST KEY_GENERIC_TYPE subList = getList().subList(0, 2).subList(1, 2); + assertEquals("subList(0, 2).subList(1, 2) " + "should be a single-element list of the element at index 1", + Collections.singletonList(getOrderedElements().GET_KEY(1)), subList); + } + +#ignore + @CollectionSize.Require(absent = { ZERO }) +#endignore + public void testSubList_size() { + LIST KEY_GENERIC_TYPE list = getList(); + int size = getNumElements(); + assertEquals(size, list.subList(0, size).size()); + assertEquals(size - 1, list.subList(0, size - 1).size()); + assertEquals(size - 1, list.subList(1, size).size()); + assertEquals(0, list.subList(size, size).size()); + assertEquals(0, list.subList(0, 0).size()); + } + +#ignore + @CollectionSize.Require(absent = { ZERO }) +#endignore + public void testSubList_isEmpty() { + LIST KEY_GENERIC_TYPE list = getList(); + int size = getNumElements(); + for (LIST KEY_GENERIC_TYPE subList : Arrays.asList(list.subList(0, size), list.subList(0, size - 1), list.subList(1, size), + list.subList(0, 0), list.subList(size, size))) { + assertEquals(subList.size() == 0, subList.isEmpty()); + } + } + +#ignore + @CollectionSize.Require(absent = { ZERO, ONE }) +#endignore + public void testSubList_get() { + LIST KEY_GENERIC_TYPE list = getList(); + int size = getNumElements(); + LIST KEY_GENERIC_TYPE copy = list.subList(0, size); + LIST KEY_GENERIC_TYPE head = list.subList(0, size - 1); + LIST KEY_GENERIC_TYPE tail = list.subList(1, size); + assertEquals(list.GET_KEY(0), copy.GET_KEY(0)); + assertEquals(list.GET_KEY(size - 1), copy.GET_KEY(size - 1)); + assertEquals(list.GET_KEY(1), tail.GET_KEY(0)); + assertEquals(list.GET_KEY(size - 1), tail.GET_KEY(size - 2)); + assertEquals(list.GET_KEY(0), head.GET_KEY(0)); + assertEquals(list.GET_KEY(size - 2), head.GET_KEY(size - 2)); + for (LIST KEY_GENERIC_TYPE subList : Arrays.asList(copy, head, tail)) { + for (int index : Arrays.asList(-1, subList.size())) { + try { + subList.GET_KEY(index); + fail("expected IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException expected) { + } + } + } + } + +#ignore + @CollectionSize.Require(absent = { ZERO, ONE }) +#endignore + public void testSubList_contains() { + LIST KEY_GENERIC_TYPE list = getList(); + int size = getNumElements(); + LIST KEY_GENERIC_TYPE copy = list.subList(0, size); + LIST KEY_GENERIC_TYPE head = list.subList(0, size - 1); + LIST KEY_GENERIC_TYPE tail = list.subList(1, size); + assertTrue(copy.contains(list.GET_KEY(0))); + assertTrue(head.contains(list.GET_KEY(0))); + assertTrue(tail.contains(list.GET_KEY(1))); + // The following assumes all elements are distinct. + assertTrue(copy.contains(list.GET_KEY(size - 1))); + assertTrue(head.contains(list.GET_KEY(size - 2))); + assertTrue(tail.contains(list.GET_KEY(size - 1))); + assertFalse(head.contains(list.GET_KEY(size - 1))); + assertFalse(tail.contains(list.GET_KEY(0))); + } + +#ignore + @CollectionSize.Require(absent = { ZERO, ONE }) +#endignore + public void testSubList_indexOf() { + LIST KEY_GENERIC_TYPE list = getList(); + int size = getNumElements(); + LIST KEY_GENERIC_TYPE copy = list.subList(0, size); + LIST KEY_GENERIC_TYPE head = list.subList(0, size - 1); + LIST KEY_GENERIC_TYPE tail = list.subList(1, size); + assertEquals(0, copy.indexOf(list.GET_KEY(0))); + assertEquals(0, head.indexOf(list.GET_KEY(0))); + assertEquals(0, tail.indexOf(list.GET_KEY(1))); + // The following assumes all elements are distinct. + assertEquals(size - 1, copy.indexOf(list.GET_KEY(size - 1))); + assertEquals(size - 2, head.indexOf(list.GET_KEY(size - 2))); + assertEquals(size - 2, tail.indexOf(list.GET_KEY(size - 1))); + assertEquals(-1, head.indexOf(list.GET_KEY(size - 1))); + assertEquals(-1, tail.indexOf(list.GET_KEY(0))); + } + +#ignore + @CollectionSize.Require(absent = { ZERO, ONE }) +#endignore + public void testSubList_lastIndexOf() { + LIST KEY_GENERIC_TYPE list = getList(); + int size = list.size(); + LIST KEY_GENERIC_TYPE copy = list.subList(0, size); + LIST KEY_GENERIC_TYPE head = list.subList(0, size - 1); + LIST KEY_GENERIC_TYPE tail = list.subList(1, size); + assertEquals(size - 1, copy.lastIndexOf(list.GET_KEY(size - 1))); + assertEquals(size - 2, head.lastIndexOf(list.GET_KEY(size - 2))); + assertEquals(size - 2, tail.lastIndexOf(list.GET_KEY(size - 1))); + // The following assumes all elements are distinct. + assertEquals(0, copy.lastIndexOf(list.GET_KEY(0))); + assertEquals(0, head.lastIndexOf(list.GET_KEY(0))); + assertEquals(0, tail.lastIndexOf(list.GET_KEY(1))); + assertEquals(-1, head.lastIndexOf(list.GET_KEY(size - 1))); + assertEquals(-1, tail.lastIndexOf(list.GET_KEY(0))); + } + +#ignore + @CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS) +#endignore + public void testReserializeWholeSubList() { + SerializableTester.reserializeAndAssert(getList().subList(0, getNumElements())); + } + +#ignore + @CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS) +#endignore + public void testReserializeEmptySubList() { + SerializableTester.reserializeAndAssert(getList().subList(0, 0)); + } + +#ignore + @CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS) + @CollectionSize.Require(absent = { ZERO, ONE }) +#endignore + public void testReserializeSubList() { + SerializableTester.reserializeAndAssert(getList().subList(0, 2)); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListSwapRemoveAtIndexTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListSwapRemoveAtIndexTester.template index 713e490..d30be1d 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListSwapRemoveAtIndexTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListSwapRemoveAtIndexTester.template @@ -1,115 +1,115 @@ -package speiger.src.testers.PACKAGE.tests.list; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_REMOVE_WITH_INDEX; -#endignore - -import java.util.ConcurrentModificationException; - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.ListFeature; - -import speiger.src.collections.PACKAGE.collections.ITERATOR; -import speiger.src.collections.PACKAGE.collections.COLLECTION; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; -import speiger.src.testers.PACKAGE.utils.HELPERS; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListSwapRemoveAtIndexTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ -#ignore - @ListFeature.Require(absent = SUPPORTS_REMOVE_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) - public void testRemoveAtIndex_unsupported() { - try { - getList().swapRemove(0); - fail("remove(i) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } - - @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) - public void testRemoveAtIndex_negative() { - try { - getList().swapRemove(-1); - fail("remove(-1) should throw"); - } catch (IndexOutOfBoundsException expected) { - } - expectUnchanged(); - } - - @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) - public void testRemoveAtIndex_tooLarge() { - try { - getList().swapRemove(getNumElements()); - fail("remove(size) should throw"); - } catch (IndexOutOfBoundsException expected) { - } - expectUnchanged(); - } - - @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) - public void testRemoveAtIndex_first() { - runRemoveTest(0); - } - - @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) - @CollectionSize.Require(absent = { ZERO, ONE }) -#endignore - public void testRemoveAtSecondOfFour() { - COLLECTION KEY_GENERIC_TYPE samples = getSampleElements(4); - KEY_TYPE[] data = samples.TO_ARRAY(NEW_KEY_ARRAY(4)); - collection = primitiveGenerator.create(data); - assertEquals(data[1], getList().GET_KEY(1)); - assertEquals(data[1], getList().swapRemove(1)); - assertEquals(data[3], getList().GET_KEY(1)); - } - -#ignore - @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) - @CollectionSize.Require(absent = { ZERO, ONE }) - public void testRemoveAtIndex_middle() { - runRemoveTest(getNumElements() / 2); - } - - @CollectionFeature.Require(FAILS_FAST_ON_CONCURRENT_MODIFICATION) - @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRemoveAtIndexConcurrentWithIteration() { - try { - ITERATOR KEY_GENERIC_TYPE iterator = collection.iterator(); - getList().swapRemove(getNumElements() / 2); - iterator.NEXT(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#ignore - @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRemoveAtIndex_last() { - runRemoveTest(getNumElements() - 1); - } - - private void runRemoveTest(int index) { - assertEquals(String.format("remove(%d) should return the element at index %d", index, index), getList().GET_KEY(index), getList().swapRemove(index)); - LIST KEY_GENERIC_TYPE expected = HELPERS.copyToList(createSamplesArray()); - expected.set(index, expected.GET_KEY(expected.size()-1)); - expected.REMOVE(expected.size()-1); - expectContents(expected); - } -} +package speiger.src.testers.PACKAGE.tests.list; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_REMOVE_WITH_INDEX; +#endignore + +import java.util.ConcurrentModificationException; + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.ListFeature; + +import speiger.src.collections.PACKAGE.collections.ITERATOR; +import speiger.src.collections.PACKAGE.collections.COLLECTION; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; +import speiger.src.testers.PACKAGE.utils.HELPERS; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListSwapRemoveAtIndexTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ +#ignore + @ListFeature.Require(absent = SUPPORTS_REMOVE_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) + public void testRemoveAtIndex_unsupported() { + try { + getList().swapRemove(0); + fail("remove(i) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } + + @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) + public void testRemoveAtIndex_negative() { + try { + getList().swapRemove(-1); + fail("remove(-1) should throw"); + } catch (IndexOutOfBoundsException expected) { + } + expectUnchanged(); + } + + @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) + public void testRemoveAtIndex_tooLarge() { + try { + getList().swapRemove(getNumElements()); + fail("remove(size) should throw"); + } catch (IndexOutOfBoundsException expected) { + } + expectUnchanged(); + } + + @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) + public void testRemoveAtIndex_first() { + runRemoveTest(0); + } + + @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) + @CollectionSize.Require(absent = { ZERO, ONE }) +#endignore + public void testRemoveAtSecondOfFour() { + COLLECTION KEY_GENERIC_TYPE samples = getSampleElements(4); + KEY_TYPE[] data = samples.TO_ARRAY(NEW_KEY_ARRAY(4)); + collection = primitiveGenerator.create(data); + assertEquals(data[1], getList().GET_KEY(1)); + assertEquals(data[1], getList().swapRemove(1)); + assertEquals(data[3], getList().GET_KEY(1)); + } + +#ignore + @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) + @CollectionSize.Require(absent = { ZERO, ONE }) + public void testRemoveAtIndex_middle() { + runRemoveTest(getNumElements() / 2); + } + + @CollectionFeature.Require(FAILS_FAST_ON_CONCURRENT_MODIFICATION) + @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRemoveAtIndexConcurrentWithIteration() { + try { + ITERATOR KEY_GENERIC_TYPE iterator = collection.iterator(); + getList().swapRemove(getNumElements() / 2); + iterator.NEXT(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#ignore + @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRemoveAtIndex_last() { + runRemoveTest(getNumElements() - 1); + } + + private void runRemoveTest(int index) { + assertEquals(String.format("remove(%d) should return the element at index %d", index, index), getList().GET_KEY(index), getList().swapRemove(index)); + LIST KEY_GENERIC_TYPE expected = HELPERS.copyToList(createSamplesArray()); + expected.set(index, expected.GET_KEY(expected.size()-1)); + expected.REMOVE(expected.size()-1); + expectContents(expected); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListSwapRemoveTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListSwapRemoveTester.template index c4c8061..a715372 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListSwapRemoveTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListSwapRemoveTester.template @@ -1,81 +1,81 @@ -package speiger.src.testers.PACKAGE.tests.list; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -#if !TYPE_BOOLEAN -import speiger.src.collections.PACKAGE.collections.COLLECTION; -#endif -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListSwapRemoveTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = {ZERO, ONE}) -#endignore - public void testRemove_duplicate() { - ArrayWithDuplicate KEY_GENERIC_TYPE arrayAndDuplicate = createArrayWithDuplicateElement(); - collection = primitiveGenerator.create(arrayAndDuplicate.elements); - KEY_TYPE duplicate = arrayAndDuplicate.duplicate; - KEY_TYPE lastElement = arrayAndDuplicate.elements[arrayAndDuplicate.elements.length-1]; - - int firstIndex = getList().indexOf(duplicate); - int initialSize = getList().size(); - assertTrue("swapRemove(present) should return true", getList().REMOVE_SWAP(duplicate)); - assertTrue("removed element should have moved the last element in its place", getList().GET_KEY(firstIndex) == lastElement); - assertTrue("After remove(duplicate), a list should still contain the duplicate element", getList().contains(duplicate)); - assertEquals("remove(present) should decrease the size of a list by one.", initialSize - 1, getList().size()); - } -#if !TYPE_BOOLEAN - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = {ZERO, ONE}) -#endignore - public void testSwapRemove_First() { - assertTrue(getList().REMOVE_SWAP(e0())); - assertFalse(getList().contains(e0())); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = { ZERO, ONE }) -#endignore - public void testRemoveAtSecondOfFour() { - COLLECTION KEY_GENERIC_TYPE samples = getSampleElements(4); - KEY_TYPE[] data = samples.TO_ARRAY(NEW_KEY_ARRAY(4)); - collection = primitiveGenerator.create(data); - assertTrue(getList().REMOVE_SWAP(data[2])); - assertFalse(getList().contains(data[2])); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = {ZERO, ONE}) -#endignore - public void testSwapRemove_Middle() { - assertTrue(getList().REMOVE_SWAP(e1())); - assertFalse(getList().contains(e1())); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = {ZERO, ONE}) -#endignore - public void testSwapRemove_Missing() { - assertFalse(getList().REMOVE_SWAP(e3())); - assertFalse(getList().contains(e3())); - } -#endif +package speiger.src.testers.PACKAGE.tests.list; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +#if !TYPE_BOOLEAN +import speiger.src.collections.PACKAGE.collections.COLLECTION; +#endif +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListSwapRemoveTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = {ZERO, ONE}) +#endignore + public void testRemove_duplicate() { + ArrayWithDuplicate KEY_GENERIC_TYPE arrayAndDuplicate = createArrayWithDuplicateElement(); + collection = primitiveGenerator.create(arrayAndDuplicate.elements); + KEY_TYPE duplicate = arrayAndDuplicate.duplicate; + KEY_TYPE lastElement = arrayAndDuplicate.elements[arrayAndDuplicate.elements.length-1]; + + int firstIndex = getList().indexOf(duplicate); + int initialSize = getList().size(); + assertTrue("swapRemove(present) should return true", getList().REMOVE_SWAP(duplicate)); + assertTrue("removed element should have moved the last element in its place", getList().GET_KEY(firstIndex) == lastElement); + assertTrue("After remove(duplicate), a list should still contain the duplicate element", getList().contains(duplicate)); + assertEquals("remove(present) should decrease the size of a list by one.", initialSize - 1, getList().size()); + } +#if !TYPE_BOOLEAN + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = {ZERO, ONE}) +#endignore + public void testSwapRemove_First() { + assertTrue(getList().REMOVE_SWAP(e0())); + assertFalse(getList().contains(e0())); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = { ZERO, ONE }) +#endignore + public void testRemoveAtSecondOfFour() { + COLLECTION KEY_GENERIC_TYPE samples = getSampleElements(4); + KEY_TYPE[] data = samples.TO_ARRAY(NEW_KEY_ARRAY(4)); + collection = primitiveGenerator.create(data); + assertTrue(getList().REMOVE_SWAP(data[2])); + assertFalse(getList().contains(data[2])); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = {ZERO, ONE}) +#endignore + public void testSwapRemove_Middle() { + assertTrue(getList().REMOVE_SWAP(e1())); + assertFalse(getList().contains(e1())); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = {ZERO, ONE}) +#endignore + public void testSwapRemove_Missing() { + assertFalse(getList().REMOVE_SWAP(e3())); + assertFalse(getList().contains(e3())); + } +#endif } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListToArrayTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListToArrayTester.template index a7163d7..f818ac0 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/list/ListToArrayTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/list/ListToArrayTester.template @@ -1,37 +1,37 @@ -package speiger.src.testers.PACKAGE.tests.list; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEListToArrayTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE -{ - public void testToArray_noArg() { - KEY_OBJECT_TYPE[] actual = getList().TO_ARRAY(); - assertArrayEquals("toArray() order should match list", createOrderedArray(), actual); - } - - @CollectionSize.Require(absent = ZERO) - public void testToArray_tooSmall() { - KEY_TYPE[] actual = getList().TO_ARRAY(NEW_KEY_ARRAY(0)); - assertArrayEquals("toArray(tooSmall) order should match list", createOrderedArray(), actual); - } - - public void testToArray_largeEnough() { - KEY_TYPE[] actual = getList().TO_ARRAY(NEW_KEY_ARRAY(getNumElements())); - assertArrayEquals("toArray(largeEnough) order should match list", createOrderedArray(), actual); - } - - private static void assertArrayEquals(String message, KEY_OBJECT_TYPE[] expected, KEY_OBJECT_TYPE[] actual) { - assertEquals(message, ARRAY_LIST.wrap(expected), ARRAY_LIST.wrap(actual)); - } -} +package speiger.src.testers.PACKAGE.tests.list; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_LIST_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEListToArrayTester KEY_GENERIC_TYPE extends ABSTRACT_LIST_TESTER KEY_GENERIC_TYPE +{ + public void testToArray_noArg() { + KEY_OBJECT_TYPE[] actual = getList().TO_ARRAY(); + assertArrayEquals("toArray() order should match list", createOrderedArray(), actual); + } + + @CollectionSize.Require(absent = ZERO) + public void testToArray_tooSmall() { + KEY_TYPE[] actual = getList().TO_ARRAY(NEW_KEY_ARRAY(0)); + assertArrayEquals("toArray(tooSmall) order should match list", createOrderedArray(), actual); + } + + public void testToArray_largeEnough() { + KEY_TYPE[] actual = getList().TO_ARRAY(NEW_KEY_ARRAY(getNumElements())); + assertArrayEquals("toArray(largeEnough) order should match list", createOrderedArray(), actual); + } + + private static void assertArrayEquals(String message, KEY_OBJECT_TYPE[] expected, KEY_OBJECT_TYPE[] actual) { + assertEquals(message, ARRAY_LIST.wrap(expected), ARRAY_LIST.wrap(actual)); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapAddToTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapAddToTester.template index 33208e3..f289eaa 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapAddToTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapAddToTester.template @@ -1,150 +1,150 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -import org.junit.Ignore; - -#if VALUE_PRIMITIVES -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; -#endignore - -import java.util.ConcurrentModificationException; -import java.util.Iterator; - - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; - -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; -#if !SAME_TYPE -import speiger.src.collections.PACKAGE.collections.ITERATOR; -#endif -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -#endif -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapAddToTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ -#if VALUE_PRIMITIVES -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddTo_supportedPresent() { - assertEquals("addTo(present, value) should return the old value", v0(), getMap().addTo(k0(), v3())); -#if VALUE_CHAR - expectReplacement(entry(k0(), (char)(v0()+v3()))); -#else - expectReplacement(entry(k0(), v3())); -#endif - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) -#endignore - public void testAddTo_supportedNotPresent() { - assertEquals("addTo(notPresent, value) should return INVALID_VALUE", INVALID_VALUE, addTo(e3())); - expectAdded(e3()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) -#endignore - public void testAddToSum_supportedNotPresent() { - assertEquals("addTo(notPresent, value) should return INVALID_VALUE", INVALID_VALUE, addTo(e3())); - assertEquals("addTo(notPresent, value) should return "+v3(), v3(), addTo(e3())); - expectAdded(entry(k3(), (VALUE_TYPE)(v3()+v3()))); - } - - -#ignore - @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT }) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddToAbsentConcurrentWithEntrySetIteration() { - try { - Iterator iterator = getMap().ENTRY_SET().iterator(); - addTo(e3()); - iterator.next(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#ignore - @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT }) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddToAbsentConcurrentWithKeySetIteration() { - try { - ITERATOR KEY_GENERIC_TYPE iterator = getMap().keySet().iterator(); - addTo(e3()); - iterator.NEXT(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#ignore - @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT }) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddToAbsentConcurrentWithValueIteration() { - try { - VALUE_ITERATOR VALUE_GENERIC_TYPE iterator = getMap().values().iterator(); - addTo(e3()); - iterator.VALUE_NEXT(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) -#endignore - public void testAddTo_unsupportedNotPresent() { - try { - addTo(e3()); - fail("addTo(notPresent, value) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - expectMissing(e3()); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddTo_unsupportedPresentExistingValue() { - try { - assertEquals("addTo(present, existingValue) should return present or throw", v0(), addTo(e0())); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddTo_unsupportedPresentDifferentValue() { - try { - getMap().addTo(k0(), v3()); - fail("addTo(present, differentValue) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } - - private VALUE_TYPE addTo(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { - return getMap().addTo(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); - } -#endif -} +package speiger.src.testers.PACKAGE.tests.maps; + +import org.junit.Ignore; + +#if VALUE_PRIMITIVES +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; +#endignore + +import java.util.ConcurrentModificationException; +import java.util.Iterator; + + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; +#if !SAME_TYPE +import speiger.src.collections.PACKAGE.collections.ITERATOR; +#endif +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +#endif +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapAddToTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#if VALUE_PRIMITIVES +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddTo_supportedPresent() { + assertEquals("addTo(present, value) should return the old value", v0(), getMap().addTo(k0(), v3())); +#if VALUE_CHAR + expectReplacement(entry(k0(), (char)(v0()+v3()))); +#else + expectReplacement(entry(k0(), v3())); +#endif + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) +#endignore + public void testAddTo_supportedNotPresent() { + assertEquals("addTo(notPresent, value) should return INVALID_VALUE", INVALID_VALUE, addTo(e3())); + expectAdded(e3()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) +#endignore + public void testAddToSum_supportedNotPresent() { + assertEquals("addTo(notPresent, value) should return INVALID_VALUE", INVALID_VALUE, addTo(e3())); + assertEquals("addTo(notPresent, value) should return "+v3(), v3(), addTo(e3())); + expectAdded(entry(k3(), (VALUE_TYPE)(v3()+v3()))); + } + + +#ignore + @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT }) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddToAbsentConcurrentWithEntrySetIteration() { + try { + Iterator iterator = getMap().ENTRY_SET().iterator(); + addTo(e3()); + iterator.next(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#ignore + @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT }) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddToAbsentConcurrentWithKeySetIteration() { + try { + ITERATOR KEY_GENERIC_TYPE iterator = getMap().keySet().iterator(); + addTo(e3()); + iterator.NEXT(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#ignore + @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT }) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddToAbsentConcurrentWithValueIteration() { + try { + VALUE_ITERATOR VALUE_GENERIC_TYPE iterator = getMap().values().iterator(); + addTo(e3()); + iterator.VALUE_NEXT(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) +#endignore + public void testAddTo_unsupportedNotPresent() { + try { + addTo(e3()); + fail("addTo(notPresent, value) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + expectMissing(e3()); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddTo_unsupportedPresentExistingValue() { + try { + assertEquals("addTo(present, existingValue) should return present or throw", v0(), addTo(e0())); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddTo_unsupportedPresentDifferentValue() { + try { + getMap().addTo(k0(), v3()); + fail("addTo(present, differentValue) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } + + private VALUE_TYPE addTo(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { + return getMap().addTo(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); + } +#endif +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapClearTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapClearTester.template index 7490f3d..ad0e8a0 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapClearTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapClearTester.template @@ -1,110 +1,110 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; -#endignore - -import java.util.ConcurrentModificationException; - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; - -#if !VALUE_OBJECT -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; -#endif -#if !TYPE_OBJECT && !SAME_TYPE -import speiger.src.collections.PACKAGE.collections.ITERATOR; -#endif -import speiger.src.collections.PACKAGE.maps.interfaces.MAP.Entry; -import speiger.src.collections.objects.collections.ObjectIterator; -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapClearTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) -#endignore - public void testClear() { - getMap().clear(); - assertTrue("After clear(), a map should be empty.", getMap().isEmpty()); - assertEquals(0, getMap().size()); - assertFalse(getMap().ENTRY_SET().iterator().hasNext()); - } - -#ignore - @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE }) - @CollectionSize.Require(SEVERAL) -#endignore - public void testClearConcurrentWithEntrySetIteration() { - try { - ObjectIterator iterator = getMap().ENTRY_SET().iterator(); - getMap().clear(); - iterator.next(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#ignore - @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE }) - @CollectionSize.Require(SEVERAL) -#endignore - public void testClearConcurrentWithKeySetIteration() { - try { - ITERATOR KEY_GENERIC_TYPE iterator = getMap().keySet().iterator(); - getMap().clear(); - iterator.NEXT(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#ignore - @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE }) - @CollectionSize.Require(SEVERAL) -#endignore - public void testClearConcurrentWithValuesIteration() { - try { - VALUE_ITERATOR VALUE_GENERIC_TYPE iterator = getMap().values().iterator(); - getMap().clear(); - iterator.VALUE_NEXT(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testClear_unsupported() { - try { - getMap().clear(); - fail("clear() should throw UnsupportedOperation if a map does not support it and is not empty."); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_REMOVE) - @CollectionSize.Require(ZERO) -#endignore - public void testClear_unsupportedByEmptyCollection() { - try { - getMap().clear(); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; +#endignore + +import java.util.ConcurrentModificationException; + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +#if !VALUE_OBJECT +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; +#endif +#if !TYPE_OBJECT && !SAME_TYPE +import speiger.src.collections.PACKAGE.collections.ITERATOR; +#endif +import speiger.src.collections.PACKAGE.maps.interfaces.MAP.Entry; +import speiger.src.collections.objects.collections.ObjectIterator; +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapClearTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) +#endignore + public void testClear() { + getMap().clear(); + assertTrue("After clear(), a map should be empty.", getMap().isEmpty()); + assertEquals(0, getMap().size()); + assertFalse(getMap().ENTRY_SET().iterator().hasNext()); + } + +#ignore + @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE }) + @CollectionSize.Require(SEVERAL) +#endignore + public void testClearConcurrentWithEntrySetIteration() { + try { + ObjectIterator iterator = getMap().ENTRY_SET().iterator(); + getMap().clear(); + iterator.next(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#ignore + @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE }) + @CollectionSize.Require(SEVERAL) +#endignore + public void testClearConcurrentWithKeySetIteration() { + try { + ITERATOR KEY_GENERIC_TYPE iterator = getMap().keySet().iterator(); + getMap().clear(); + iterator.NEXT(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#ignore + @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE }) + @CollectionSize.Require(SEVERAL) +#endignore + public void testClearConcurrentWithValuesIteration() { + try { + VALUE_ITERATOR VALUE_GENERIC_TYPE iterator = getMap().values().iterator(); + getMap().clear(); + iterator.VALUE_NEXT(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testClear_unsupported() { + try { + getMap().clear(); + fail("clear() should throw UnsupportedOperation if a map does not support it and is not empty."); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_REMOVE) + @CollectionSize.Require(ZERO) +#endignore + public void testClear_unsupportedByEmptyCollection() { + try { + getMap().clear(); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapComputeIfAbsentTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapComputeIfAbsentTester.template index b151a09..ca67b61 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapComputeIfAbsentTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapComputeIfAbsentTester.template @@ -1,157 +1,157 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; -#endignore -#if !VALUE_BOOLEAN -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ONE; -#endignore -#endif - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; - -import junit.framework.AssertionFailedError; -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeIfAbsentTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ -#ignore - @MapFeature.Require(SUPPORTS_PUT) -#endignore - public void testComputeIfAbsent_supportedAbsent() { - assertEquals("COMPUTE_IF_ABSENT(notPresent, function) should return new value", v3(), - getMap().COMPUTE_IF_ABSENT(k3(), k -> { - assertEquals(k3(), k); - return v3(); - })); - expectAdded(e3()); - } - -#if !VALUE_BOOLEAN -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(ONE) -#endignore - public void testComputeIfAbsent_supportedAbsentFirst() { - getMap().setDefaultReturnValue(v0()); - assertEquals("COMPUTE_IF_ABSENT(notPresent, function) should return new value", v3(), - getMap().COMPUTE_IF_ABSENT(k0(), k -> { - assertEquals(k0(), k); - return v3(); - })); - expectContents(entry(k0(), v3())); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(ONE) -#endignore - public void testComputeIfAbsent_supportedAbsentSameResult() { - getMap().setDefaultReturnValue(v0()); - assertEquals("COMPUTE_IF_ABSENT(notPresent, function) should return new value", v0(), - getMap().COMPUTE_IF_ABSENT(k0(), k -> { - assertEquals(k0(), k); - return v0(); - })); - expectUnchanged(); - } - -#endif -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testComputeIfAbsent_supportedPresent() { - assertEquals("COMPUTE_IF_ABSENT(present, function) should return existing value", v0(), - getMap().COMPUTE_IF_ABSENT(k0(), k -> { - throw new AssertionFailedError(); - })); - expectUnchanged(); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) -#endignore - public void testComputeIfAbsent_functionReturnsNullNotInserted() { - assertEquals("COMPUTE_IF_ABSENT(absent, returnsNull) should return INVALID_VALUE", - INVALID_VALUE, getMap().COMPUTE_IF_ABSENT(k3(), k -> { - assertEquals(k3(), k); - return INVALID_VALUE; - })); - expectUnchanged(); - } - - static class ExpectedException extends RuntimeException { - private static final long serialVersionUID = 1L; - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) -#endignore - public void testComputeIfAbsent_functionThrows() { - try { - getMap().COMPUTE_IF_ABSENT(k3(), k -> { - assertEquals(k3(), k); - throw new ExpectedException(); - }); - fail("Expected ExpectedException"); - } catch (ExpectedException expected) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) -#endignore - public void testComputeIfAbsent_unsupportedAbsent() { - try { - getMap().COMPUTE_IF_ABSENT(k3(), k -> { - // allowed to be called - assertEquals(k3(), k); - return v3(); - }); - fail("COMPUTE_IF_ABSENT(notPresent, function) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testComputeIfAbsent_unsupportedPresentExistingValue() { - try { - assertEquals("COMPUTE_IF_ABSENT(present, returnsCurrentValue) should return present or throw", v0(), - getMap().COMPUTE_IF_ABSENT(k0(), k -> { - assertEquals(k0(), k); - return v0(); - })); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testComputeIfAbsent_unsupportedPresentDifferentValue() { - try { - assertEquals("COMPUTE_IF_ABSENT(present, returnsDifferentValue) should return present or throw", v0(), - getMap().COMPUTE_IF_ABSENT(k0(), k -> { - assertEquals(k0(), k); - return v3(); - })); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; +#endignore +#if !VALUE_BOOLEAN +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ONE; +#endignore +#endif + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +import junit.framework.AssertionFailedError; +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeIfAbsentTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#ignore + @MapFeature.Require(SUPPORTS_PUT) +#endignore + public void testComputeIfAbsent_supportedAbsent() { + assertEquals("COMPUTE_IF_ABSENT(notPresent, function) should return new value", v3(), + getMap().COMPUTE_IF_ABSENT(k3(), k -> { + assertEquals(k3(), k); + return v3(); + })); + expectAdded(e3()); + } + +#if !VALUE_BOOLEAN +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(ONE) +#endignore + public void testComputeIfAbsent_supportedAbsentFirst() { + getMap().setDefaultReturnValue(v0()); + assertEquals("COMPUTE_IF_ABSENT(notPresent, function) should return new value", v3(), + getMap().COMPUTE_IF_ABSENT(k0(), k -> { + assertEquals(k0(), k); + return v3(); + })); + expectContents(entry(k0(), v3())); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(ONE) +#endignore + public void testComputeIfAbsent_supportedAbsentSameResult() { + getMap().setDefaultReturnValue(v0()); + assertEquals("COMPUTE_IF_ABSENT(notPresent, function) should return new value", v0(), + getMap().COMPUTE_IF_ABSENT(k0(), k -> { + assertEquals(k0(), k); + return v0(); + })); + expectUnchanged(); + } + +#endif +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testComputeIfAbsent_supportedPresent() { + assertEquals("COMPUTE_IF_ABSENT(present, function) should return existing value", v0(), + getMap().COMPUTE_IF_ABSENT(k0(), k -> { + throw new AssertionFailedError(); + })); + expectUnchanged(); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) +#endignore + public void testComputeIfAbsent_functionReturnsNullNotInserted() { + assertEquals("COMPUTE_IF_ABSENT(absent, returnsNull) should return INVALID_VALUE", + INVALID_VALUE, getMap().COMPUTE_IF_ABSENT(k3(), k -> { + assertEquals(k3(), k); + return INVALID_VALUE; + })); + expectUnchanged(); + } + + static class ExpectedException extends RuntimeException { + private static final long serialVersionUID = 1L; + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) +#endignore + public void testComputeIfAbsent_functionThrows() { + try { + getMap().COMPUTE_IF_ABSENT(k3(), k -> { + assertEquals(k3(), k); + throw new ExpectedException(); + }); + fail("Expected ExpectedException"); + } catch (ExpectedException expected) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) +#endignore + public void testComputeIfAbsent_unsupportedAbsent() { + try { + getMap().COMPUTE_IF_ABSENT(k3(), k -> { + // allowed to be called + assertEquals(k3(), k); + return v3(); + }); + fail("COMPUTE_IF_ABSENT(notPresent, function) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testComputeIfAbsent_unsupportedPresentExistingValue() { + try { + assertEquals("COMPUTE_IF_ABSENT(present, returnsCurrentValue) should return present or throw", v0(), + getMap().COMPUTE_IF_ABSENT(k0(), k -> { + assertEquals(k0(), k); + return v0(); + })); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testComputeIfAbsent_unsupportedPresentDifferentValue() { + try { + assertEquals("COMPUTE_IF_ABSENT(present, returnsDifferentValue) should return present or throw", v0(), + getMap().COMPUTE_IF_ABSENT(k0(), k -> { + assertEquals(k0(), k); + return v3(); + })); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapComputeIfPresentTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapComputeIfPresentTester.template index 9511597..58b0ad1 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapComputeIfPresentTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapComputeIfPresentTester.template @@ -1,105 +1,105 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; -#endignore - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; - -import junit.framework.AssertionFailedError; -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeIfPresentTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ -#ignore - @MapFeature.Require(SUPPORTS_PUT) -#endignore - public void testComputeIfPresent_supportedAbsent() { - assertEquals("COMPUTE_IF_PRESENT(notPresent, function) should return INVALID_VALUE", INVALID_VALUE, - getMap().COMPUTE_IF_PRESENT(k3(), (k, v) -> { - throw new AssertionFailedError(); - })); - expectUnchanged(); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testComputeIfPresent_supportedPresent() { - assertEquals("COMPUTE_IF_PRESENT(present, function) should return new value", v3(), - getMap().COMPUTE_IF_PRESENT(k0(), (k, v) -> { - assertEquals(k0(), k); - assertEquals(v0(), v); - return v3(); - })); - expectReplacement(entry(k0(), v3())); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testComputeIfPresent_functionReturnsNull() { - assertEquals("COMPUTE_IF_PRESENT(present, returnsNull) should return INVALID_VALUE", INVALID_VALUE, - getMap().COMPUTE_IF_PRESENT(k0(), (k, v) -> { - assertEquals(k0(), k); - assertEquals(v0(), v); - return INVALID_VALUE; - })); - expectMissing(e0()); - } - - static class ExpectedException extends RuntimeException { - private static final long serialVersionUID = 1L; - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testComputeIfPresent_functionThrows() { - try { - getMap().COMPUTE_IF_PRESENT(k0(), (k, v) -> { - assertEquals(k0(), k); - assertEquals(v0(), v); - throw new ExpectedException(); - }); - fail("Expected ExpectedException"); - } catch (ExpectedException expected) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) -#endignore - public void testComputeIfPresent_unsupportedAbsent() { - try { - getMap().COMPUTE_IF_PRESENT(k3(), (k, v) -> { - throw new AssertionFailedError(); - }); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testComputeIfPresent_unsupportedPresent() { - try { - getMap().COMPUTE_IF_PRESENT(k0(), (k, v) -> v3()); - fail("Expected UnsupportedOperationException"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; +#endignore + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +import junit.framework.AssertionFailedError; +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeIfPresentTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#ignore + @MapFeature.Require(SUPPORTS_PUT) +#endignore + public void testComputeIfPresent_supportedAbsent() { + assertEquals("COMPUTE_IF_PRESENT(notPresent, function) should return INVALID_VALUE", INVALID_VALUE, + getMap().COMPUTE_IF_PRESENT(k3(), (k, v) -> { + throw new AssertionFailedError(); + })); + expectUnchanged(); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testComputeIfPresent_supportedPresent() { + assertEquals("COMPUTE_IF_PRESENT(present, function) should return new value", v3(), + getMap().COMPUTE_IF_PRESENT(k0(), (k, v) -> { + assertEquals(k0(), k); + assertEquals(v0(), v); + return v3(); + })); + expectReplacement(entry(k0(), v3())); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testComputeIfPresent_functionReturnsNull() { + assertEquals("COMPUTE_IF_PRESENT(present, returnsNull) should return INVALID_VALUE", INVALID_VALUE, + getMap().COMPUTE_IF_PRESENT(k0(), (k, v) -> { + assertEquals(k0(), k); + assertEquals(v0(), v); + return INVALID_VALUE; + })); + expectMissing(e0()); + } + + static class ExpectedException extends RuntimeException { + private static final long serialVersionUID = 1L; + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testComputeIfPresent_functionThrows() { + try { + getMap().COMPUTE_IF_PRESENT(k0(), (k, v) -> { + assertEquals(k0(), k); + assertEquals(v0(), v); + throw new ExpectedException(); + }); + fail("Expected ExpectedException"); + } catch (ExpectedException expected) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) +#endignore + public void testComputeIfPresent_unsupportedAbsent() { + try { + getMap().COMPUTE_IF_PRESENT(k3(), (k, v) -> { + throw new AssertionFailedError(); + }); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testComputeIfPresent_unsupportedPresent() { + try { + getMap().COMPUTE_IF_PRESENT(k0(), (k, v) -> v3()); + fail("Expected UnsupportedOperationException"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapComputeTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapComputeTester.template index 9705180..70afb64 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapComputeTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapComputeTester.template @@ -1,145 +1,145 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; -#endignore - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; - -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ -#ignore - @MapFeature.Require({ SUPPORTS_PUT, SUPPORTS_REMOVE }) -#endignore - public void testCompute_absentToPresent() { - assertEquals("Map.COMPUTE(absent, functionReturningValue) should return value", v3(), - getMap().COMPUTE(k3(), (k, v) -> { - assertEquals(k3(), k); - assertEquals(INVALID_VALUE, v); - return v3(); - })); - expectAdded(e3()); - assertEquals(getNumElements() + 1, getMap().size()); - } - -#ignore - @MapFeature.Require({ SUPPORTS_PUT, SUPPORTS_REMOVE }) -#endignore - public void testCompute_absentToAbsent() { - assertEquals("Map.COMPUTE(absent, functionReturningNull) should return INVALID_VALUE", INVALID_VALUE, getMap().COMPUTE(k3(), (k, v) -> { - assertEquals(k3(), k); - assertEquals(INVALID_VALUE, v); - return INVALID_VALUE; - })); - expectUnchanged(); - assertEquals(getNumElements(), getMap().size()); - } - -#ignore - @MapFeature.Require({ SUPPORTS_PUT, SUPPORTS_REMOVE }) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testCompute_presentToPresent() { - assertEquals("Map.COMPUTE(present, functionReturningValue) should return new value", v3(), - getMap().COMPUTE(k0(), (k, v) -> { - assertEquals(k0(), k); - assertEquals(v0(), v); - return v3(); - })); - expectReplacement(entry(k0(), v3())); - assertEquals(getNumElements(), getMap().size()); - } - -#ignore - @MapFeature.Require({ SUPPORTS_PUT, SUPPORTS_REMOVE }) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testCompute_presentToAbsent() { - assertEquals("Map.COMPUTE(present, functionReturningNull) should return INVALID_VALUE", INVALID_VALUE, getMap().COMPUTE(k0(), (k, v) -> { - assertEquals(k0(), k); - assertEquals(v0(), v); - return INVALID_VALUE; - })); - expectMissing(e0()); - expectMissingKeys(k0()); - assertEquals(getNumElements() - 1, getMap().size()); - } - - static class ExpectedException extends RuntimeException { - private static final long serialVersionUID = 1L; - } - -#ignore - @MapFeature.Require({ SUPPORTS_PUT, SUPPORTS_REMOVE }) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testCompute_presentFunctionThrows() { - try { - getMap().COMPUTE(k0(), (k, v) -> { - assertEquals(k0(), k); - assertEquals(v0(), v); - throw new ExpectedException(); - }); - fail("Expected ExpectedException"); - } catch (ExpectedException expected) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require({ SUPPORTS_PUT, SUPPORTS_REMOVE }) -#endignore - public void testCompute_absentFunctionThrows() { - try { - getMap().COMPUTE(k3(), (k, v) -> { - assertEquals(k3(), k); - assertEquals(INVALID_VALUE, v); - throw new ExpectedException(); - }); - fail("Expected ExpectedException"); - } catch (ExpectedException expected) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_REMOVE) -#endignore - public void testCompute_removeAbsent() { - try { - getMap().COMPUTE(k3(), (k, v) -> { - assertEquals(k3(), k); - assertEquals(INVALID_VALUE, v); - return INVALID_VALUE; - }); - fail("Expected UnsupportedOperationException"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) -#endignore - public void testCompute_putAbsent() { - try { - getMap().COMPUTE(k3(), (k, v) -> { - assertEquals(k3(), k); - assertEquals(INVALID_VALUE, v); - return INVALID_VALUE; - }); - fail("Expected UnsupportedOperationException"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; +#endignore + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#ignore + @MapFeature.Require({ SUPPORTS_PUT, SUPPORTS_REMOVE }) +#endignore + public void testCompute_absentToPresent() { + assertEquals("Map.COMPUTE(absent, functionReturningValue) should return value", v3(), + getMap().COMPUTE(k3(), (k, v) -> { + assertEquals(k3(), k); + assertEquals(INVALID_VALUE, v); + return v3(); + })); + expectAdded(e3()); + assertEquals(getNumElements() + 1, getMap().size()); + } + +#ignore + @MapFeature.Require({ SUPPORTS_PUT, SUPPORTS_REMOVE }) +#endignore + public void testCompute_absentToAbsent() { + assertEquals("Map.COMPUTE(absent, functionReturningNull) should return INVALID_VALUE", INVALID_VALUE, getMap().COMPUTE(k3(), (k, v) -> { + assertEquals(k3(), k); + assertEquals(INVALID_VALUE, v); + return INVALID_VALUE; + })); + expectUnchanged(); + assertEquals(getNumElements(), getMap().size()); + } + +#ignore + @MapFeature.Require({ SUPPORTS_PUT, SUPPORTS_REMOVE }) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testCompute_presentToPresent() { + assertEquals("Map.COMPUTE(present, functionReturningValue) should return new value", v3(), + getMap().COMPUTE(k0(), (k, v) -> { + assertEquals(k0(), k); + assertEquals(v0(), v); + return v3(); + })); + expectReplacement(entry(k0(), v3())); + assertEquals(getNumElements(), getMap().size()); + } + +#ignore + @MapFeature.Require({ SUPPORTS_PUT, SUPPORTS_REMOVE }) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testCompute_presentToAbsent() { + assertEquals("Map.COMPUTE(present, functionReturningNull) should return INVALID_VALUE", INVALID_VALUE, getMap().COMPUTE(k0(), (k, v) -> { + assertEquals(k0(), k); + assertEquals(v0(), v); + return INVALID_VALUE; + })); + expectMissing(e0()); + expectMissingKeys(k0()); + assertEquals(getNumElements() - 1, getMap().size()); + } + + static class ExpectedException extends RuntimeException { + private static final long serialVersionUID = 1L; + } + +#ignore + @MapFeature.Require({ SUPPORTS_PUT, SUPPORTS_REMOVE }) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testCompute_presentFunctionThrows() { + try { + getMap().COMPUTE(k0(), (k, v) -> { + assertEquals(k0(), k); + assertEquals(v0(), v); + throw new ExpectedException(); + }); + fail("Expected ExpectedException"); + } catch (ExpectedException expected) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require({ SUPPORTS_PUT, SUPPORTS_REMOVE }) +#endignore + public void testCompute_absentFunctionThrows() { + try { + getMap().COMPUTE(k3(), (k, v) -> { + assertEquals(k3(), k); + assertEquals(INVALID_VALUE, v); + throw new ExpectedException(); + }); + fail("Expected ExpectedException"); + } catch (ExpectedException expected) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_REMOVE) +#endignore + public void testCompute_removeAbsent() { + try { + getMap().COMPUTE(k3(), (k, v) -> { + assertEquals(k3(), k); + assertEquals(INVALID_VALUE, v); + return INVALID_VALUE; + }); + fail("Expected UnsupportedOperationException"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) +#endignore + public void testCompute_putAbsent() { + try { + getMap().COMPUTE(k3(), (k, v) -> { + assertEquals(k3(), k); + assertEquals(INVALID_VALUE, v); + return INVALID_VALUE; + }); + fail("Expected UnsupportedOperationException"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapConstructorTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapConstructorTester.template index 14d0461..5106c9f 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapConstructorTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapConstructorTester.template @@ -1,249 +1,249 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.Map; -#if VALUE_OBJECT && !TYPE_OBJECT -import java.util.Objects; -#endif -import java.util.function.BiFunction; -import java.util.function.Function; -import java.util.function.IntFunction; -import java.util.function.Supplier; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.Ignore; -import junit.framework.TestCase; - -#if !VALUE_OBJECT -import speiger.src.collections.VALUE_PACKAGE.utils.VALUE_ARRAYS; -#endif -import speiger.src.collections.PACKAGE.maps.impl.hash.LINKED_HASH_MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -#if !SAME_TYPE && !TYPE_OBJECT -import speiger.src.collections.PACKAGE.utils.ARRAYS; -#endif -import speiger.src.collections.utils.ITrimmable; - -@Ignore -@SuppressWarnings("javadoc") -public abstract class FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_GENERIC_TYPE extends TestCase -{ - protected Supplier simpleConstructor; - protected IntFunction sizeConstructor; - protected BiFunction pArrayConstructor; -#if !TYPE_OBJECT || !VALUE_OBJECT - protected BiFunction arrayConstructor; -#endif - protected Function, MAP KEY_VALUE_GENERIC_TYPE> mapConstructor; - protected Function pMapConstructor; - protected KEY_TYPE[] keys = createKeyElements(); - protected VALUE_TYPE[] values = createValueElements(); - - protected void setSimpleConstructor(Supplier simpleConstructor) { - this.simpleConstructor = simpleConstructor; - } - - protected void setSizeConstructor(IntFunction sizeConstructor) { - this.sizeConstructor = sizeConstructor; - } - - protected void setPArrayConstructor(BiFunction pArrayConstructor) { - this.pArrayConstructor = pArrayConstructor; - } - -#if !TYPE_OBJECT || !VALUE_OBJECT - protected void setArrayConstructor(BiFunction arrayConstructor) { - this.arrayConstructor = arrayConstructor; - } - -#endif - protected void setMapConstructor(Function, MAP KEY_VALUE_GENERIC_TYPE> mapConstructor) { - this.mapConstructor = mapConstructor; - } - - protected void setPMapConstructor(Function pMapConstructor) { - this.pMapConstructor = pMapConstructor; - } - - @Test - public void testPrimitiveArrayConstructor() { - if(pArrayConstructor == null) return; - Assert.assertTrue(pArrayConstructor.apply(keys, values) != null); - } - - @Test - public void testPrimitiveArrayConstructorBadlySized() { - if(pArrayConstructor == null) return; - try { - pArrayConstructor.apply(Arrays.copyOf(keys, 50), values); - Assert.fail("This should throw IllegalStateException"); - } - catch(IllegalStateException | IllegalArgumentException e) { - } - } - -#if !TYPE_OBJECT || !VALUE_OBJECT - @Test - public void testArrayConstructor() { - if(arrayConstructor == null) return; -#if TYPE_OBJECT - Assert.assertTrue(arrayConstructor.apply(keys, VALUE_ARRAYS.wrap(values)) != null); -#else if VALUE_OBJECT - Assert.assertTrue(arrayConstructor.apply(ARRAYS.wrap(keys), values) != null); -#else - Assert.assertTrue(arrayConstructor.apply(ARRAYS.wrap(keys), VALUE_ARRAYS.wrap(values)) != null); -#endif - } - - @Test - public void testArrayConstructorBadlySized() { - if(arrayConstructor == null) return; - try { -#if TYPE_OBJECT - arrayConstructor.apply(Arrays.copyOf(keys, 50), VALUE_ARRAYS.wrap(values)); -#else if VALUE_OBJECT - arrayConstructor.apply(ARRAYS.wrap(Arrays.copyOf(keys, 50)), values); -#else - arrayConstructor.apply(ARRAYS.wrap(Arrays.copyOf(keys, 50)), VALUE_ARRAYS.wrap(values)); -#endif - Assert.fail("This should throw IllegalStateException"); - } - catch(IllegalStateException | IllegalArgumentException e) { - } - } - -#endif - @Test - public void testPrimitiveMapsConstructor() { - if(pMapConstructor == null) return; - Assert.assertTrue(pMapConstructor.apply(new LINKED_HASH_MAPKV_BRACES(keys, values)) != null); - } - - @Test - public void testMapsConstructor() { - if(mapConstructor == null) return; - Assert.assertTrue(mapConstructor.apply(new LinkedHashMap<>(new LINKED_HASH_MAPKV_BRACES(keys, values))) != null); - } - - @Test - public void testSimpleConstructor() { - if(simpleConstructor == null) return; - Assert.assertTrue(simpleConstructor.get() != null); - } - - @Test - public void testSizeConstructor_empty() { - if(sizeConstructor == null) return; - Assert.assertTrue(sizeConstructor.apply(0) != null); - } - - @Test - public void testSizeConstructor_smallSize() { - if(sizeConstructor == null) return; - Assert.assertTrue(sizeConstructor.apply(32) != null); - } - - @Test - public void testSizeConstructor_largeSize() { - if(sizeConstructor == null) return; - Assert.assertTrue(sizeConstructor.apply(25212) != null); - } - - @Test - public void testRehash() { - if(sizeConstructor == null) return; - try - { - MAP KEY_VALUE_GENERIC_TYPE map = sizeConstructor.apply(0); - if(map instanceof ITrimmable) { - ITrimmable trim = (ITrimmable)map; - map.putAll(keys, values); - map.clear(); - Assert.assertTrue(trim.trim()); - Assert.assertFalse(trim.trim()); - map.putAll(keys, values); - trim.clearAndTrim(); - map.putAll(keys, values); - trim.clearAndTrim(Short.MAX_VALUE); - } - } - catch(UnsupportedOperationException e) { - //Ignore thats fine - } - } - -#if !TYPE_OBJECT - public void testHashCollisions() { - if(simpleConstructor == null) return; - MAP KEY_VALUE_GENERIC_TYPE map = simpleConstructor.get(); - int value = fillMap(map); - for(int i = value;i>=0;i-=16) { - Assert.assertTrue(VALUE_EQUALS(values[i], map.remove(keys[i]))); - } - value = fillMap(map); - for(int i = value;i>=0;i-=16) { - Assert.assertTrue(map.remove(keys[i], values[i])); - } - value = fillMap(map); - for(int i = value;i>=0;i-=16) { - Assert.assertTrue(map.remove(KEY_TO_OBJ(keys[i]), VALUE_TO_OBJ(values[i]))); - } - } - - private int fillMap(MAP KEY_VALUE_GENERIC_TYPE map) { - int result = 0; - for(int i = 2;i<100;i+=16) { - map.put(keys[i], values[i]); - result = i; - } - return result; - } - -#endif - @Test - public void testSizeConstructor_InvalidSize() { - if(sizeConstructor == null) return; - try { - sizeConstructor.apply(-1); - Assert.fail("When Inputted Size is negative this should crash"); - } - catch(IllegalStateException e) { - } - } - -#if TYPE_OBJECT - protected abstract KEY_TYPE[] createKeyElements(); - -#else - protected KEY_TYPE[] createKeyElements() { - KEY_TYPE[] keys = NEW_KEY_ARRAY(100); - for(int i = 0;i<100;i++) { - keys[i] = (KEY_TYPE)i; - } - return keys; - } -#endif - -#if VALUE_OBJECT - protected abstract VALUE_TYPE[] createValueElements(); - -#else - protected VALUE_TYPE[] createValueElements() { - VALUE_TYPE[] values = NEW_VALUE_ARRAY(getSize()); - for(int i = 0,m=getSize();i simpleConstructor; + protected IntFunction sizeConstructor; + protected BiFunction pArrayConstructor; +#if !TYPE_OBJECT || !VALUE_OBJECT + protected BiFunction arrayConstructor; +#endif + protected Function, MAP KEY_VALUE_GENERIC_TYPE> mapConstructor; + protected Function pMapConstructor; + protected KEY_TYPE[] keys = createKeyElements(); + protected VALUE_TYPE[] values = createValueElements(); + + protected void setSimpleConstructor(Supplier simpleConstructor) { + this.simpleConstructor = simpleConstructor; + } + + protected void setSizeConstructor(IntFunction sizeConstructor) { + this.sizeConstructor = sizeConstructor; + } + + protected void setPArrayConstructor(BiFunction pArrayConstructor) { + this.pArrayConstructor = pArrayConstructor; + } + +#if !TYPE_OBJECT || !VALUE_OBJECT + protected void setArrayConstructor(BiFunction arrayConstructor) { + this.arrayConstructor = arrayConstructor; + } + +#endif + protected void setMapConstructor(Function, MAP KEY_VALUE_GENERIC_TYPE> mapConstructor) { + this.mapConstructor = mapConstructor; + } + + protected void setPMapConstructor(Function pMapConstructor) { + this.pMapConstructor = pMapConstructor; + } + + @Test + public void testPrimitiveArrayConstructor() { + if(pArrayConstructor == null) return; + Assert.assertTrue(pArrayConstructor.apply(keys, values) != null); + } + + @Test + public void testPrimitiveArrayConstructorBadlySized() { + if(pArrayConstructor == null) return; + try { + pArrayConstructor.apply(Arrays.copyOf(keys, 50), values); + Assert.fail("This should throw IllegalStateException"); + } + catch(IllegalStateException | IllegalArgumentException e) { + } + } + +#if !TYPE_OBJECT || !VALUE_OBJECT + @Test + public void testArrayConstructor() { + if(arrayConstructor == null) return; +#if TYPE_OBJECT + Assert.assertTrue(arrayConstructor.apply(keys, VALUE_ARRAYS.wrap(values)) != null); +#else if VALUE_OBJECT + Assert.assertTrue(arrayConstructor.apply(ARRAYS.wrap(keys), values) != null); +#else + Assert.assertTrue(arrayConstructor.apply(ARRAYS.wrap(keys), VALUE_ARRAYS.wrap(values)) != null); +#endif + } + + @Test + public void testArrayConstructorBadlySized() { + if(arrayConstructor == null) return; + try { +#if TYPE_OBJECT + arrayConstructor.apply(Arrays.copyOf(keys, 50), VALUE_ARRAYS.wrap(values)); +#else if VALUE_OBJECT + arrayConstructor.apply(ARRAYS.wrap(Arrays.copyOf(keys, 50)), values); +#else + arrayConstructor.apply(ARRAYS.wrap(Arrays.copyOf(keys, 50)), VALUE_ARRAYS.wrap(values)); +#endif + Assert.fail("This should throw IllegalStateException"); + } + catch(IllegalStateException | IllegalArgumentException e) { + } + } + +#endif + @Test + public void testPrimitiveMapsConstructor() { + if(pMapConstructor == null) return; + Assert.assertTrue(pMapConstructor.apply(new LINKED_HASH_MAPKV_BRACES(keys, values)) != null); + } + + @Test + public void testMapsConstructor() { + if(mapConstructor == null) return; + Assert.assertTrue(mapConstructor.apply(new LinkedHashMap<>(new LINKED_HASH_MAPKV_BRACES(keys, values))) != null); + } + + @Test + public void testSimpleConstructor() { + if(simpleConstructor == null) return; + Assert.assertTrue(simpleConstructor.get() != null); + } + + @Test + public void testSizeConstructor_empty() { + if(sizeConstructor == null) return; + Assert.assertTrue(sizeConstructor.apply(0) != null); + } + + @Test + public void testSizeConstructor_smallSize() { + if(sizeConstructor == null) return; + Assert.assertTrue(sizeConstructor.apply(32) != null); + } + + @Test + public void testSizeConstructor_largeSize() { + if(sizeConstructor == null) return; + Assert.assertTrue(sizeConstructor.apply(25212) != null); + } + + @Test + public void testRehash() { + if(sizeConstructor == null) return; + try + { + MAP KEY_VALUE_GENERIC_TYPE map = sizeConstructor.apply(0); + if(map instanceof ITrimmable) { + ITrimmable trim = (ITrimmable)map; + map.putAll(keys, values); + map.clear(); + Assert.assertTrue(trim.trim()); + Assert.assertFalse(trim.trim()); + map.putAll(keys, values); + trim.clearAndTrim(); + map.putAll(keys, values); + trim.clearAndTrim(Short.MAX_VALUE); + } + } + catch(UnsupportedOperationException e) { + //Ignore thats fine + } + } + +#if !TYPE_OBJECT + public void testHashCollisions() { + if(simpleConstructor == null) return; + MAP KEY_VALUE_GENERIC_TYPE map = simpleConstructor.get(); + int value = fillMap(map); + for(int i = value;i>=0;i-=16) { + Assert.assertTrue(VALUE_EQUALS(values[i], map.remove(keys[i]))); + } + value = fillMap(map); + for(int i = value;i>=0;i-=16) { + Assert.assertTrue(map.remove(keys[i], values[i])); + } + value = fillMap(map); + for(int i = value;i>=0;i-=16) { + Assert.assertTrue(map.remove(KEY_TO_OBJ(keys[i]), VALUE_TO_OBJ(values[i]))); + } + } + + private int fillMap(MAP KEY_VALUE_GENERIC_TYPE map) { + int result = 0; + for(int i = 2;i<100;i+=16) { + map.put(keys[i], values[i]); + result = i; + } + return result; + } + +#endif + @Test + public void testSizeConstructor_InvalidSize() { + if(sizeConstructor == null) return; + try { + sizeConstructor.apply(-1); + Assert.fail("When Inputted Size is negative this should crash"); + } + catch(IllegalStateException e) { + } + } + +#if TYPE_OBJECT + protected abstract KEY_TYPE[] createKeyElements(); + +#else + protected KEY_TYPE[] createKeyElements() { + KEY_TYPE[] keys = NEW_KEY_ARRAY(100); + for(int i = 0;i<100;i++) { + keys[i] = (KEY_TYPE)i; + } + return keys; + } +#endif + +#if VALUE_OBJECT + protected abstract VALUE_TYPE[] createValueElements(); + +#else + protected VALUE_TYPE[] createValueElements() { + VALUE_TYPE[] values = NEW_VALUE_ARRAY(getSize()); + for(int i = 0,m=getSize();i(e0()))); - } - - public void testContains_no() { - assertFalse("contains(notPresent) should return false", getMap().ENTRY_SET().contains(e3())); - } - - public void testContainsObject_no() { - assertFalse("contains(notPresent) should return false", getMap().ENTRY_SET().contains(new AbstractMap.SimpleEntry<>(e3()))); - } - -#ignore - @CollectionSize.Require(ONE) -#endignore - public void testContainsEntry_yes() { - MAP.Entry KEY_VALUE_GENERIC_TYPE value = getMap().ENTRY_SET().iterator().next(); - assertTrue("MAP.Entry.equals() should return true", value.equals(e0())); - } - -#ignore - @CollectionSize.Require(ONE) -#endignore - public void testContainsEntryObject_yes() { - MAP.Entry KEY_VALUE_GENERIC_TYPE value = getMap().ENTRY_SET().iterator().next(); - assertTrue("MAP.Entry.equals() should return true", value.equals(new AbstractMap.SimpleEntry<>(e0()))); - } - -#ignore - @CollectionSize.Require(ONE) -#endignore - public void testContainsEntry_no() { - MAP.Entry KEY_VALUE_GENERIC_TYPE value = getMap().ENTRY_SET().iterator().next(); - assertFalse("MAP.Entry.equals() should return false", value.equals(e3())); - } - -#ignore - @CollectionSize.Require(ONE) -#endignore - public void testContainsEntryObject_no() { - MAP.Entry KEY_VALUE_GENERIC_TYPE value = getMap().ENTRY_SET().iterator().next(); - assertFalse("MAP.Entry.equals() should return false", value.equals(new AbstractMap.SimpleEntry<>(e3()))); - } +package speiger.src.testers.PACKAGE.tests.maps; + +import java.util.AbstractMap; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.CollectionSize.ONE; +#endignore + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapContainsTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#ignore + @CollectionSize.Require(absent = ZERO) +#endignore + public void testContains_yes() { + assertTrue("contains(present) should return true", getMap().ENTRY_SET().contains(e0())); + } + +#ignore + @CollectionSize.Require(absent = ZERO) +#endignore + public void testContainsObject_yes() { + assertTrue("contains(present) should return true", getMap().ENTRY_SET().contains(new AbstractMap.SimpleEntry<>(e0()))); + } + + public void testContains_no() { + assertFalse("contains(notPresent) should return false", getMap().ENTRY_SET().contains(e3())); + } + + public void testContainsObject_no() { + assertFalse("contains(notPresent) should return false", getMap().ENTRY_SET().contains(new AbstractMap.SimpleEntry<>(e3()))); + } + +#ignore + @CollectionSize.Require(ONE) +#endignore + public void testContainsEntry_yes() { + MAP.Entry KEY_VALUE_GENERIC_TYPE value = getMap().ENTRY_SET().iterator().next(); + assertTrue("MAP.Entry.equals() should return true", value.equals(e0())); + } + +#ignore + @CollectionSize.Require(ONE) +#endignore + public void testContainsEntryObject_yes() { + MAP.Entry KEY_VALUE_GENERIC_TYPE value = getMap().ENTRY_SET().iterator().next(); + assertTrue("MAP.Entry.equals() should return true", value.equals(new AbstractMap.SimpleEntry<>(e0()))); + } + +#ignore + @CollectionSize.Require(ONE) +#endignore + public void testContainsEntry_no() { + MAP.Entry KEY_VALUE_GENERIC_TYPE value = getMap().ENTRY_SET().iterator().next(); + assertFalse("MAP.Entry.equals() should return false", value.equals(e3())); + } + +#ignore + @CollectionSize.Require(ONE) +#endignore + public void testContainsEntryObject_no() { + MAP.Entry KEY_VALUE_GENERIC_TYPE value = getMap().ENTRY_SET().iterator().next(); + assertFalse("MAP.Entry.equals() should return false", value.equals(new AbstractMap.SimpleEntry<>(e3()))); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapContainsValueTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapContainsValueTester.template index e311379..3a4db10 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapContainsValueTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapContainsValueTester.template @@ -1,49 +1,49 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapContainsValueTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ -#ignore - @CollectionSize.Require(absent = ZERO) -#endignore - public void testContains_yes() { - assertTrue("containsValue(present) should return true", getMap().containsValue(v0())); - } - - public void testContains_no() { - assertFalse("containsValue(notPresent) should return false", getMap().containsValue(v3())); - } - -#ignore - @CollectionSize.Require(absent = ZERO) -#endignore - public void testContainsObject_yes() { - assertTrue("containsValue(present) should return true", getMap().containsValue(VALUE_TO_OBJ(v0()))); - } - -#if !VALUE_BOOLEAN - public void testContainsObject_no() { - assertFalse("containsValue(notPresent) should return false", getMap().containsValue(VALUE_TO_OBJ(v3()))); - } - -#if !VALUE_OBJECT -#ignore - @CollectionSize.Require(absent = ZERO) -#endignore - public void testContains_null() { - assertFalse("containsValue(present) should return false", getMap().containsValue(null)); - } -#endif -#endif -} +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapContainsValueTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#ignore + @CollectionSize.Require(absent = ZERO) +#endignore + public void testContains_yes() { + assertTrue("containsValue(present) should return true", getMap().containsValue(v0())); + } + + public void testContains_no() { + assertFalse("containsValue(notPresent) should return false", getMap().containsValue(v3())); + } + +#ignore + @CollectionSize.Require(absent = ZERO) +#endignore + public void testContainsObject_yes() { + assertTrue("containsValue(present) should return true", getMap().containsValue(VALUE_TO_OBJ(v0()))); + } + +#if !VALUE_BOOLEAN + public void testContainsObject_no() { + assertFalse("containsValue(notPresent) should return false", getMap().containsValue(VALUE_TO_OBJ(v3()))); + } + +#if !VALUE_OBJECT +#ignore + @CollectionSize.Require(absent = ZERO) +#endignore + public void testContains_null() { + assertFalse("containsValue(present) should return false", getMap().containsValue(null)); + } +#endif +#endif +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapCopyTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapCopyTester.template index c45957c..0804d87 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapCopyTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapCopyTester.template @@ -1,38 +1,38 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -import org.junit.Assert; -import org.junit.Ignore; - -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.collections.PACKAGE.utils.maps.MAPS; -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; -import speiger.src.testers.utils.SpecialFeature; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapCopyTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ -#ignore - @SpecialFeature.Require(SpecialFeature.COPYING) -#endignore - public void testEquals() { - MAP KEY_VALUE_GENERIC_TYPE copy = container.copy(); - if(!(copy instanceof MAPS.EmptyMap)) { - Assert.assertFalse("Copied Map shouldn't match", copy == container); - } - Assert.assertTrue("Copied Map contents should match", copy.equals(container)); - } - -#ignore - @SpecialFeature.Require(absent = SpecialFeature.COPYING) -#endignore - public void testEqualsFail() { - try { - assertNull(container.copy()); - fail("If Copying isn't supported it should throw a UnsupportedOperationException"); - } - catch(UnsupportedOperationException e) { - //Success - } - } -} +package speiger.src.testers.PACKAGE.tests.maps; + +import org.junit.Assert; +import org.junit.Ignore; + +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.collections.PACKAGE.utils.maps.MAPS; +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; +import speiger.src.testers.utils.SpecialFeature; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapCopyTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#ignore + @SpecialFeature.Require(SpecialFeature.COPYING) +#endignore + public void testEquals() { + MAP KEY_VALUE_GENERIC_TYPE copy = container.copy(); + if(!(copy instanceof MAPS.EmptyMap)) { + Assert.assertFalse("Copied Map shouldn't match", copy == container); + } + Assert.assertTrue("Copied Map contents should match", copy.equals(container)); + } + +#ignore + @SpecialFeature.Require(absent = SpecialFeature.COPYING) +#endignore + public void testEqualsFail() { + try { + assertNull(container.copy()); + fail("If Copying isn't supported it should throw a UnsupportedOperationException"); + } + catch(UnsupportedOperationException e) { + //Success + } + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapCreatorTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapCreatorTester.template index 752668e..7bc7273 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapCreatorTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapCreatorTester.template @@ -1,40 +1,40 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.MapFeature.REJECTS_DUPLICATES_AT_CREATION; -#endignore - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; - -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.collections.objects.lists.ObjectArrayList; -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapCreatorTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ -#ignore - @MapFeature.Require(absent = REJECTS_DUPLICATES_AT_CREATION) - @CollectionSize.Require(absent = { ZERO, ONE }) -#endignore - public void testCreateWithDuplicates_nonNullDuplicatesNotRejected() { - expectFirstRemoved(getEntriesMultipleNonNullKeys()); - } - - private MAP.Entry KEY_VALUE_GENERIC_TYPE[] getEntriesMultipleNonNullKeys() { - MAP.Entry KEY_VALUE_GENERIC_TYPE[] entries = createSamplesArray(); - entries[0] = entry(k1(), v0()); - return entries; - } - - private void expectFirstRemoved(MAP.Entry KEY_VALUE_GENERIC_TYPE[] entries) { - resetMap(entries); - expectContents(ObjectArrayList.wrap(entries).subList(1, getNumElements())); - } -} +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.MapFeature.REJECTS_DUPLICATES_AT_CREATION; +#endignore + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.collections.objects.lists.ObjectArrayList; +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapCreatorTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#ignore + @MapFeature.Require(absent = REJECTS_DUPLICATES_AT_CREATION) + @CollectionSize.Require(absent = { ZERO, ONE }) +#endignore + public void testCreateWithDuplicates_nonNullDuplicatesNotRejected() { + expectFirstRemoved(getEntriesMultipleNonNullKeys()); + } + + private MAP.Entry KEY_VALUE_GENERIC_TYPE[] getEntriesMultipleNonNullKeys() { + MAP.Entry KEY_VALUE_GENERIC_TYPE[] entries = createSamplesArray(); + entries[0] = entry(k1(), v0()); + return entries; + } + + private void expectFirstRemoved(MAP.Entry KEY_VALUE_GENERIC_TYPE[] entries) { + resetMap(entries); + expectContents(ObjectArrayList.wrap(entries).subList(1, getNumElements())); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapEntrySetTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapEntrySetTester.template index c08d602..5d6a9f1 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapEntrySetTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapEntrySetTester.template @@ -1,56 +1,56 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ITERATOR_REMOVE; -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; -#endignore - -import java.util.Iterator; -import java.util.Set; -#if TYPE_OBJECT -import java.util.Objects; -#endif - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; - -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapEntrySetTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ -#ignore - @CollectionSize.Require(ONE) - @CollectionFeature.Require(SUPPORTS_ITERATOR_REMOVE) -#endignore - public void testEntrySetIteratorRemove() { - Set entrySet = getMap().ENTRY_SET(); - Iterator entryItr = entrySet.iterator(); - assertEquals(e0(), entryItr.next()); - entryItr.remove(); - assertTrue(getMap().isEmpty()); - assertFalse(entrySet.contains(e0())); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testSetValue() { - for (MAP.Entry KEY_VALUE_GENERIC_TYPE entry : getMap().ENTRY_SET()) { - if (KEY_EQUALS(entry.ENTRY_KEY(), k0())) { - assertEquals("entry.setValue() should return the old value", v0(), entry.setValue(v3())); - break; - } - } - expectReplacement(entry(k0(), v3())); - } - +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ITERATOR_REMOVE; +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; +#endignore + +import java.util.Iterator; +import java.util.Set; +#if TYPE_OBJECT +import java.util.Objects; +#endif + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapEntrySetTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#ignore + @CollectionSize.Require(ONE) + @CollectionFeature.Require(SUPPORTS_ITERATOR_REMOVE) +#endignore + public void testEntrySetIteratorRemove() { + Set entrySet = getMap().ENTRY_SET(); + Iterator entryItr = entrySet.iterator(); + assertEquals(e0(), entryItr.next()); + entryItr.remove(); + assertTrue(getMap().isEmpty()); + assertFalse(entrySet.contains(e0())); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testSetValue() { + for (MAP.Entry KEY_VALUE_GENERIC_TYPE entry : getMap().ENTRY_SET()) { + if (KEY_EQUALS(entry.ENTRY_KEY(), k0())) { + assertEquals("entry.setValue() should return the old value", v0(), entry.setValue(v3())); + break; + } + } + expectReplacement(entry(k0(), v3())); + } + } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapEqualsTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapEqualsTester.template index 4d0df87..fb1324d 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapEqualsTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapEqualsTester.template @@ -1,95 +1,95 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -import java.util.AbstractMap; - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.maps.impl.hash.HASH_MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.collections.objects.collections.ObjectCollection; -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; -import speiger.src.testers.objects.utils.ObjectHelpers; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapEqualsTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ - public void testEquals_otherMapWithSameEntries() { - assertTrue("A Map should equal any other Map containing the same entries.", getMap().equals(newHashMap(getSampleEntries()))); - } - -#ignore - @CollectionSize.Require(absent = CollectionSize.ZERO) -#endignore - public void testEquals_otherMapWithDifferentEntries() { - MAP KEY_VALUE_GENERIC_TYPE other = newHashMap(getSampleEntries(getNumEntries() - 1)); - other.put(k3(), v3()); - assertFalse("A Map should not equal another Map containing different entries.", getMap().equals(other)); - } - -#ignore - @CollectionSize.Require(absent = CollectionSize.ZERO) -#endignore - public void testEquals_smallerMap() { - ObjectCollection fewerEntries = getSampleEntries(getNumEntries() - 1); - assertFalse("Maps of different sizes should not be equal.", getMap().equals(newHashMap(fewerEntries))); - } - - public void testEquals_largerMap() { - ObjectCollection moreEntries = getSampleEntries(getNumEntries() + 1); - assertFalse("Maps of different sizes should not be equal.", getMap().equals(newHashMap(moreEntries))); - } - - public void testEquals_list() { - assertFalse("A List should never equal a Map.", getMap().equals(ObjectHelpers.copyToList(getMap().ENTRY_SET()))); - } - -#ignore - @CollectionSize.Require(CollectionSize.ONE) -#endignore - public void testEquals_EntryMatches() { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = e0(); - assertEquals("The Entries should match", entry, getMap().ENTRY_SET().iterator().next()); - } - -#ignore - @CollectionSize.Require(CollectionSize.ONE) -#endignore - public void testEquals_EntryMatchesObject() { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = e0(); - assertEquals("The Entries should match", new AbstractMap.SimpleEntry<>(entry), getMap().ENTRY_SET().iterator().next()); - } - -#ignore - @CollectionSize.Require(CollectionSize.ONE) -#endignore - public void testEquals_EntryNotMatches() { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = e3(); - assertFalse("The Entries should match", getMap().ENTRY_SET().iterator().next().equals(entry)); - } - -#ignore - @CollectionSize.Require(CollectionSize.ONE) -#endignore - public void testEquals_EntryNotMatchesObject() { - MAP.Entry KEY_VALUE_GENERIC_TYPE entry = e3(); - assertFalse("The Entries should match", getMap().ENTRY_SET().iterator().next().equals(new AbstractMap.SimpleEntry<>(entry))); - } - -#ignore - @CollectionSize.Require(CollectionSize.ONE) -#endignore - public void testEquals_EntryNotMatchingNull() { - assertFalse("The Entries should match", getMap().ENTRY_SET().iterator().next().equals(null)); - } - - private static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE newHashMap(ObjectCollection entries) { - MAP KEY_VALUE_GENERIC_TYPE map = new HASH_MAPKV_BRACES(); - for (MAP.Entry KEY_VALUE_GENERIC_TYPE entry : entries) { - map.put(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); - } - return map; - } -} +package speiger.src.testers.PACKAGE.tests.maps; + +import java.util.AbstractMap; + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.maps.impl.hash.HASH_MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.collections.objects.collections.ObjectCollection; +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; +import speiger.src.testers.objects.utils.ObjectHelpers; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapEqualsTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ + public void testEquals_otherMapWithSameEntries() { + assertTrue("A Map should equal any other Map containing the same entries.", getMap().equals(newHashMap(getSampleEntries()))); + } + +#ignore + @CollectionSize.Require(absent = CollectionSize.ZERO) +#endignore + public void testEquals_otherMapWithDifferentEntries() { + MAP KEY_VALUE_GENERIC_TYPE other = newHashMap(getSampleEntries(getNumEntries() - 1)); + other.put(k3(), v3()); + assertFalse("A Map should not equal another Map containing different entries.", getMap().equals(other)); + } + +#ignore + @CollectionSize.Require(absent = CollectionSize.ZERO) +#endignore + public void testEquals_smallerMap() { + ObjectCollection fewerEntries = getSampleEntries(getNumEntries() - 1); + assertFalse("Maps of different sizes should not be equal.", getMap().equals(newHashMap(fewerEntries))); + } + + public void testEquals_largerMap() { + ObjectCollection moreEntries = getSampleEntries(getNumEntries() + 1); + assertFalse("Maps of different sizes should not be equal.", getMap().equals(newHashMap(moreEntries))); + } + + public void testEquals_list() { + assertFalse("A List should never equal a Map.", getMap().equals(ObjectHelpers.copyToList(getMap().ENTRY_SET()))); + } + +#ignore + @CollectionSize.Require(CollectionSize.ONE) +#endignore + public void testEquals_EntryMatches() { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = e0(); + assertEquals("The Entries should match", entry, getMap().ENTRY_SET().iterator().next()); + } + +#ignore + @CollectionSize.Require(CollectionSize.ONE) +#endignore + public void testEquals_EntryMatchesObject() { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = e0(); + assertEquals("The Entries should match", new AbstractMap.SimpleEntry<>(entry), getMap().ENTRY_SET().iterator().next()); + } + +#ignore + @CollectionSize.Require(CollectionSize.ONE) +#endignore + public void testEquals_EntryNotMatches() { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = e3(); + assertFalse("The Entries should match", getMap().ENTRY_SET().iterator().next().equals(entry)); + } + +#ignore + @CollectionSize.Require(CollectionSize.ONE) +#endignore + public void testEquals_EntryNotMatchesObject() { + MAP.Entry KEY_VALUE_GENERIC_TYPE entry = e3(); + assertFalse("The Entries should match", getMap().ENTRY_SET().iterator().next().equals(new AbstractMap.SimpleEntry<>(entry))); + } + +#ignore + @CollectionSize.Require(CollectionSize.ONE) +#endignore + public void testEquals_EntryNotMatchingNull() { + assertFalse("The Entries should match", getMap().ENTRY_SET().iterator().next().equals(null)); + } + + private static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE newHashMap(ObjectCollection entries) { + MAP KEY_VALUE_GENERIC_TYPE map = new HASH_MAPKV_BRACES(); + for (MAP.Entry KEY_VALUE_GENERIC_TYPE entry : entries) { + map.put(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); + } + return map; + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapForEachTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapForEachTester.template index 73b771a..c48864d 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapForEachTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapForEachTester.template @@ -1,59 +1,59 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; -#endignore - -import java.util.List; - -import org.junit.Ignore; - -import com.google.common.collect.testing.Helpers; -import com.google.common.collect.testing.features.CollectionFeature; - -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.collections.PACKAGE.utils.maps.MAPS; -import speiger.src.collections.objects.lists.ObjectArrayList; -import speiger.src.collections.objects.lists.ObjectList; -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapForEachTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(KNOWN_ORDER) -#endignore - public void testForEachKnownOrder() { - ObjectList entries = new ObjectArrayList<>(); - getMap().forEach((k, v) -> entries.add(entry(k, v))); - assertEquals(getOrderedElements(), entries); - } - -#ignore - @CollectionFeature.Require(absent = KNOWN_ORDER) -#endignore - public void testForEachUnknownOrder() { - List entries = new ObjectArrayList<>(); - getMap().forEach((k, v) -> entries.add(entry(k, v))); - Helpers.assertEqualIgnoringOrder(getSampleEntries(), entries); - } - -#ignore - @CollectionFeature.Require(KNOWN_ORDER) -#endignore - public void testFastForEachKnownOrder() { - ObjectList entries = new ObjectArrayList<>(); - MAPS.fastForEach(getMap(), T -> entries.add(entry(T.ENTRY_KEY(), T.ENTRY_VALUE()))); - assertEquals(getOrderedElements(), entries); - } - -#ignore - @CollectionFeature.Require(absent = KNOWN_ORDER) -#endignore - public void testFastForEachUnknownOrder() { - List entries = new ObjectArrayList<>(); - MAPS.fastForEach(getMap(), T -> entries.add(entry(T.ENTRY_KEY(), T.ENTRY_VALUE()))); - Helpers.assertEqualIgnoringOrder(getSampleEntries(), entries); - } -} +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; +#endignore + +import java.util.List; + +import org.junit.Ignore; + +import com.google.common.collect.testing.Helpers; +import com.google.common.collect.testing.features.CollectionFeature; + +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.collections.PACKAGE.utils.maps.MAPS; +import speiger.src.collections.objects.lists.ObjectArrayList; +import speiger.src.collections.objects.lists.ObjectList; +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapForEachTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(KNOWN_ORDER) +#endignore + public void testForEachKnownOrder() { + ObjectList entries = new ObjectArrayList<>(); + getMap().forEach((k, v) -> entries.add(entry(k, v))); + assertEquals(getOrderedElements(), entries); + } + +#ignore + @CollectionFeature.Require(absent = KNOWN_ORDER) +#endignore + public void testForEachUnknownOrder() { + List entries = new ObjectArrayList<>(); + getMap().forEach((k, v) -> entries.add(entry(k, v))); + Helpers.assertEqualIgnoringOrder(getSampleEntries(), entries); + } + +#ignore + @CollectionFeature.Require(KNOWN_ORDER) +#endignore + public void testFastForEachKnownOrder() { + ObjectList entries = new ObjectArrayList<>(); + MAPS.fastForEach(getMap(), T -> entries.add(entry(T.ENTRY_KEY(), T.ENTRY_VALUE()))); + assertEquals(getOrderedElements(), entries); + } + +#ignore + @CollectionFeature.Require(absent = KNOWN_ORDER) +#endignore + public void testFastForEachUnknownOrder() { + List entries = new ObjectArrayList<>(); + MAPS.fastForEach(getMap(), T -> entries.add(entry(T.ENTRY_KEY(), T.ENTRY_VALUE()))); + Helpers.assertEqualIgnoringOrder(getSampleEntries(), entries); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapGetOrDefaultTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapGetOrDefaultTester.template index 0601f2a..3bee96b 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapGetOrDefaultTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapGetOrDefaultTester.template @@ -1,27 +1,27 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapGetOrDefaultTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ -#ignore - @CollectionSize.Require(absent = ZERO) -#endignore - public void testGetOrDefault_present() { - assertEquals("getOrDefault(present, def) should return the associated value", v0(), getMap().getOrDefault(k0(), v3())); - } - - public void testGetOrDefault_absent() { - assertEquals("getOrDefault(absent, def) should return the default value", v3(), getMap().getOrDefault(k3(), v3())); - } -} +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapGetOrDefaultTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#ignore + @CollectionSize.Require(absent = ZERO) +#endignore + public void testGetOrDefault_present() { + assertEquals("getOrDefault(present, def) should return the associated value", v0(), getMap().getOrDefault(k0(), v3())); + } + + public void testGetOrDefault_absent() { + assertEquals("getOrDefault(absent, def) should return the default value", v3(), getMap().getOrDefault(k3(), v3())); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapGetTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapGetTester.template index 68d26cf..d4f2df8 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapGetTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapGetTester.template @@ -1,40 +1,40 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapGetTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ -#ignore - @CollectionSize.Require(absent = ZERO) -#endignore - public void testGet_yes() { - assertEquals("get(present) should return the associated value", v0(), get(k0())); - } - - public void testGet_no() { - assertEquals("get(notPresent) should return INVALID_VALUE", INVALID_VALUE, get(k3())); - } - -#if !TYPE_OBJECT -#ignore - @CollectionSize.Require(absent = ZERO) -#endignore - public void testGetObject_yes() { - assertEquals("get(present) should return the associated value", VALUE_TO_OBJ(v0()), get(KEY_TO_OBJ(k0()))); - } - - public void testGetObject_no() { - assertEquals("get(notPresent) should return INVALID_VALUE", VALUE_TO_OBJ(INVALID_VALUE), get(KEY_TO_OBJ(k3()))); - } -#endif -} +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapGetTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#ignore + @CollectionSize.Require(absent = ZERO) +#endignore + public void testGet_yes() { + assertEquals("get(present) should return the associated value", v0(), get(k0())); + } + + public void testGet_no() { + assertEquals("get(notPresent) should return INVALID_VALUE", INVALID_VALUE, get(k3())); + } + +#if !TYPE_OBJECT +#ignore + @CollectionSize.Require(absent = ZERO) +#endignore + public void testGetObject_yes() { + assertEquals("get(present) should return the associated value", VALUE_TO_OBJ(v0()), get(KEY_TO_OBJ(k0()))); + } + + public void testGetObject_no() { + assertEquals("get(notPresent) should return INVALID_VALUE", VALUE_TO_OBJ(INVALID_VALUE), get(KEY_TO_OBJ(k3()))); + } +#endif +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapHashCodeTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapHashCodeTester.template index 6cb5fab..5cffa24 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapHashCodeTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapHashCodeTester.template @@ -1,27 +1,27 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#if TYPE_OBJECT || VALUE_OBJECT -import java.util.Objects; -#endif - -import org.junit.Ignore; - -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapHashCodeTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ - public void testHashCode() { - int expectedHashCode = 0; - for (MAP.Entry KEY_VALUE_GENERIC_TYPE entry : getSampleEntries()) { - expectedHashCode += hash(entry); - } - assertEquals("A Map's hashCode() should be the sum of those of its entries.", expectedHashCode, getMap().hashCode()); - } - - private static GENERIC_KEY_VALUE_BRACES int hash(MAP.Entry KEY_VALUE_GENERIC_TYPE e) { - return KEY_TO_HASH(e.ENTRY_KEY()) ^ VALUE_TO_HASH(e.ENTRY_VALUE()); - } -} +package speiger.src.testers.PACKAGE.tests.maps; + +#if TYPE_OBJECT || VALUE_OBJECT +import java.util.Objects; +#endif + +import org.junit.Ignore; + +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapHashCodeTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ + public void testHashCode() { + int expectedHashCode = 0; + for (MAP.Entry KEY_VALUE_GENERIC_TYPE entry : getSampleEntries()) { + expectedHashCode += hash(entry); + } + assertEquals("A Map's hashCode() should be the sum of those of its entries.", expectedHashCode, getMap().hashCode()); + } + + private static GENERIC_KEY_VALUE_BRACES int hash(MAP.Entry KEY_VALUE_GENERIC_TYPE e) { + return KEY_TO_HASH(e.ENTRY_KEY()) ^ VALUE_TO_HASH(e.ENTRY_VALUE()); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapIsEmptyTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapIsEmptyTester.template index 320920d..3b3c681 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapIsEmptyTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapIsEmptyTester.template @@ -1,30 +1,30 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapIsEmptyTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ -#ignore - @CollectionSize.Require(ZERO) -#endignore - public void testIsEmpty_yes() { - assertTrue("isEmpty() should return true", getMap().isEmpty()); - } - -#ignore - @CollectionSize.Require(absent = ZERO) -#endignore - public void testIsEmpty_no() { - assertFalse("isEmpty() should return false", getMap().isEmpty()); - } +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapIsEmptyTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#ignore + @CollectionSize.Require(ZERO) +#endignore + public void testIsEmpty_yes() { + assertTrue("isEmpty() should return true", getMap().isEmpty()); + } + +#ignore + @CollectionSize.Require(absent = ZERO) +#endignore + public void testIsEmpty_no() { + assertFalse("isEmpty() should return false", getMap().isEmpty()); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapMergeBulkTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapMergeBulkTester.template index e060435..79c46ec 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapMergeBulkTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapMergeBulkTester.template @@ -1,93 +1,93 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; -#endignore - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; - -import junit.framework.AssertionFailedError; -import speiger.src.collections.PACKAGE.utils.maps.MAPS; -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapMergeBulkTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ -#if !VALUE_BOOLEAN -#ignore - @MapFeature.Require(SUPPORTS_PUT) -#endignore - public void testAbsent() { - getMap().BULK_MERGE(MAPS.singleton(k3(), v3()), (oldV, newV) -> { - throw new AssertionFailedError("Should not call BULK_MERGE function if key was absent"); - }); - expectAdded(e3()); - } - -#endif -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testBulkMergePresent() { - getMap().BULK_MERGE(MAPS.singleton(k0(), v3()), (oldV, newV) -> { - assertEquals(v0(), oldV); - assertEquals(v3(), newV); - return v4(); - }); - expectReplacement(entry(k0(), v4())); - } - - private static class ExpectedException extends RuntimeException { - private static final long serialVersionUID = 1L; - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testBulkMergeFunctionThrows() { - try { - getMap().BULK_MERGE(MAPS.singleton(k0(), v3()), (oldV, newV) -> { - assertEquals(v0(), oldV); - assertEquals(v3(), newV); - throw new ExpectedException(); - }); - fail("Expected ExpectedException"); - } catch (ExpectedException expected) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testBulkMergePresentToNull() { - getMap().BULK_MERGE(MAPS.singleton(k0(), v3()), (oldV, newV) -> { - assertEquals(v0(), oldV); - assertEquals(v3(), newV); - return INVALID_VALUE; - }); - expectMissing(e0()); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) -#endignore - public void testBulkMergeUnsupported() { - try { - getMap().BULK_MERGE(MAPS.singleton(k3(), v3()), (oldV, newV) -> { - throw new AssertionFailedError(); - }); - fail("Expected UnsupportedOperationException"); - } catch (UnsupportedOperationException expected) { - } - } +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; +#endignore + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +import junit.framework.AssertionFailedError; +import speiger.src.collections.PACKAGE.utils.maps.MAPS; +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapMergeBulkTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#if !VALUE_BOOLEAN +#ignore + @MapFeature.Require(SUPPORTS_PUT) +#endignore + public void testAbsent() { + getMap().BULK_MERGE(MAPS.singleton(k3(), v3()), (oldV, newV) -> { + throw new AssertionFailedError("Should not call BULK_MERGE function if key was absent"); + }); + expectAdded(e3()); + } + +#endif +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testBulkMergePresent() { + getMap().BULK_MERGE(MAPS.singleton(k0(), v3()), (oldV, newV) -> { + assertEquals(v0(), oldV); + assertEquals(v3(), newV); + return v4(); + }); + expectReplacement(entry(k0(), v4())); + } + + private static class ExpectedException extends RuntimeException { + private static final long serialVersionUID = 1L; + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testBulkMergeFunctionThrows() { + try { + getMap().BULK_MERGE(MAPS.singleton(k0(), v3()), (oldV, newV) -> { + assertEquals(v0(), oldV); + assertEquals(v3(), newV); + throw new ExpectedException(); + }); + fail("Expected ExpectedException"); + } catch (ExpectedException expected) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testBulkMergePresentToNull() { + getMap().BULK_MERGE(MAPS.singleton(k0(), v3()), (oldV, newV) -> { + assertEquals(v0(), oldV); + assertEquals(v3(), newV); + return INVALID_VALUE; + }); + expectMissing(e0()); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) +#endignore + public void testBulkMergeUnsupported() { + try { + getMap().BULK_MERGE(MAPS.singleton(k3(), v3()), (oldV, newV) -> { + throw new AssertionFailedError(); + }); + fail("Expected UnsupportedOperationException"); + } catch (UnsupportedOperationException expected) { + } + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapMergeTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapMergeTester.template index 7de2a27..30e6d9b 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapMergeTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapMergeTester.template @@ -1,93 +1,93 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; -#endignore - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; - -import junit.framework.AssertionFailedError; -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapMergeTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ -#ignore - @MapFeature.Require(SUPPORTS_PUT) -#endignore - public void testAbsent() { - assertEquals("Map.MERGE(absent, value, function) should return value", v3(), - getMap().MERGE(k3(), v3(), (oldV, newV) -> { - throw new AssertionFailedError("Should not call MERGE function if key was absent"); - })); - expectAdded(e3()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testMergePresent() { - assertEquals("Map.MERGE(present, value, function) should return function result", v4(), - getMap().MERGE(k0(), v3(), (oldV, newV) -> { - assertEquals(v0(), oldV); - assertEquals(v3(), newV); - return v4(); - })); - expectReplacement(entry(k0(), v4())); - } - - private static class ExpectedException extends RuntimeException { - private static final long serialVersionUID = 1L; - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testMergeFunctionThrows() { - try { - getMap().MERGE(k0(), v3(), (oldV, newV) -> { - assertEquals(v0(), oldV); - assertEquals(v3(), newV); - throw new ExpectedException(); - }); - fail("Expected ExpectedException"); - } catch (ExpectedException expected) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testMergePresentToNull() { - assertEquals("Map.MERGE(present, value, functionReturningNull) should return INVALID_VALUE", INVALID_VALUE, - getMap().MERGE(k0(), v3(), (oldV, newV) -> { - assertEquals(v0(), oldV); - assertEquals(v3(), newV); - return INVALID_VALUE; - })); - expectMissing(e0()); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) -#endignore - public void testMergeUnsupported() { - try { - getMap().MERGE(k3(), v3(), (oldV, newV) -> { - throw new AssertionFailedError(); - }); - fail("Expected UnsupportedOperationException"); - } catch (UnsupportedOperationException expected) { - } - } +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; +#endignore + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +import junit.framework.AssertionFailedError; +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapMergeTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#ignore + @MapFeature.Require(SUPPORTS_PUT) +#endignore + public void testAbsent() { + assertEquals("Map.MERGE(absent, value, function) should return value", v3(), + getMap().MERGE(k3(), v3(), (oldV, newV) -> { + throw new AssertionFailedError("Should not call MERGE function if key was absent"); + })); + expectAdded(e3()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testMergePresent() { + assertEquals("Map.MERGE(present, value, function) should return function result", v4(), + getMap().MERGE(k0(), v3(), (oldV, newV) -> { + assertEquals(v0(), oldV); + assertEquals(v3(), newV); + return v4(); + })); + expectReplacement(entry(k0(), v4())); + } + + private static class ExpectedException extends RuntimeException { + private static final long serialVersionUID = 1L; + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testMergeFunctionThrows() { + try { + getMap().MERGE(k0(), v3(), (oldV, newV) -> { + assertEquals(v0(), oldV); + assertEquals(v3(), newV); + throw new ExpectedException(); + }); + fail("Expected ExpectedException"); + } catch (ExpectedException expected) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testMergePresentToNull() { + assertEquals("Map.MERGE(present, value, functionReturningNull) should return INVALID_VALUE", INVALID_VALUE, + getMap().MERGE(k0(), v3(), (oldV, newV) -> { + assertEquals(v0(), oldV); + assertEquals(v3(), newV); + return INVALID_VALUE; + })); + expectMissing(e0()); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) +#endignore + public void testMergeUnsupported() { + try { + getMap().MERGE(k3(), v3(), (oldV, newV) -> { + throw new AssertionFailedError(); + }); + fail("Expected UnsupportedOperationException"); + } catch (UnsupportedOperationException expected) { + } + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapPutAllArrayTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapPutAllArrayTester.template index cfe2aa7..b3ea7cb 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapPutAllArrayTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapPutAllArrayTester.template @@ -1,243 +1,243 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; -#endignore - -import java.util.ConcurrentModificationException; -import java.util.Map; - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; - -import speiger.src.collections.PACKAGE.maps.impl.hash.LINKED_HASH_MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.collections.objects.collections.ObjectIterable; -import speiger.src.collections.objects.collections.ObjectIterator; -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; -import speiger.src.testers.objects.utils.MinimalObjectCollection; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutAllArrayTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ -#ignore - @MapFeature.Require(SUPPORTS_PUT) -#endignore - public void testPutAllArray_supportedNothing() { - getMap().putAll(emptyKeyArray(), emptyValueArray()); - expectUnchanged(); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) -#endignore - public void testPutAllObjectArray_supportedNothing() { - getMap().putAll(emptyKeyObjectArray(), emptyValueObjectArray()); - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) -#endignore - public void testPutAllArray_unsupportedNothing() { - try { - getMap().putAll(emptyKeyArray(), emptyValueArray()); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) -#endignore - public void testPutAllObjectArray_unsupportedNothing() { - try { - getMap().putAll(emptyKeyObjectArray(), emptyValueObjectArray()); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) -#endignore - public void testPutAllArray_supportedNonePresent() { - putAll(createDisjointCollection()); - expectAdded(e3(), e4()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) -#endignore - public void testPutAllObjectArray_supportedNonePresent() { - putAllObjects(createDisjointCollection()); - expectAdded(e3(), e4()); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) -#endignore - public void testPutAllArray_unsupportedNonePresent() { - try { - putAll(createDisjointCollection()); - fail("putAll(nonePresent) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - expectMissing(e3(), e4()); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) -#endignore - public void testPutAllObjectArray_unsupportedNonePresent() { - try { - putAllObjects(createDisjointCollection()); - fail("putAll(nonePresent) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - expectMissing(e3(), e4()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testPutAllArray_supportedSomePresent() { - putAll(MinimalObjectCollection.of(e3(), e0())); - expectAdded(e3()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testPutAllObjectArray_supportedSomePresent() { - putAllObjects(MinimalObjectCollection.of(e3(), e0())); - expectAdded(e3()); - } - -#ignore - @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT }) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testPutAllArraySomePresentConcurrentWithEntrySetIteration() { - try { - ObjectIterator iterator = getMap().ENTRY_SET().iterator(); - putAll(MinimalObjectCollection.of(e3(), e0())); - iterator.next(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#ignore - @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT }) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testPutAllObjectArraySomePresentConcurrentWithEntrySetIteration() { - try { - ObjectIterator iterator = getMap().ENTRY_SET().iterator(); - putAllObjects(MinimalObjectCollection.of(e3(), e0())); - iterator.next(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testPutAllArray_unsupportedSomePresent() { - try { - putAll(MinimalObjectCollection.of(e3(), e0())); - fail("putAll(somePresent) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testPutAllObjectArray_unsupportedSomePresent() { - try { - putAllObjects(MinimalObjectCollection.of(e3(), e0())); - fail("putAll(somePresent) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testPutAllArray_unsupportedAllPresent() { - try { - putAll(MinimalObjectCollection.of(e0())); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testPutAllObjectArray_unsupportedAllPresent() { - try { - putAllObjects(MinimalObjectCollection.of(e0())); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) -#endignore - public void testPutAllArray_nullCollectionReference() { - try { - getMap().putAll((KEY_TYPE[])null, (VALUE_TYPE[])null); - fail("putAll(null) should throw NullPointerException"); - } catch (NullPointerException expected) { - } - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) -#endignore - public void testPutAllObjectArray_nullCollectionReference() { - try { - getMap().putAll((CLASS_TYPE[])null, (CLASS_VALUE_TYPE[])null); - fail("putAll(null) should throw NullPointerException"); - } catch (NullPointerException expected) { - } - } - - private void putAll(ObjectIterable entries) { - MAP KEY_VALUE_GENERIC_TYPE map = new LINKED_HASH_MAPKV_BRACES(); - for (MAP.Entry KEY_VALUE_GENERIC_TYPE entry : entries) { - map.put(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); - } - getMap().putAll(map.keySet().TO_ARRAY(NEW_KEY_ARRAY(map.size())), map.values().VALUE_TO_ARRAY(NEW_VALUE_ARRAY(map.size()))); - } - - private void putAllObjects(ObjectIterable entries) { - Map map = new LINKED_HASH_MAPKV_BRACES(); - for (MAP.Entry KEY_VALUE_GENERIC_TYPE entry : entries) { - map.put(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); - } - getMap().putAll(map.keySet().toArray(NEW_CLASS_ARRAY(map.size())), map.values().toArray(NEW_CLASS_VALUE_ARRAY(map.size()))); - } -} +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; +#endignore + +import java.util.ConcurrentModificationException; +import java.util.Map; + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +import speiger.src.collections.PACKAGE.maps.impl.hash.LINKED_HASH_MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.collections.objects.collections.ObjectIterable; +import speiger.src.collections.objects.collections.ObjectIterator; +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; +import speiger.src.testers.objects.utils.MinimalObjectCollection; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutAllArrayTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#ignore + @MapFeature.Require(SUPPORTS_PUT) +#endignore + public void testPutAllArray_supportedNothing() { + getMap().putAll(emptyKeyArray(), emptyValueArray()); + expectUnchanged(); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) +#endignore + public void testPutAllObjectArray_supportedNothing() { + getMap().putAll(emptyKeyObjectArray(), emptyValueObjectArray()); + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) +#endignore + public void testPutAllArray_unsupportedNothing() { + try { + getMap().putAll(emptyKeyArray(), emptyValueArray()); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) +#endignore + public void testPutAllObjectArray_unsupportedNothing() { + try { + getMap().putAll(emptyKeyObjectArray(), emptyValueObjectArray()); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) +#endignore + public void testPutAllArray_supportedNonePresent() { + putAll(createDisjointCollection()); + expectAdded(e3(), e4()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) +#endignore + public void testPutAllObjectArray_supportedNonePresent() { + putAllObjects(createDisjointCollection()); + expectAdded(e3(), e4()); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) +#endignore + public void testPutAllArray_unsupportedNonePresent() { + try { + putAll(createDisjointCollection()); + fail("putAll(nonePresent) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + expectMissing(e3(), e4()); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) +#endignore + public void testPutAllObjectArray_unsupportedNonePresent() { + try { + putAllObjects(createDisjointCollection()); + fail("putAll(nonePresent) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + expectMissing(e3(), e4()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testPutAllArray_supportedSomePresent() { + putAll(MinimalObjectCollection.of(e3(), e0())); + expectAdded(e3()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testPutAllObjectArray_supportedSomePresent() { + putAllObjects(MinimalObjectCollection.of(e3(), e0())); + expectAdded(e3()); + } + +#ignore + @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT }) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testPutAllArraySomePresentConcurrentWithEntrySetIteration() { + try { + ObjectIterator iterator = getMap().ENTRY_SET().iterator(); + putAll(MinimalObjectCollection.of(e3(), e0())); + iterator.next(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#ignore + @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT }) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testPutAllObjectArraySomePresentConcurrentWithEntrySetIteration() { + try { + ObjectIterator iterator = getMap().ENTRY_SET().iterator(); + putAllObjects(MinimalObjectCollection.of(e3(), e0())); + iterator.next(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testPutAllArray_unsupportedSomePresent() { + try { + putAll(MinimalObjectCollection.of(e3(), e0())); + fail("putAll(somePresent) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testPutAllObjectArray_unsupportedSomePresent() { + try { + putAllObjects(MinimalObjectCollection.of(e3(), e0())); + fail("putAll(somePresent) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testPutAllArray_unsupportedAllPresent() { + try { + putAll(MinimalObjectCollection.of(e0())); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testPutAllObjectArray_unsupportedAllPresent() { + try { + putAllObjects(MinimalObjectCollection.of(e0())); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) +#endignore + public void testPutAllArray_nullCollectionReference() { + try { + getMap().putAll((KEY_TYPE[])null, (VALUE_TYPE[])null); + fail("putAll(null) should throw NullPointerException"); + } catch (NullPointerException expected) { + } + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) +#endignore + public void testPutAllObjectArray_nullCollectionReference() { + try { + getMap().putAll((CLASS_TYPE[])null, (CLASS_VALUE_TYPE[])null); + fail("putAll(null) should throw NullPointerException"); + } catch (NullPointerException expected) { + } + } + + private void putAll(ObjectIterable entries) { + MAP KEY_VALUE_GENERIC_TYPE map = new LINKED_HASH_MAPKV_BRACES(); + for (MAP.Entry KEY_VALUE_GENERIC_TYPE entry : entries) { + map.put(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); + } + getMap().putAll(map.keySet().TO_ARRAY(NEW_KEY_ARRAY(map.size())), map.values().VALUE_TO_ARRAY(NEW_VALUE_ARRAY(map.size()))); + } + + private void putAllObjects(ObjectIterable entries) { + Map map = new LINKED_HASH_MAPKV_BRACES(); + for (MAP.Entry KEY_VALUE_GENERIC_TYPE entry : entries) { + map.put(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); + } + getMap().putAll(map.keySet().toArray(NEW_CLASS_ARRAY(map.size())), map.values().toArray(NEW_CLASS_VALUE_ARRAY(map.size()))); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapPutAllTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapPutAllTester.template index c085a9f..a85da51 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapPutAllTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapPutAllTester.template @@ -1,139 +1,139 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; -#endignore - -import java.util.ConcurrentModificationException; - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; - -import speiger.src.collections.PACKAGE.maps.impl.hash.LINKED_HASH_MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.collections.PACKAGE.utils.maps.MAPS; -import speiger.src.collections.objects.collections.ObjectIterable; -import speiger.src.collections.objects.collections.ObjectIterator; -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; -import speiger.src.testers.objects.utils.MinimalObjectCollection; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutAllTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ -#ignore - @MapFeature.Require(SUPPORTS_PUT) -#endignore - public void testPutAll_supportedNothing() { - getMap().putAll(emptyMap()); - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) -#endignore - public void testPutAll_unsupportedNothing() { - try { - getMap().putAll(emptyMap()); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) -#endignore - public void testPutAll_supportedNonePresent() { - putAll(createDisjointCollection()); - expectAdded(e3(), e4()); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) -#endignore - public void testPutAll_unsupportedNonePresent() { - try { - putAll(createDisjointCollection()); - fail("putAll(nonePresent) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - expectMissing(e3(), e4()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testPutAll_supportedSomePresent() { - putAll(MinimalObjectCollection.of(e3(), e0())); - expectAdded(e3()); - } - -#ignore - @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT }) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testPutAllSomePresentConcurrentWithEntrySetIteration() { - try { - ObjectIterator iterator = getMap().ENTRY_SET().iterator(); - putAll(MinimalObjectCollection.of(e3(), e0())); - iterator.next(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testPutAll_unsupportedSomePresent() { - try { - putAll(MinimalObjectCollection.of(e3(), e0())); - fail("putAll(somePresent) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testPutAll_unsupportedAllPresent() { - try { - putAll(MinimalObjectCollection.of(e0())); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) -#endignore - public void testPutAll_nullCollectionReference() { - try { - getMap().putAll(null); - fail("putAll(null) should throw NullPointerException"); - } catch (NullPointerException expected) { - } - } - - private MAP KEY_VALUE_GENERIC_TYPE emptyMap() { - return MAPS.empty(); - } - - private void putAll(ObjectIterable entries) { - MAP KEY_VALUE_GENERIC_TYPE map = new LINKED_HASH_MAPKV_BRACES(); - for (MAP.Entry KEY_VALUE_GENERIC_TYPE entry : entries) { - map.put(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); - } - getMap().putAll(map); - } -} +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; +#endignore + +import java.util.ConcurrentModificationException; + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +import speiger.src.collections.PACKAGE.maps.impl.hash.LINKED_HASH_MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.collections.PACKAGE.utils.maps.MAPS; +import speiger.src.collections.objects.collections.ObjectIterable; +import speiger.src.collections.objects.collections.ObjectIterator; +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; +import speiger.src.testers.objects.utils.MinimalObjectCollection; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutAllTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#ignore + @MapFeature.Require(SUPPORTS_PUT) +#endignore + public void testPutAll_supportedNothing() { + getMap().putAll(emptyMap()); + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) +#endignore + public void testPutAll_unsupportedNothing() { + try { + getMap().putAll(emptyMap()); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) +#endignore + public void testPutAll_supportedNonePresent() { + putAll(createDisjointCollection()); + expectAdded(e3(), e4()); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) +#endignore + public void testPutAll_unsupportedNonePresent() { + try { + putAll(createDisjointCollection()); + fail("putAll(nonePresent) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + expectMissing(e3(), e4()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testPutAll_supportedSomePresent() { + putAll(MinimalObjectCollection.of(e3(), e0())); + expectAdded(e3()); + } + +#ignore + @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT }) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testPutAllSomePresentConcurrentWithEntrySetIteration() { + try { + ObjectIterator iterator = getMap().ENTRY_SET().iterator(); + putAll(MinimalObjectCollection.of(e3(), e0())); + iterator.next(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testPutAll_unsupportedSomePresent() { + try { + putAll(MinimalObjectCollection.of(e3(), e0())); + fail("putAll(somePresent) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testPutAll_unsupportedAllPresent() { + try { + putAll(MinimalObjectCollection.of(e0())); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) +#endignore + public void testPutAll_nullCollectionReference() { + try { + getMap().putAll(null); + fail("putAll(null) should throw NullPointerException"); + } catch (NullPointerException expected) { + } + } + + private MAP KEY_VALUE_GENERIC_TYPE emptyMap() { + return MAPS.empty(); + } + + private void putAll(ObjectIterable entries) { + MAP KEY_VALUE_GENERIC_TYPE map = new LINKED_HASH_MAPKV_BRACES(); + for (MAP.Entry KEY_VALUE_GENERIC_TYPE entry : entries) { + map.put(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); + } + getMap().putAll(map); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapPutIfAbsentTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapPutIfAbsentTester.template index 2977aa6..fd6c37b 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapPutIfAbsentTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapPutIfAbsentTester.template @@ -1,82 +1,82 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; -#endignore - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; - -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutIfAbsentTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ -#ignore - @MapFeature.Require(SUPPORTS_PUT) -#endignore - public void testPutIfAbsent_supportedAbsent() { - assertEquals("putIfAbsent(notPresent, value) should return INVALID_VALUE", INVALID_VALUE, getMap().putIfAbsent(k3(), v3())); - expectAdded(e3()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testPutIfAbsent_supportedPresent() { - assertEquals("putIfAbsent(present, value) should return existing value", v0(), getMap().putIfAbsent(k0(), v3())); - expectUnchanged(); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) -#endignore - public void testPutIfAbsent_replaceableDefaultValue() { - getMap().putIfAbsent(k3(), getMap().getDefaultReturnValue()); - assertEquals("get(present) should return defaultValue value", getMap().getDefaultReturnValue(), get(k3())); - getMap().putIfAbsent(k3(), v3()); - assertEquals("get(present) value should have been replaced", v3(), get(k3())); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) -#endignore - public void testPutIfAbsent_unsupportedAbsent() { - try { - getMap().putIfAbsent(k3(), v3()); - fail("putIfAbsent(notPresent, value) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - expectMissing(e3()); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testPutIfAbsent_unsupportedPresentExistingValue() { - try { - assertEquals("putIfAbsent(present, existingValue) should return present or throw", v0(), getMap().putIfAbsent(k0(), v0())); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testPutIfAbsent_unsupportedPresentDifferentValue() { - try { - getMap().putIfAbsent(k0(), v3()); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } -} +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; +#endignore + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutIfAbsentTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#ignore + @MapFeature.Require(SUPPORTS_PUT) +#endignore + public void testPutIfAbsent_supportedAbsent() { + assertEquals("putIfAbsent(notPresent, value) should return INVALID_VALUE", INVALID_VALUE, getMap().putIfAbsent(k3(), v3())); + expectAdded(e3()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testPutIfAbsent_supportedPresent() { + assertEquals("putIfAbsent(present, value) should return existing value", v0(), getMap().putIfAbsent(k0(), v3())); + expectUnchanged(); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) +#endignore + public void testPutIfAbsent_replaceableDefaultValue() { + getMap().putIfAbsent(k3(), getMap().getDefaultReturnValue()); + assertEquals("get(present) should return defaultValue value", getMap().getDefaultReturnValue(), get(k3())); + getMap().putIfAbsent(k3(), v3()); + assertEquals("get(present) value should have been replaced", v3(), get(k3())); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) +#endignore + public void testPutIfAbsent_unsupportedAbsent() { + try { + getMap().putIfAbsent(k3(), v3()); + fail("putIfAbsent(notPresent, value) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + expectMissing(e3()); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testPutIfAbsent_unsupportedPresentExistingValue() { + try { + assertEquals("putIfAbsent(present, existingValue) should return present or throw", v0(), getMap().putIfAbsent(k0(), v0())); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testPutIfAbsent_unsupportedPresentDifferentValue() { + try { + getMap().putIfAbsent(k0(), v3()); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapPutTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapPutTester.template index b82bbb5..47a0e5d 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapPutTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapPutTester.template @@ -1,131 +1,131 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; -#endignore - -import java.util.ConcurrentModificationException; -import java.util.Iterator; - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; - -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; -#if !SAME_TYPE -import speiger.src.collections.PACKAGE.collections.ITERATOR; -#endif -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testPut_supportedPresent() { - assertEquals("put(present, value) should return the old value", v0(), getMap().put(k0(), v3())); - expectReplacement(entry(k0(), v3())); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) -#endignore - public void testPut_supportedNotPresent() { - assertEquals("put(notPresent, value) should return INVALID_VALUE", INVALID_VALUE, put(e3())); - expectAdded(e3()); - } - -#ignore - @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT }) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testPutAbsentConcurrentWithEntrySetIteration() { - try { - Iterator iterator = getMap().ENTRY_SET().iterator(); - put(e3()); - iterator.next(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#ignore - @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT }) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testPutAbsentConcurrentWithKeySetIteration() { - try { - ITERATOR KEY_GENERIC_TYPE iterator = getMap().keySet().iterator(); - put(e3()); - iterator.NEXT(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#ignore - @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT }) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testPutAbsentConcurrentWithValueIteration() { - try { - VALUE_ITERATOR VALUE_GENERIC_TYPE iterator = getMap().values().iterator(); - put(e3()); - iterator.VALUE_NEXT(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) -#endignore - public void testPut_unsupportedNotPresent() { - try { - put(e3()); - fail("put(notPresent, value) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - expectMissing(e3()); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testPut_unsupportedPresentExistingValue() { - try { - assertEquals("put(present, existingValue) should return present or throw", v0(), put(e0())); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testPut_unsupportedPresentDifferentValue() { - try { - getMap().put(k0(), v3()); - fail("put(present, differentValue) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } - - private VALUE_TYPE put(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { - return getMap().put(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); - } -} +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; +#endignore + +import java.util.ConcurrentModificationException; +import java.util.Iterator; + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; +#if !SAME_TYPE +import speiger.src.collections.PACKAGE.collections.ITERATOR; +#endif +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testPut_supportedPresent() { + assertEquals("put(present, value) should return the old value", v0(), getMap().put(k0(), v3())); + expectReplacement(entry(k0(), v3())); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) +#endignore + public void testPut_supportedNotPresent() { + assertEquals("put(notPresent, value) should return INVALID_VALUE", INVALID_VALUE, put(e3())); + expectAdded(e3()); + } + +#ignore + @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT }) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testPutAbsentConcurrentWithEntrySetIteration() { + try { + Iterator iterator = getMap().ENTRY_SET().iterator(); + put(e3()); + iterator.next(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#ignore + @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT }) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testPutAbsentConcurrentWithKeySetIteration() { + try { + ITERATOR KEY_GENERIC_TYPE iterator = getMap().keySet().iterator(); + put(e3()); + iterator.NEXT(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#ignore + @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT }) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testPutAbsentConcurrentWithValueIteration() { + try { + VALUE_ITERATOR VALUE_GENERIC_TYPE iterator = getMap().values().iterator(); + put(e3()); + iterator.VALUE_NEXT(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) +#endignore + public void testPut_unsupportedNotPresent() { + try { + put(e3()); + fail("put(notPresent, value) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + expectMissing(e3()); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testPut_unsupportedPresentExistingValue() { + try { + assertEquals("put(present, existingValue) should return present or throw", v0(), put(e0())); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testPut_unsupportedPresentDifferentValue() { + try { + getMap().put(k0(), v3()); + fail("put(present, differentValue) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } + + private VALUE_TYPE put(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { + return getMap().put(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapRemoveEntryTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapRemoveEntryTester.template index 5a94660..80c5161 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapRemoveEntryTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapRemoveEntryTester.template @@ -1,186 +1,186 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; -#endignore - -import java.util.AbstractMap; - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; - -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapRemoveEntryTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRemove_supportedPresent() { - assertTrue(getMap().remove(k0(), v0())); - expectMissing(e0()); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testRemove_supportedPresentLast() { - assertTrue(getMap().remove(k2(), v2())); - expectMissing(e2()); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testRemove_supportedPresentLastWrongValue() { - assertFalse(getMap().remove(k1(), v2())); - expectUnchanged(); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) -#endignore - public void testRemove_supportedPresentKeyWrongValue() { - assertFalse(getMap().remove(k0(), v3())); - expectUnchanged(); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) -#endignore - public void testRemove_supportedWrongKeyPresentValue() { - assertFalse(getMap().remove(k3(), v0())); - expectUnchanged(); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) -#endignore - public void testRemove_supportedAbsentKeyAbsentValue() { - assertFalse(getMap().remove(k3(), v3())); - expectUnchanged(); - } - -#if !TYPE_OBJECT -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRemoveObject_supportedPresent() { - assertTrue(getMap().remove(KEY_TO_OBJ(k0()), VALUE_TO_OBJ(v0()))); - expectMissing(e0()); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testRemoveObject_supportedPresentLast() { - assertTrue(getMap().remove(KEY_TO_OBJ(k2()), VALUE_TO_OBJ(v2()))); - expectMissing(e2()); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testRemoveObject_supportedPresentLastWrongValue() { - assertFalse(getMap().remove(KEY_TO_OBJ(k1()), VALUE_TO_OBJ(v2()))); - expectUnchanged(); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) -#endignore - public void testRemoveObject_supportedPresentKeyWrongValue() { - assertFalse(getMap().remove(KEY_TO_OBJ(k0()), VALUE_TO_OBJ(v3()))); - expectUnchanged(); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) -#endignore - public void testRemoveObject_supportedWrongKeyPresentValue() { - assertFalse(getMap().remove(KEY_TO_OBJ(k3()), VALUE_TO_OBJ(v0()))); - expectUnchanged(); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) -#endignore - public void testRemoveObject_supportedAbsentKeyAbsentValue() { - assertFalse(getMap().remove(KEY_TO_OBJ(k3()), VALUE_TO_OBJ(v3()))); - expectUnchanged(); - } - -#endif -#ignore - @CollectionSize.Require(ONE) - @MapFeature.Require(SUPPORTS_REMOVE) -#endignore - public void testRemove_supportedEntryPresent() { - assertTrue(getMap().ENTRY_SET().remove(e0())); - expectMissing(e0()); - } - -#ignore - @CollectionSize.Require(ONE) - @MapFeature.Require(SUPPORTS_REMOVE) -#endignore - public void testRemove_supportedObjectEntryPresent() { - assertTrue(getMap().ENTRY_SET().remove(new AbstractMap.SimpleEntry<>(e0()))); - expectMissing(e0()); - } - -#ignore - @CollectionSize.Require(ONE) - @MapFeature.Require(SUPPORTS_REMOVE) -#endignore - public void testRemove_supportedEntryMissing() { - assertFalse(getMap().ENTRY_SET().remove(e3())); - expectUnchanged(); - } - -#ignore - @CollectionSize.Require(ONE) - @MapFeature.Require(SUPPORTS_REMOVE) -#endignore - public void testRemove_supportedObjectEntryMissing() { - assertFalse(getMap().ENTRY_SET().remove(new AbstractMap.SimpleEntry<>(e3()))); - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRemove_unsupportedPresent() { - try { - getMap().remove(k0(), v0()); - fail("Expected UnsupportedOperationException"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_REMOVE) -#endignore - public void testRemove_unsupportedAbsent() { - try { - assertFalse(getMap().remove(k0(), v3())); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; +#endignore + +import java.util.AbstractMap; + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapRemoveEntryTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRemove_supportedPresent() { + assertTrue(getMap().remove(k0(), v0())); + expectMissing(e0()); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testRemove_supportedPresentLast() { + assertTrue(getMap().remove(k2(), v2())); + expectMissing(e2()); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testRemove_supportedPresentLastWrongValue() { + assertFalse(getMap().remove(k1(), v2())); + expectUnchanged(); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) +#endignore + public void testRemove_supportedPresentKeyWrongValue() { + assertFalse(getMap().remove(k0(), v3())); + expectUnchanged(); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) +#endignore + public void testRemove_supportedWrongKeyPresentValue() { + assertFalse(getMap().remove(k3(), v0())); + expectUnchanged(); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) +#endignore + public void testRemove_supportedAbsentKeyAbsentValue() { + assertFalse(getMap().remove(k3(), v3())); + expectUnchanged(); + } + +#if !TYPE_OBJECT +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRemoveObject_supportedPresent() { + assertTrue(getMap().remove(KEY_TO_OBJ(k0()), VALUE_TO_OBJ(v0()))); + expectMissing(e0()); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testRemoveObject_supportedPresentLast() { + assertTrue(getMap().remove(KEY_TO_OBJ(k2()), VALUE_TO_OBJ(v2()))); + expectMissing(e2()); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testRemoveObject_supportedPresentLastWrongValue() { + assertFalse(getMap().remove(KEY_TO_OBJ(k1()), VALUE_TO_OBJ(v2()))); + expectUnchanged(); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) +#endignore + public void testRemoveObject_supportedPresentKeyWrongValue() { + assertFalse(getMap().remove(KEY_TO_OBJ(k0()), VALUE_TO_OBJ(v3()))); + expectUnchanged(); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) +#endignore + public void testRemoveObject_supportedWrongKeyPresentValue() { + assertFalse(getMap().remove(KEY_TO_OBJ(k3()), VALUE_TO_OBJ(v0()))); + expectUnchanged(); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) +#endignore + public void testRemoveObject_supportedAbsentKeyAbsentValue() { + assertFalse(getMap().remove(KEY_TO_OBJ(k3()), VALUE_TO_OBJ(v3()))); + expectUnchanged(); + } + +#endif +#ignore + @CollectionSize.Require(ONE) + @MapFeature.Require(SUPPORTS_REMOVE) +#endignore + public void testRemove_supportedEntryPresent() { + assertTrue(getMap().ENTRY_SET().remove(e0())); + expectMissing(e0()); + } + +#ignore + @CollectionSize.Require(ONE) + @MapFeature.Require(SUPPORTS_REMOVE) +#endignore + public void testRemove_supportedObjectEntryPresent() { + assertTrue(getMap().ENTRY_SET().remove(new AbstractMap.SimpleEntry<>(e0()))); + expectMissing(e0()); + } + +#ignore + @CollectionSize.Require(ONE) + @MapFeature.Require(SUPPORTS_REMOVE) +#endignore + public void testRemove_supportedEntryMissing() { + assertFalse(getMap().ENTRY_SET().remove(e3())); + expectUnchanged(); + } + +#ignore + @CollectionSize.Require(ONE) + @MapFeature.Require(SUPPORTS_REMOVE) +#endignore + public void testRemove_supportedObjectEntryMissing() { + assertFalse(getMap().ENTRY_SET().remove(new AbstractMap.SimpleEntry<>(e3()))); + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRemove_unsupportedPresent() { + try { + getMap().remove(k0(), v0()); + fail("Expected UnsupportedOperationException"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_REMOVE) +#endignore + public void testRemove_unsupportedAbsent() { + try { + assertFalse(getMap().remove(k0(), v3())); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapRemoveOrDefaultTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapRemoveOrDefaultTester.template index d4cdb25..718c450 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapRemoveOrDefaultTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapRemoveOrDefaultTester.template @@ -1,121 +1,121 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; -#endignore - -import java.util.ConcurrentModificationException; - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; - -#if !VALUE_OBJECT -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; -#endif -#if !TYPE_OBJECT && !SAME_TYPE -import speiger.src.collections.PACKAGE.collections.ITERATOR; -#endif -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.collections.objects.collections.ObjectIterator; -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapRemoveOrDefaultTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRemove_present() { - int initialSize = getMap().size(); - assertEquals("remove(present) should return the associated value", v0(), getMap().REMOVE_VALUEOrDefault(k0(), v1())); - assertEquals("remove(present) should decrease a map's size by one.", initialSize - 1, getMap().size()); - expectMissing(e0()); - } - -#ignore - @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE }) - @CollectionSize.Require(SEVERAL) -#endignore - public void testRemovePresentConcurrentWithEntrySetIteration() { - try { - ObjectIterator iterator = getMap().ENTRY_SET().iterator(); - getMap().REMOVE_VALUEOrDefault(k0(), v0()); - iterator.next(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#ignore - @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE }) - @CollectionSize.Require(SEVERAL) -#endignore - public void testRemovePresentConcurrentWithKeySetIteration() { - try { - ITERATOR KEY_GENERIC_TYPE iterator = getMap().keySet().iterator(); - getMap().REMOVE_VALUEOrDefault(k0(), v0()); - iterator.NEXT(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#ignore - @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE }) - @CollectionSize.Require(SEVERAL) -#endignore - public void testRemovePresentConcurrentWithValuesIteration() { - try { - VALUE_ITERATOR VALUE_GENERIC_TYPE iterator = getMap().values().iterator(); - getMap().REMOVE_VALUEOrDefault(k0(), v0()); - iterator.VALUE_NEXT(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) -#endignore - public void testRemove_notPresent() { - assertEquals("remove(notPresent) should return "+v3(), v3(), getMap().REMOVE_VALUEOrDefault(k3(), v3())); - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRemove_unsupported() { - try { - getMap().REMOVE_VALUEOrDefault(k0(), v0()); - fail("remove(present) should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - assertEquals("remove(present) should not remove the element", v0(), get(k0())); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_REMOVE) -#endignore - public void testRemove_unsupportedNotPresent() { - try { - assertNull("remove(notPresent) should return null or throw UnsupportedOperationException", getMap().REMOVE_VALUEOrDefault(k3(), v3())); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - expectMissing(e3()); - } - -} +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; +#endignore + +import java.util.ConcurrentModificationException; + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +#if !VALUE_OBJECT +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; +#endif +#if !TYPE_OBJECT && !SAME_TYPE +import speiger.src.collections.PACKAGE.collections.ITERATOR; +#endif +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.collections.objects.collections.ObjectIterator; +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapRemoveOrDefaultTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRemove_present() { + int initialSize = getMap().size(); + assertEquals("remove(present) should return the associated value", v0(), getMap().REMOVE_VALUEOrDefault(k0(), v1())); + assertEquals("remove(present) should decrease a map's size by one.", initialSize - 1, getMap().size()); + expectMissing(e0()); + } + +#ignore + @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE }) + @CollectionSize.Require(SEVERAL) +#endignore + public void testRemovePresentConcurrentWithEntrySetIteration() { + try { + ObjectIterator iterator = getMap().ENTRY_SET().iterator(); + getMap().REMOVE_VALUEOrDefault(k0(), v0()); + iterator.next(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#ignore + @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE }) + @CollectionSize.Require(SEVERAL) +#endignore + public void testRemovePresentConcurrentWithKeySetIteration() { + try { + ITERATOR KEY_GENERIC_TYPE iterator = getMap().keySet().iterator(); + getMap().REMOVE_VALUEOrDefault(k0(), v0()); + iterator.NEXT(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#ignore + @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE }) + @CollectionSize.Require(SEVERAL) +#endignore + public void testRemovePresentConcurrentWithValuesIteration() { + try { + VALUE_ITERATOR VALUE_GENERIC_TYPE iterator = getMap().values().iterator(); + getMap().REMOVE_VALUEOrDefault(k0(), v0()); + iterator.VALUE_NEXT(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) +#endignore + public void testRemove_notPresent() { + assertEquals("remove(notPresent) should return "+v3(), v3(), getMap().REMOVE_VALUEOrDefault(k3(), v3())); + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRemove_unsupported() { + try { + getMap().REMOVE_VALUEOrDefault(k0(), v0()); + fail("remove(present) should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + assertEquals("remove(present) should not remove the element", v0(), get(k0())); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_REMOVE) +#endignore + public void testRemove_unsupportedNotPresent() { + try { + assertNull("remove(notPresent) should return null or throw UnsupportedOperationException", getMap().REMOVE_VALUEOrDefault(k3(), v3())); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + expectMissing(e3()); + } + +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapRemoveTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapRemoveTester.template index c97c8b2..3d16823 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapRemoveTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapRemoveTester.template @@ -1,225 +1,225 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; -#endignore - -import java.util.ConcurrentModificationException; - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; - -#if !VALUE_OBJECT -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; -#endif -#if !TYPE_OBJECT && !SAME_TYPE -import speiger.src.collections.PACKAGE.collections.ITERATOR; -#endif -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.collections.objects.collections.ObjectIterator; -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapRemoveTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRemove_present() { - int initialSize = getMap().size(); - assertEquals("remove(present) should return the associated value", v0(), getMap().REMOVE_VALUE(k0())); - assertEquals("remove(present) should decrease a map's size by one.", initialSize - 1, getMap().size()); - expectMissing(e0()); - } - -#if !TYPE_OBJECT - enum WrongType { - INSTANCE; - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRemove_WrongType() { - assertFalse("Should return false if the wrong type is going to be removed", getMap().remove(WrongType.INSTANCE, v0())); - } - -#endif -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testRemove_lastPresent() { - int initialSize = getMap().size(); - assertEquals("remove(present) should return the associated value", v2(), getMap().REMOVE_VALUE(k2())); - assertEquals("remove(present) should decrease a map's size by one.", initialSize - 1, getMap().size()); - expectMissing(e2()); - } - -#if !TYPE_OBJECT -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRemoveObject_present() { - int initialSize = getMap().size(); - assertEquals("remove(present) should return the associated value", VALUE_TO_OBJ(v0()), getMap().remove(KEY_TO_OBJ(k0()))); - assertEquals("remove(present) should decrease a map's size by one.", initialSize - 1, getMap().size()); - expectMissing(e0()); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testRemoveObject_presentLast() { - int initialSize = getMap().size(); - assertEquals("remove(present) should return the associated value", VALUE_TO_OBJ(v2()), getMap().remove(KEY_TO_OBJ(k2()))); - assertEquals("remove(present) should decrease a map's size by one.", initialSize - 1, getMap().size()); - expectMissing(e2()); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRemoveObject_missing() { - int initialSize = getMap().size(); - assertEquals("remove(missing) should return the associated value", VALUE_TO_OBJ(INVALID_VALUE), getMap().remove(KEY_TO_OBJ(k3()))); - assertEquals("remove(missing) should not have changed in size.", initialSize, getMap().size()); - expectUnchanged(); - } - -#endif -#ignore - @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE }) - @CollectionSize.Require(SEVERAL) -#endignore - public void testRemovePresentConcurrentWithEntrySetIteration() { - try { - ObjectIterator iterator = getMap().ENTRY_SET().iterator(); - getMap().REMOVE_VALUE(k0()); - iterator.next(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#if !TYPE_OBJECT -#ignore - @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE }) - @CollectionSize.Require(SEVERAL) -#endignore - public void testRemoveObjectPresentConcurrentWithEntrySetIteration() { - try { - ObjectIterator iterator = getMap().ENTRY_SET().iterator(); - getMap().remove(KEY_TO_OBJ(k0())); - iterator.next(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#endif -#ignore - @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE }) - @CollectionSize.Require(SEVERAL) -#endignore - public void testRemovePresentConcurrentWithKeySetIteration() { - try { - ITERATOR KEY_GENERIC_TYPE iterator = getMap().keySet().iterator(); - getMap().REMOVE_VALUE(k0()); - iterator.NEXT(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#ignore - @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE }) - @CollectionSize.Require(SEVERAL) -#endignore - public void testRemovePresentConcurrentWithValuesIteration() { - try { - VALUE_ITERATOR VALUE_GENERIC_TYPE iterator = getMap().values().iterator(); - getMap().REMOVE_VALUE(k0()); - iterator.VALUE_NEXT(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) -#endignore - public void testRemove_notPresent() { - assertEquals("remove(notPresent) should return INVALID_VALUE", INVALID_VALUE, getMap().REMOVE_VALUE(k3())); - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRemove_unsupported() { - try { - getMap().REMOVE_VALUE(k0()); - fail("remove(present) should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - assertEquals("remove(present) should not remove the element", v0(), get(k0())); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_REMOVE) -#endignore - public void testRemove_unsupportedNotPresent() { - try { - assertEquals("remove(notPresent) should return INVALID_VALUE or throw UnsupportedOperationException", INVALID_VALUE, getMap().REMOVE_VALUE(k3())); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - expectMissing(e3()); - } - -#if !TYPE_OBJECT -#ignore - @MapFeature.Require(absent = SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRemoveObject_unsupported() { - try { - getMap().remove(KEY_TO_OBJ(k0())); - fail("remove(present) should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - assertEquals("remove(present) should not remove the element", VALUE_TO_OBJ(v0()), get(KEY_TO_OBJ(k0()))); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_REMOVE) -#endignore - public void testRemoveObject_unsupportedNotPresent() { - try { - assertEquals("remove(notPresent) should return INVALID_VALUE or throw UnsupportedOperationException", VALUE_TO_OBJ(INVALID_VALUE), getMap().remove(KEY_TO_OBJ(k3()))); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - expectMissing(e3()); - } -#endif +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; +#endignore + +import java.util.ConcurrentModificationException; + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +#if !VALUE_OBJECT +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; +#endif +#if !TYPE_OBJECT && !SAME_TYPE +import speiger.src.collections.PACKAGE.collections.ITERATOR; +#endif +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.collections.objects.collections.ObjectIterator; +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapRemoveTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRemove_present() { + int initialSize = getMap().size(); + assertEquals("remove(present) should return the associated value", v0(), getMap().REMOVE_VALUE(k0())); + assertEquals("remove(present) should decrease a map's size by one.", initialSize - 1, getMap().size()); + expectMissing(e0()); + } + +#if !TYPE_OBJECT + enum WrongType { + INSTANCE; + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRemove_WrongType() { + assertFalse("Should return false if the wrong type is going to be removed", getMap().remove(WrongType.INSTANCE, v0())); + } + +#endif +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testRemove_lastPresent() { + int initialSize = getMap().size(); + assertEquals("remove(present) should return the associated value", v2(), getMap().REMOVE_VALUE(k2())); + assertEquals("remove(present) should decrease a map's size by one.", initialSize - 1, getMap().size()); + expectMissing(e2()); + } + +#if !TYPE_OBJECT +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRemoveObject_present() { + int initialSize = getMap().size(); + assertEquals("remove(present) should return the associated value", VALUE_TO_OBJ(v0()), getMap().remove(KEY_TO_OBJ(k0()))); + assertEquals("remove(present) should decrease a map's size by one.", initialSize - 1, getMap().size()); + expectMissing(e0()); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testRemoveObject_presentLast() { + int initialSize = getMap().size(); + assertEquals("remove(present) should return the associated value", VALUE_TO_OBJ(v2()), getMap().remove(KEY_TO_OBJ(k2()))); + assertEquals("remove(present) should decrease a map's size by one.", initialSize - 1, getMap().size()); + expectMissing(e2()); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRemoveObject_missing() { + int initialSize = getMap().size(); + assertEquals("remove(missing) should return the associated value", VALUE_TO_OBJ(INVALID_VALUE), getMap().remove(KEY_TO_OBJ(k3()))); + assertEquals("remove(missing) should not have changed in size.", initialSize, getMap().size()); + expectUnchanged(); + } + +#endif +#ignore + @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE }) + @CollectionSize.Require(SEVERAL) +#endignore + public void testRemovePresentConcurrentWithEntrySetIteration() { + try { + ObjectIterator iterator = getMap().ENTRY_SET().iterator(); + getMap().REMOVE_VALUE(k0()); + iterator.next(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#if !TYPE_OBJECT +#ignore + @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE }) + @CollectionSize.Require(SEVERAL) +#endignore + public void testRemoveObjectPresentConcurrentWithEntrySetIteration() { + try { + ObjectIterator iterator = getMap().ENTRY_SET().iterator(); + getMap().remove(KEY_TO_OBJ(k0())); + iterator.next(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#endif +#ignore + @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE }) + @CollectionSize.Require(SEVERAL) +#endignore + public void testRemovePresentConcurrentWithKeySetIteration() { + try { + ITERATOR KEY_GENERIC_TYPE iterator = getMap().keySet().iterator(); + getMap().REMOVE_VALUE(k0()); + iterator.NEXT(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#ignore + @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE }) + @CollectionSize.Require(SEVERAL) +#endignore + public void testRemovePresentConcurrentWithValuesIteration() { + try { + VALUE_ITERATOR VALUE_GENERIC_TYPE iterator = getMap().values().iterator(); + getMap().REMOVE_VALUE(k0()); + iterator.VALUE_NEXT(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) +#endignore + public void testRemove_notPresent() { + assertEquals("remove(notPresent) should return INVALID_VALUE", INVALID_VALUE, getMap().REMOVE_VALUE(k3())); + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRemove_unsupported() { + try { + getMap().REMOVE_VALUE(k0()); + fail("remove(present) should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + assertEquals("remove(present) should not remove the element", v0(), get(k0())); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_REMOVE) +#endignore + public void testRemove_unsupportedNotPresent() { + try { + assertEquals("remove(notPresent) should return INVALID_VALUE or throw UnsupportedOperationException", INVALID_VALUE, getMap().REMOVE_VALUE(k3())); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + expectMissing(e3()); + } + +#if !TYPE_OBJECT +#ignore + @MapFeature.Require(absent = SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRemoveObject_unsupported() { + try { + getMap().remove(KEY_TO_OBJ(k0())); + fail("remove(present) should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + assertEquals("remove(present) should not remove the element", VALUE_TO_OBJ(v0()), get(KEY_TO_OBJ(k0()))); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_REMOVE) +#endignore + public void testRemoveObject_unsupportedNotPresent() { + try { + assertEquals("remove(notPresent) should return INVALID_VALUE or throw UnsupportedOperationException", VALUE_TO_OBJ(INVALID_VALUE), getMap().remove(KEY_TO_OBJ(k3()))); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + expectMissing(e3()); + } +#endif } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapReplaceAllTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapReplaceAllTester.template index 79ceaa2..faaef26 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapReplaceAllTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapReplaceAllTester.template @@ -1,110 +1,110 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; -#endignore - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; - -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.collections.objects.lists.ObjectArrayList; -import speiger.src.collections.objects.lists.ObjectList; -import speiger.src.testers.VALUE_PACKAGE.utils.VALUE_SAMPLE_ELEMENTS; -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; -#if !SAME_TYPE -import speiger.src.testers.PACKAGE.utils.SAMPLE_ELEMENTS; -#endif - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapReplaceAllTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ - private SAMPLE_ELEMENTS KEY_GENERIC_TYPE keys() { - return new SAMPLE_ELEMENTSBRACES(k0(), k1(), k2(), k3(), k4()); - } - - private VALUE_SAMPLE_ELEMENTS VALUE_GENERIC_TYPE values() { - return new VALUE_SAMPLE_ELEMENTSVALUE_BRACES(v0(), v1(), v2(), v3(), v4()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) -#endignore - public void testReplaceAllRotate() { - getMap().REPLACE_VALUES((k, v) -> { - int index = keys().asList().indexOf(k); - return values().asList().VALUE_GET_KEY(index + 1); - }); - ObjectList expectedEntries = new ObjectArrayList<>(); - for (MAP.Entry KEY_VALUE_GENERIC_TYPE entry : getSampleEntries()) { - int index = keys().asList().indexOf(entry.ENTRY_KEY()); - expectedEntries.add(entry(entry.ENTRY_KEY(), values().asList().VALUE_GET_KEY(index + 1))); - } - expectContents(expectedEntries); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionFeature.Require(KNOWN_ORDER) -#endignore - public void testReplaceAllPreservesOrder() { - getMap().REPLACE_VALUES((k, v) -> { - int index = keys().asList().indexOf(k); - return values().asList().VALUE_GET_KEY(index + 1); - }); - ObjectList orderedEntries = getOrderedElements(); - int index = 0; - for (KEY_TYPE key : getMap().keySet()) { - assertEquals(orderedEntries.get(index).ENTRY_KEY(), key); - index++; - } - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testReplaceAll_unsupported() { - try { - getMap().REPLACE_VALUES((k, v) -> { - int index = keys().asList().indexOf(k); - return values().asList().VALUE_GET_KEY(index + 1); - }); - fail("REPLACE_VALUES() should throw UnsupportedOperation if a map does " + "not support it and is not empty."); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) - @CollectionSize.Require(ZERO) -#endignore - public void testReplaceAll_unsupportedByEmptyCollection() { - try { - getMap().REPLACE_VALUES((k, v) -> { - int index = keys().asList().indexOf(k); - return values().asList().VALUE_GET_KEY(index + 1); - }); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) -#endignore - public void testReplaceAll_unsupportedNoOpFunction() { - try { - getMap().REPLACE_VALUES((k, v) -> v); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; +#endignore + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.collections.objects.lists.ObjectArrayList; +import speiger.src.collections.objects.lists.ObjectList; +import speiger.src.testers.VALUE_PACKAGE.utils.VALUE_SAMPLE_ELEMENTS; +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; +#if !SAME_TYPE +import speiger.src.testers.PACKAGE.utils.SAMPLE_ELEMENTS; +#endif + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapReplaceAllTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ + private SAMPLE_ELEMENTS KEY_GENERIC_TYPE keys() { + return new SAMPLE_ELEMENTSBRACES(k0(), k1(), k2(), k3(), k4()); + } + + private VALUE_SAMPLE_ELEMENTS VALUE_GENERIC_TYPE values() { + return new VALUE_SAMPLE_ELEMENTSVALUE_BRACES(v0(), v1(), v2(), v3(), v4()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) +#endignore + public void testReplaceAllRotate() { + getMap().REPLACE_VALUES((k, v) -> { + int index = keys().asList().indexOf(k); + return values().asList().VALUE_GET_KEY(index + 1); + }); + ObjectList expectedEntries = new ObjectArrayList<>(); + for (MAP.Entry KEY_VALUE_GENERIC_TYPE entry : getSampleEntries()) { + int index = keys().asList().indexOf(entry.ENTRY_KEY()); + expectedEntries.add(entry(entry.ENTRY_KEY(), values().asList().VALUE_GET_KEY(index + 1))); + } + expectContents(expectedEntries); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionFeature.Require(KNOWN_ORDER) +#endignore + public void testReplaceAllPreservesOrder() { + getMap().REPLACE_VALUES((k, v) -> { + int index = keys().asList().indexOf(k); + return values().asList().VALUE_GET_KEY(index + 1); + }); + ObjectList orderedEntries = getOrderedElements(); + int index = 0; + for (KEY_TYPE key : getMap().keySet()) { + assertEquals(orderedEntries.get(index).ENTRY_KEY(), key); + index++; + } + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testReplaceAll_unsupported() { + try { + getMap().REPLACE_VALUES((k, v) -> { + int index = keys().asList().indexOf(k); + return values().asList().VALUE_GET_KEY(index + 1); + }); + fail("REPLACE_VALUES() should throw UnsupportedOperation if a map does " + "not support it and is not empty."); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) + @CollectionSize.Require(ZERO) +#endignore + public void testReplaceAll_unsupportedByEmptyCollection() { + try { + getMap().REPLACE_VALUES((k, v) -> { + int index = keys().asList().indexOf(k); + return values().asList().VALUE_GET_KEY(index + 1); + }); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) +#endignore + public void testReplaceAll_unsupportedNoOpFunction() { + try { + getMap().REPLACE_VALUES((k, v) -> v); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapReplaceEntryTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapReplaceEntryTester.template index a1d097e..08621e5 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapReplaceEntryTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapReplaceEntryTester.template @@ -1,93 +1,93 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; -#endignore - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; - -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapReplaceEntryTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testReplaceEntry_supportedPresent() { - try { - assertTrue(getMap().replace(k0(), v0(), v3())); - expectReplacement(entry(k0(), v3())); - } catch (ClassCastException tolerated) { // for ClassToInstanceMap - expectUnchanged(); - } - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testReplaceEntry_supportedPresentUnchanged() { - assertTrue(getMap().replace(k0(), v0(), v0())); - expectUnchanged(); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testReplaceEntry_supportedWrongValue() { - assertFalse(getMap().replace(k0(), v3(), v4())); - expectUnchanged(); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) -#endignore - public void testReplaceEntry_supportedAbsentKey() { - assertFalse(getMap().replace(k3(), v3(), v4())); - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testReplaceEntry_unsupportedPresent() { - try { - getMap().replace(k0(), v0(), v3()); - fail("Expected UnsupportedOperationException"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testReplaceEntry_unsupportedWrongValue() { - try { - getMap().replace(k0(), v3(), v4()); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) -#endignore - public void testReplaceEntry_unsupportedAbsentKey() { - try { - getMap().replace(k3(), v3(), v4()); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; +#endignore + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapReplaceEntryTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testReplaceEntry_supportedPresent() { + try { + assertTrue(getMap().replace(k0(), v0(), v3())); + expectReplacement(entry(k0(), v3())); + } catch (ClassCastException tolerated) { // for ClassToInstanceMap + expectUnchanged(); + } + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testReplaceEntry_supportedPresentUnchanged() { + assertTrue(getMap().replace(k0(), v0(), v0())); + expectUnchanged(); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testReplaceEntry_supportedWrongValue() { + assertFalse(getMap().replace(k0(), v3(), v4())); + expectUnchanged(); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) +#endignore + public void testReplaceEntry_supportedAbsentKey() { + assertFalse(getMap().replace(k3(), v3(), v4())); + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testReplaceEntry_unsupportedPresent() { + try { + getMap().replace(k0(), v0(), v3()); + fail("Expected UnsupportedOperationException"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testReplaceEntry_unsupportedWrongValue() { + try { + getMap().replace(k0(), v3(), v4()); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) +#endignore + public void testReplaceEntry_unsupportedAbsentKey() { + try { + getMap().replace(k3(), v3(), v4()); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapReplaceTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapReplaceTester.template index ed3694c..8b7d351 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapReplaceTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapReplaceTester.template @@ -1,63 +1,63 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; -#endignore - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; - -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapReplaceTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testReplace_supportedPresent() { - try { - assertEquals(v0(), getMap().replace(k0(), v3())); - expectReplacement(entry(k0(), v3())); - } catch (ClassCastException tolerated) { // for ClassToInstanceMap - expectUnchanged(); - } - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testReplace_supportedPresentNoChange() { - assertEquals(v0(), getMap().replace(k0(), v0())); - expectUnchanged(); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) -#endignore - public void testReplace_supportedAbsent() { - assertEquals(INVALID_VALUE, getMap().replace(k3(), v3())); - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testReplace_unsupportedPresent() { - try { - getMap().replace(k0(), v3()); - fail("Expected UnsupportedOperationException"); - } catch (UnsupportedOperationException expected) { - } catch (ClassCastException tolerated) { - // for ClassToInstanceMap - } - expectUnchanged(); - } +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; +#endignore + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapReplaceTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testReplace_supportedPresent() { + try { + assertEquals(v0(), getMap().replace(k0(), v3())); + expectReplacement(entry(k0(), v3())); + } catch (ClassCastException tolerated) { // for ClassToInstanceMap + expectUnchanged(); + } + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testReplace_supportedPresentNoChange() { + assertEquals(v0(), getMap().replace(k0(), v0())); + expectUnchanged(); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) +#endignore + public void testReplace_supportedAbsent() { + assertEquals(INVALID_VALUE, getMap().replace(k3(), v3())); + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testReplace_unsupportedPresent() { + try { + getMap().replace(k0(), v3()); + fail("Expected UnsupportedOperationException"); + } catch (UnsupportedOperationException expected) { + } catch (ClassCastException tolerated) { + // for ClassToInstanceMap + } + expectUnchanged(); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapSizeTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapSizeTester.template index bd08454..14dcdd2 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapSizeTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapSizeTester.template @@ -1,14 +1,14 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -import org.junit.Ignore; - -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapSizeTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE { - - public void testSize() { - assertEquals("size():", getNumElements(), getMap().size()); - } -} +package speiger.src.testers.PACKAGE.tests.maps; + +import org.junit.Ignore; + +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapSizeTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE { + + public void testSize() { + assertEquals("size():", getNumElements(), getMap().size()); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapSubFromTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapSubFromTester.template index 4f98835..2c5cc0d 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapSubFromTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapSubFromTester.template @@ -1,148 +1,148 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -import org.junit.Ignore; - -#if VALUE_PRIMITIVES -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; -import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; -#endignore - -import java.util.ConcurrentModificationException; -import java.util.Iterator; - - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; - -import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; -#if !SAME_TYPE -import speiger.src.collections.PACKAGE.collections.ITERATOR; -#endif -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -#endif -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapSubFromTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ -#if VALUE_PRIMITIVES -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testSubFrom_supportedPresent() { - assertEquals("subFrom(present, value) should return the old value", v1(), getMap().subFrom(k1(), v3())); - expectMissing(e1()); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) -#endignore - public void testSubFrom_supportedNotPresent() { - assertEquals("subFrom(notPresent, value) should return INVALID_VALUE", INVALID_VALUE, subFrom(e3())); - expectUnchanged(); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testSubFromSum_supportedNotPresent() { - assertEquals("subFrom(notPresent, value) should return "+v2(), v2(), getMap().subFrom(k2(), v3())); - assertEquals("subFrom(notPresent, value) should return INVALID_VALUE", INVALID_VALUE, subFrom(e2())); - expectMissing(e2()); - } - - -#ignore - @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE }) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testSubFromAbsentConcurrentWithEntrySetIteration() { - try { - Iterator iterator = getMap().ENTRY_SET().iterator(); - subFrom(e3()); - iterator.next(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#ignore - @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE }) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testSubFromAbsentConcurrentWithKeySetIteration() { - try { - ITERATOR KEY_GENERIC_TYPE iterator = getMap().keySet().iterator(); - subFrom(e3()); - iterator.NEXT(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#ignore - @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE }) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testSubFromAbsentConcurrentWithValueIteration() { - try { - VALUE_ITERATOR VALUE_GENERIC_TYPE iterator = getMap().values().iterator(); - subFrom(e3()); - iterator.VALUE_NEXT(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - // success - } - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_REMOVE) -#endignore - public void testSubFrom_unsupportedNotPresent() { - try { - subFrom(e3()); - fail("subFrom(notPresent, value) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - expectMissing(e3()); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testSubFrom_unsupportedPresentExistingValue() { - try { - assertEquals("subFrom(present, existingValue) should return present or throw", v0(), subFrom(e0())); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testSubFrom_unsupportedPresentDifferentValue() { - try { - getMap().subFrom(k0(), v3()); - fail("subFrom(present, differentValue) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } - - private VALUE_TYPE subFrom(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { - return getMap().subFrom(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); - } -#endif -} +package speiger.src.testers.PACKAGE.tests.maps; + +import org.junit.Ignore; + +#if VALUE_PRIMITIVES +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; +import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; +#endignore + +import java.util.ConcurrentModificationException; +import java.util.Iterator; + + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; +#if !SAME_TYPE +import speiger.src.collections.PACKAGE.collections.ITERATOR; +#endif +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +#endif +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapSubFromTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#if VALUE_PRIMITIVES +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testSubFrom_supportedPresent() { + assertEquals("subFrom(present, value) should return the old value", v1(), getMap().subFrom(k1(), v3())); + expectMissing(e1()); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) +#endignore + public void testSubFrom_supportedNotPresent() { + assertEquals("subFrom(notPresent, value) should return INVALID_VALUE", INVALID_VALUE, subFrom(e3())); + expectUnchanged(); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testSubFromSum_supportedNotPresent() { + assertEquals("subFrom(notPresent, value) should return "+v2(), v2(), getMap().subFrom(k2(), v3())); + assertEquals("subFrom(notPresent, value) should return INVALID_VALUE", INVALID_VALUE, subFrom(e2())); + expectMissing(e2()); + } + + +#ignore + @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE }) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testSubFromAbsentConcurrentWithEntrySetIteration() { + try { + Iterator iterator = getMap().ENTRY_SET().iterator(); + subFrom(e3()); + iterator.next(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#ignore + @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE }) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testSubFromAbsentConcurrentWithKeySetIteration() { + try { + ITERATOR KEY_GENERIC_TYPE iterator = getMap().keySet().iterator(); + subFrom(e3()); + iterator.NEXT(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#ignore + @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE }) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testSubFromAbsentConcurrentWithValueIteration() { + try { + VALUE_ITERATOR VALUE_GENERIC_TYPE iterator = getMap().values().iterator(); + subFrom(e3()); + iterator.VALUE_NEXT(); + fail("Expected ConcurrentModificationException"); + } catch (ConcurrentModificationException expected) { + // success + } + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_REMOVE) +#endignore + public void testSubFrom_unsupportedNotPresent() { + try { + subFrom(e3()); + fail("subFrom(notPresent, value) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + expectMissing(e3()); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testSubFrom_unsupportedPresentExistingValue() { + try { + assertEquals("subFrom(present, existingValue) should return present or throw", v0(), subFrom(e0())); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testSubFrom_unsupportedPresentDifferentValue() { + try { + getMap().subFrom(k0(), v3()); + fail("subFrom(present, differentValue) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } + + private VALUE_TYPE subFrom(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { + return getMap().subFrom(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); + } +#endif +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapSupplyIfAbsentTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapSupplyIfAbsentTester.template index 868edfb..4bd9bbe 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapSupplyIfAbsentTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapSupplyIfAbsentTester.template @@ -1,131 +1,131 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; -#endignore -#if !VALUE_BOOLEAN -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ONE; -#endignore -#endif - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; - -import junit.framework.AssertionFailedError; -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapSupplyIfAbsentTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ -#ignore - @MapFeature.Require(SUPPORTS_PUT) -#endignore - public void testSupplyIfAbsent_supportedAbsent() { - assertEquals("SUPPLY_IF_ABSENT(notPresent, function) should return new value", v3(), - getMap().SUPPLY_IF_ABSENT(k3(), this::v3)); - expectAdded(e3()); - } - -#if !VALUE_BOOLEAN -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(ONE) -#endignore - public void testSupplyIfAbsent_supportedAbsentFirst() { - getMap().setDefaultReturnValue(v0()); - assertEquals("SUPPLY_IF_ABSENT(notPresent, function) should return new value", v3(), - getMap().SUPPLY_IF_ABSENT(k0(), this::v3)); - expectContents(entry(k0(), v3())); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(ONE) -#endignore - public void testSupplyIfAbsent_supportedAbsentSameResult() { - getMap().setDefaultReturnValue(v0()); - assertEquals("SUPPLY_IF_ABSENT(notPresent, function) should return new value", v0(), - getMap().SUPPLY_IF_ABSENT(k0(), this::v0)); - expectUnchanged(); - } - -#endif -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testSupplyIfAbsent_supportedPresent() { - assertEquals("SUPPLY_IF_ABSENT(present, function) should return existing value", v0(), - getMap().SUPPLY_IF_ABSENT(k0(), () -> { - throw new AssertionFailedError(); - })); - expectUnchanged(); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) -#endignore - public void testSupplyIfAbsent_functionReturnsNullNotInserted() { - assertEquals("SUPPLY_IF_ABSENT(absent, returnsNull) should return INVALID_VALUE", INVALID_VALUE, getMap().SUPPLY_IF_ABSENT(k3(), () -> INVALID_VALUE)); - expectUnchanged(); - } - - static class ExpectedException extends RuntimeException { - private static final long serialVersionUID = 1L; - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) -#endignore - public void testSupplyIfAbsent_functionThrows() { - try { - getMap().SUPPLY_IF_ABSENT(k3(), () -> { - throw new ExpectedException(); - }); - fail("Expected ExpectedException"); - } catch (ExpectedException expected) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) -#endignore - public void testSupplyIfAbsent_unsupportedAbsent() { - try { - getMap().SUPPLY_IF_ABSENT(k3(), this::v3); - fail("SUPPLY_IF_ABSENT(notPresent, function) should throw"); - } catch (UnsupportedOperationException expected) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testSupplyIfAbsent_unsupportedPresentExistingValue() { - try { - assertEquals("SUPPLY_IF_ABSENT(present, returnsCurrentValue) should return present or throw", v0(), getMap().SUPPLY_IF_ABSENT(k0(), this::v0)); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testSupplyIfAbsent_unsupportedPresentDifferentValue() { - try { - assertEquals("SUPPLY_IF_ABSENT(present, returnsDifferentValue) should return present or throw", v0(), getMap().SUPPLY_IF_ABSENT(k0(), this::v3)); - } catch (UnsupportedOperationException tolerated) { - } - expectUnchanged(); - } -} +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; +#endignore +#if !VALUE_BOOLEAN +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ONE; +#endignore +#endif + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +import junit.framework.AssertionFailedError; +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapSupplyIfAbsentTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ +#ignore + @MapFeature.Require(SUPPORTS_PUT) +#endignore + public void testSupplyIfAbsent_supportedAbsent() { + assertEquals("SUPPLY_IF_ABSENT(notPresent, function) should return new value", v3(), + getMap().SUPPLY_IF_ABSENT(k3(), this::v3)); + expectAdded(e3()); + } + +#if !VALUE_BOOLEAN +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(ONE) +#endignore + public void testSupplyIfAbsent_supportedAbsentFirst() { + getMap().setDefaultReturnValue(v0()); + assertEquals("SUPPLY_IF_ABSENT(notPresent, function) should return new value", v3(), + getMap().SUPPLY_IF_ABSENT(k0(), this::v3)); + expectContents(entry(k0(), v3())); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(ONE) +#endignore + public void testSupplyIfAbsent_supportedAbsentSameResult() { + getMap().setDefaultReturnValue(v0()); + assertEquals("SUPPLY_IF_ABSENT(notPresent, function) should return new value", v0(), + getMap().SUPPLY_IF_ABSENT(k0(), this::v0)); + expectUnchanged(); + } + +#endif +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testSupplyIfAbsent_supportedPresent() { + assertEquals("SUPPLY_IF_ABSENT(present, function) should return existing value", v0(), + getMap().SUPPLY_IF_ABSENT(k0(), () -> { + throw new AssertionFailedError(); + })); + expectUnchanged(); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) +#endignore + public void testSupplyIfAbsent_functionReturnsNullNotInserted() { + assertEquals("SUPPLY_IF_ABSENT(absent, returnsNull) should return INVALID_VALUE", INVALID_VALUE, getMap().SUPPLY_IF_ABSENT(k3(), () -> INVALID_VALUE)); + expectUnchanged(); + } + + static class ExpectedException extends RuntimeException { + private static final long serialVersionUID = 1L; + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) +#endignore + public void testSupplyIfAbsent_functionThrows() { + try { + getMap().SUPPLY_IF_ABSENT(k3(), () -> { + throw new ExpectedException(); + }); + fail("Expected ExpectedException"); + } catch (ExpectedException expected) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) +#endignore + public void testSupplyIfAbsent_unsupportedAbsent() { + try { + getMap().SUPPLY_IF_ABSENT(k3(), this::v3); + fail("SUPPLY_IF_ABSENT(notPresent, function) should throw"); + } catch (UnsupportedOperationException expected) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testSupplyIfAbsent_unsupportedPresentExistingValue() { + try { + assertEquals("SUPPLY_IF_ABSENT(present, returnsCurrentValue) should return present or throw", v0(), getMap().SUPPLY_IF_ABSENT(k0(), this::v0)); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testSupplyIfAbsent_unsupportedPresentDifferentValue() { + try { + assertEquals("SUPPLY_IF_ABSENT(present, returnsDifferentValue) should return present or throw", v0(), getMap().SUPPLY_IF_ABSENT(k0(), this::v3)); + } catch (UnsupportedOperationException tolerated) { + } + expectUnchanged(); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapToStringTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapToStringTester.template index 9cf007b..4bd3d81 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapToStringTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/MapToStringTester.template @@ -1,58 +1,58 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.NON_STANDARD_TOSTRING; -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import java.util.Set; - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.maps.impl.hash.LINKED_HASH_MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapToStringTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ - public void testToString_minimal() { - assertNotNull("toString() should not return null", getMap().toString()); - } - -#ignore - @CollectionSize.Require(ZERO) - @CollectionFeature.Require(absent = NON_STANDARD_TOSTRING) -#endignore - public void testToString_size0() { - assertEquals("emptyMap.toString should return {}", "{}", getMap().toString()); - } - -#ignore - @CollectionSize.Require(ONE) - @CollectionFeature.Require(absent = NON_STANDARD_TOSTRING) -#endignore - public void testToString_size1() { - assertEquals("size1Map.toString should return {entry}", "{" + e0() + "}", getMap().toString()); - } - -#ignore - @CollectionFeature.Require(absent = NON_STANDARD_TOSTRING) -#endignore - public void testToString_formatting() { - assertEquals("map.toString() incorrect", expectedToString(getMap().ENTRY_SET()), getMap().toString()); - } - - private String expectedToString(Set entries) { - MAP KEY_VALUE_GENERIC_TYPE reference = new LINKED_HASH_MAPKV_BRACES(); - for (MAP.Entry KEY_VALUE_GENERIC_TYPE entry : entries) { - reference.put(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); - } - return reference.toString(); - } +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.NON_STANDARD_TOSTRING; +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import java.util.Set; + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.maps.impl.hash.LINKED_HASH_MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapToStringTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ + public void testToString_minimal() { + assertNotNull("toString() should not return null", getMap().toString()); + } + +#ignore + @CollectionSize.Require(ZERO) + @CollectionFeature.Require(absent = NON_STANDARD_TOSTRING) +#endignore + public void testToString_size0() { + assertEquals("emptyMap.toString should return {}", "{}", getMap().toString()); + } + +#ignore + @CollectionSize.Require(ONE) + @CollectionFeature.Require(absent = NON_STANDARD_TOSTRING) +#endignore + public void testToString_size1() { + assertEquals("size1Map.toString should return {entry}", "{" + e0() + "}", getMap().toString()); + } + +#ignore + @CollectionFeature.Require(absent = NON_STANDARD_TOSTRING) +#endignore + public void testToString_formatting() { + assertEquals("map.toString() incorrect", expectedToString(getMap().ENTRY_SET()), getMap().toString()); + } + + private String expectedToString(Set entries) { + MAP KEY_VALUE_GENERIC_TYPE reference = new LINKED_HASH_MAPKV_BRACES(); + for (MAP.Entry KEY_VALUE_GENERIC_TYPE entry : entries) { + reference.put(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); + } + return reference.toString(); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/NavigableMapNavigationTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/NavigableMapNavigationTester.template index d3c029c..67fdd48 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/NavigableMapNavigationTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/NavigableMapNavigationTester.template @@ -1,333 +1,333 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; -#endignore - -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; - -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.functions.COMPARATOR; -#endif -import speiger.src.collections.PACKAGE.maps.interfaces.MAP.Entry; -import speiger.src.collections.PACKAGE.maps.interfaces.NAVIGABLE_MAP; -import speiger.src.collections.objects.lists.ObjectArrayList; -import speiger.src.collections.objects.lists.ObjectList; -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; -import speiger.src.testers.objects.utils.ObjectHelpers; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPENavigableMapNavigationTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ - private NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE navigableMap; - private List entries; - private Entry KEY_VALUE_GENERIC_TYPE a; - private Entry KEY_VALUE_GENERIC_TYPE b; - private Entry KEY_VALUE_GENERIC_TYPE c; - - @Override - public void setUp() throws Exception { - super.setUp(); - navigableMap = (NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE) getMap(); - entries = ObjectHelpers.copyToList(getSampleElements(getNumElements())); - entries.sort(entryComparator(navigableMap.comparator())); - if (entries.size() >= 1) { - a = entries.get(0); - if (entries.size() >= 3) { - b = entries.get(1); - c = entries.get(2); - } - } - } - - public static GENERIC_KEY_VALUE_BRACES Comparator entryComparator(COMPARATOR KEY_GENERIC_TYPE keyComparator) { - return new Comparator() { - @Override - public int compare(Entry KEY_VALUE_GENERIC_TYPE a, Entry KEY_VALUE_GENERIC_TYPE b) { - return (keyComparator == null) ? COMPAREABLE_TO_KEY(a.ENTRY_KEY(), b.ENTRY_KEY()) : keyComparator.compare(a.ENTRY_KEY(), b.ENTRY_KEY()); - } - }; - } - - @SuppressWarnings("unchecked") - private void resetWithHole() { - Entry KEY_VALUE_GENERIC_TYPE[] entries = new Entry[] { a, c }; - super.resetMap(entries); - navigableMap = (NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE) getMap(); - } - -#ignore - @CollectionSize.Require(ZERO) -#endignore - public void testEmptyMapFirst() { - assertNull(navigableMap.firstEntry()); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ZERO) -#endignore - public void testEmptyMapPollFirst() { - assertNull(navigableMap.pollFirstEntry()); - } - -#ignore - @CollectionSize.Require(ZERO) -#endignore - public void testEmptyMapNearby() { -#if TYPE_OBJECT - assertNull(navigableMap.lowerEntry(k0())); - assertNull(navigableMap.lowerKey(k0())); - assertNull(navigableMap.floorEntry(k0())); - assertNull(navigableMap.floorKey(k0())); - assertNull(navigableMap.ceilingEntry(k0())); - assertNull(navigableMap.ceilingKey(k0())); - assertNull(navigableMap.higherEntry(k0())); - assertNull(navigableMap.higherKey(k0())); -#else - assertNull(navigableMap.lowerEntry(k0())); - assertEquals(CLASS_TYPE.MAX_VALUE, navigableMap.lowerKey(k0())); - assertNull(navigableMap.floorEntry(k0())); - assertEquals(CLASS_TYPE.MAX_VALUE, navigableMap.floorKey(k0())); - assertNull(navigableMap.ceilingEntry(k0())); - assertEquals(CLASS_TYPE.MIN_VALUE, navigableMap.ceilingKey(k0())); - assertNull(navigableMap.higherEntry(k0())); - assertEquals(CLASS_TYPE.MIN_VALUE, navigableMap.higherKey(k0())); -#endif - } - -#ignore - @CollectionSize.Require(ZERO) -#endignore - public void testEmptyMapLast() { - assertNull(navigableMap.lastEntry()); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ZERO) -#endignore - public void testEmptyMapPollLast() { - assertNull(navigableMap.pollLastEntry()); - } - -#ignore - @CollectionSize.Require(ONE) -#endignore - public void testSingletonMapFirst() { - assertEquals(a, navigableMap.firstEntry()); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ONE) -#endignore - public void testSingletonMapPollFirst() { - assertEquals(a, navigableMap.pollFirstEntry()); - assertTrue(navigableMap.isEmpty()); - } - -#ignore - @CollectionSize.Require(ONE) -#endignore - public void testSingletonMapNearby() { -#if TYPE_OBJECT - assertNull(navigableMap.lowerEntry(k0())); - assertNull(navigableMap.lowerKey(k0())); - assertEquals(a, navigableMap.floorEntry(k0())); - assertEquals(a.ENTRY_KEY(), navigableMap.floorKey(k0())); - assertEquals(a, navigableMap.ceilingEntry(k0())); - assertEquals(a.ENTRY_KEY(), navigableMap.ceilingKey(k0())); - assertNull(navigableMap.higherEntry(k0())); - assertNull(navigableMap.higherKey(k0())); -#else - assertNull(navigableMap.lowerEntry(k0())); - assertEquals(CLASS_TYPE.MAX_VALUE, navigableMap.lowerKey(k0())); - assertEquals(a, navigableMap.floorEntry(k0())); - assertEquals(a.ENTRY_KEY(), navigableMap.floorKey(k0())); - assertEquals(a, navigableMap.ceilingEntry(k0())); - assertEquals(a.ENTRY_KEY(), navigableMap.ceilingKey(k0())); - assertNull(navigableMap.higherEntry(k0())); - assertEquals(CLASS_TYPE.MIN_VALUE, navigableMap.higherKey(k0())); -#endif - } - -#ignore - @CollectionSize.Require(ONE) -#endignore - public void testSingletonMapLast() { - assertEquals(a, navigableMap.lastEntry()); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ONE) -#endignore - public void testSingletonMapPollLast() { - assertEquals(a, navigableMap.pollLastEntry()); - assertTrue(navigableMap.isEmpty()); - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testFirst() { - assertEquals(a, navigableMap.firstEntry()); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testPollFirst() { - assertEquals(a, navigableMap.pollFirstEntry()); - assertEquals(entries.subList(1, entries.size()), ObjectHelpers.copyToList(navigableMap.ENTRY_SET())); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_REMOVE) -#endignore - public void testPollFirstUnsupported() { - try { - navigableMap.pollFirstEntry(); - fail(); - } catch (UnsupportedOperationException e) { - } - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testLower() { - resetWithHole(); - assertEquals(null, navigableMap.lowerEntry(a.ENTRY_KEY())); -#if TYPE_OBJECT - assertNull(navigableMap.lowerKey(a.ENTRY_KEY())); -#else - assertEquals(CLASS_TYPE.MAX_VALUE, navigableMap.lowerKey(a.ENTRY_KEY())); -#endif - assertEquals(a, navigableMap.lowerEntry(b.ENTRY_KEY())); - assertEquals(a.ENTRY_KEY(), navigableMap.lowerKey(b.ENTRY_KEY())); - assertEquals(a, navigableMap.lowerEntry(c.ENTRY_KEY())); - assertEquals(a.ENTRY_KEY(), navigableMap.lowerKey(c.ENTRY_KEY())); - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testFloor() { - resetWithHole(); - assertEquals(a, navigableMap.floorEntry(a.ENTRY_KEY())); - assertEquals(a.ENTRY_KEY(), navigableMap.floorKey(a.ENTRY_KEY())); - assertEquals(a, navigableMap.floorEntry(b.ENTRY_KEY())); - assertEquals(a.ENTRY_KEY(), navigableMap.floorKey(b.ENTRY_KEY())); - assertEquals(c, navigableMap.floorEntry(c.ENTRY_KEY())); - assertEquals(c.ENTRY_KEY(), navigableMap.floorKey(c.ENTRY_KEY())); - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testCeiling() { - resetWithHole(); - assertEquals(a, navigableMap.ceilingEntry(a.ENTRY_KEY())); - assertEquals(a.ENTRY_KEY(), navigableMap.ceilingKey(a.ENTRY_KEY())); - assertEquals(c, navigableMap.ceilingEntry(b.ENTRY_KEY())); - assertEquals(c.ENTRY_KEY(), navigableMap.ceilingKey(b.ENTRY_KEY())); - assertEquals(c, navigableMap.ceilingEntry(c.ENTRY_KEY())); - assertEquals(c.ENTRY_KEY(), navigableMap.ceilingKey(c.ENTRY_KEY())); - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testHigher() { - resetWithHole(); - assertEquals(c, navigableMap.higherEntry(a.ENTRY_KEY())); - assertEquals(c.ENTRY_KEY(), navigableMap.higherKey(a.ENTRY_KEY())); - assertEquals(c, navigableMap.higherEntry(b.ENTRY_KEY())); - assertEquals(c.ENTRY_KEY(), navigableMap.higherKey(b.ENTRY_KEY())); - assertEquals(null, navigableMap.higherEntry(c.ENTRY_KEY())); -#if TYPE_OBJECT - assertNull(navigableMap.higherKey(c.ENTRY_KEY())); -#else - assertEquals(CLASS_TYPE.MIN_VALUE, navigableMap.higherKey(c.ENTRY_KEY())); -#endif - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testLast() { - assertEquals(c, navigableMap.lastEntry()); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testPollLast() { - assertEquals(c, navigableMap.pollLastEntry()); - assertEquals(entries.subList(0, entries.size() - 1), ObjectHelpers.copyToList(navigableMap.ENTRY_SET())); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testPollLastUnsupported() { - try { - navigableMap.pollLastEntry(); - fail(); - } catch (UnsupportedOperationException e) { - } - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testDescendingNavigation() { - ObjectList descending = new ObjectArrayList<>(navigableMap.descendingMap().ENTRY_SET()); - Collections.reverse(descending); - assertEquals(entries, descending); - } - -#ignore - @CollectionSize.Require(absent = ZERO) -#endignore - public void testHeadMapExclusive() { - assertFalse(navigableMap.headMap(a.ENTRY_KEY(), false).containsKey(a.ENTRY_KEY())); - } - -#ignore - @CollectionSize.Require(absent = ZERO) -#endignore - public void testHeadMapInclusive() { - assertTrue(navigableMap.headMap(a.ENTRY_KEY(), true).containsKey(a.ENTRY_KEY())); - } - -#ignore - @CollectionSize.Require(absent = ZERO) -#endignore - public void testTailMapExclusive() { - assertFalse(navigableMap.tailMap(a.ENTRY_KEY(), false).containsKey(a.ENTRY_KEY())); - } - -#ignore - @CollectionSize.Require(absent = ZERO) -#endignore - public void testTailMapInclusive() { - assertTrue(navigableMap.tailMap(a.ENTRY_KEY(), true).containsKey(a.ENTRY_KEY())); - } -} +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; +#endignore + +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.functions.COMPARATOR; +#endif +import speiger.src.collections.PACKAGE.maps.interfaces.MAP.Entry; +import speiger.src.collections.PACKAGE.maps.interfaces.NAVIGABLE_MAP; +import speiger.src.collections.objects.lists.ObjectArrayList; +import speiger.src.collections.objects.lists.ObjectList; +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; +import speiger.src.testers.objects.utils.ObjectHelpers; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPENavigableMapNavigationTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ + private NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE navigableMap; + private List entries; + private Entry KEY_VALUE_GENERIC_TYPE a; + private Entry KEY_VALUE_GENERIC_TYPE b; + private Entry KEY_VALUE_GENERIC_TYPE c; + + @Override + public void setUp() throws Exception { + super.setUp(); + navigableMap = (NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE) getMap(); + entries = ObjectHelpers.copyToList(getSampleElements(getNumElements())); + entries.sort(entryComparator(navigableMap.comparator())); + if (entries.size() >= 1) { + a = entries.get(0); + if (entries.size() >= 3) { + b = entries.get(1); + c = entries.get(2); + } + } + } + + public static GENERIC_KEY_VALUE_BRACES Comparator entryComparator(COMPARATOR KEY_GENERIC_TYPE keyComparator) { + return new Comparator() { + @Override + public int compare(Entry KEY_VALUE_GENERIC_TYPE a, Entry KEY_VALUE_GENERIC_TYPE b) { + return (keyComparator == null) ? COMPAREABLE_TO_KEY(a.ENTRY_KEY(), b.ENTRY_KEY()) : keyComparator.compare(a.ENTRY_KEY(), b.ENTRY_KEY()); + } + }; + } + + @SuppressWarnings("unchecked") + private void resetWithHole() { + Entry KEY_VALUE_GENERIC_TYPE[] entries = new Entry[] { a, c }; + super.resetMap(entries); + navigableMap = (NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE) getMap(); + } + +#ignore + @CollectionSize.Require(ZERO) +#endignore + public void testEmptyMapFirst() { + assertNull(navigableMap.firstEntry()); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ZERO) +#endignore + public void testEmptyMapPollFirst() { + assertNull(navigableMap.pollFirstEntry()); + } + +#ignore + @CollectionSize.Require(ZERO) +#endignore + public void testEmptyMapNearby() { +#if TYPE_OBJECT + assertNull(navigableMap.lowerEntry(k0())); + assertNull(navigableMap.lowerKey(k0())); + assertNull(navigableMap.floorEntry(k0())); + assertNull(navigableMap.floorKey(k0())); + assertNull(navigableMap.ceilingEntry(k0())); + assertNull(navigableMap.ceilingKey(k0())); + assertNull(navigableMap.higherEntry(k0())); + assertNull(navigableMap.higherKey(k0())); +#else + assertNull(navigableMap.lowerEntry(k0())); + assertEquals(CLASS_TYPE.MAX_VALUE, navigableMap.lowerKey(k0())); + assertNull(navigableMap.floorEntry(k0())); + assertEquals(CLASS_TYPE.MAX_VALUE, navigableMap.floorKey(k0())); + assertNull(navigableMap.ceilingEntry(k0())); + assertEquals(CLASS_TYPE.MIN_VALUE, navigableMap.ceilingKey(k0())); + assertNull(navigableMap.higherEntry(k0())); + assertEquals(CLASS_TYPE.MIN_VALUE, navigableMap.higherKey(k0())); +#endif + } + +#ignore + @CollectionSize.Require(ZERO) +#endignore + public void testEmptyMapLast() { + assertNull(navigableMap.lastEntry()); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ZERO) +#endignore + public void testEmptyMapPollLast() { + assertNull(navigableMap.pollLastEntry()); + } + +#ignore + @CollectionSize.Require(ONE) +#endignore + public void testSingletonMapFirst() { + assertEquals(a, navigableMap.firstEntry()); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ONE) +#endignore + public void testSingletonMapPollFirst() { + assertEquals(a, navigableMap.pollFirstEntry()); + assertTrue(navigableMap.isEmpty()); + } + +#ignore + @CollectionSize.Require(ONE) +#endignore + public void testSingletonMapNearby() { +#if TYPE_OBJECT + assertNull(navigableMap.lowerEntry(k0())); + assertNull(navigableMap.lowerKey(k0())); + assertEquals(a, navigableMap.floorEntry(k0())); + assertEquals(a.ENTRY_KEY(), navigableMap.floorKey(k0())); + assertEquals(a, navigableMap.ceilingEntry(k0())); + assertEquals(a.ENTRY_KEY(), navigableMap.ceilingKey(k0())); + assertNull(navigableMap.higherEntry(k0())); + assertNull(navigableMap.higherKey(k0())); +#else + assertNull(navigableMap.lowerEntry(k0())); + assertEquals(CLASS_TYPE.MAX_VALUE, navigableMap.lowerKey(k0())); + assertEquals(a, navigableMap.floorEntry(k0())); + assertEquals(a.ENTRY_KEY(), navigableMap.floorKey(k0())); + assertEquals(a, navigableMap.ceilingEntry(k0())); + assertEquals(a.ENTRY_KEY(), navigableMap.ceilingKey(k0())); + assertNull(navigableMap.higherEntry(k0())); + assertEquals(CLASS_TYPE.MIN_VALUE, navigableMap.higherKey(k0())); +#endif + } + +#ignore + @CollectionSize.Require(ONE) +#endignore + public void testSingletonMapLast() { + assertEquals(a, navigableMap.lastEntry()); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ONE) +#endignore + public void testSingletonMapPollLast() { + assertEquals(a, navigableMap.pollLastEntry()); + assertTrue(navigableMap.isEmpty()); + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testFirst() { + assertEquals(a, navigableMap.firstEntry()); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testPollFirst() { + assertEquals(a, navigableMap.pollFirstEntry()); + assertEquals(entries.subList(1, entries.size()), ObjectHelpers.copyToList(navigableMap.ENTRY_SET())); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_REMOVE) +#endignore + public void testPollFirstUnsupported() { + try { + navigableMap.pollFirstEntry(); + fail(); + } catch (UnsupportedOperationException e) { + } + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testLower() { + resetWithHole(); + assertEquals(null, navigableMap.lowerEntry(a.ENTRY_KEY())); +#if TYPE_OBJECT + assertNull(navigableMap.lowerKey(a.ENTRY_KEY())); +#else + assertEquals(CLASS_TYPE.MAX_VALUE, navigableMap.lowerKey(a.ENTRY_KEY())); +#endif + assertEquals(a, navigableMap.lowerEntry(b.ENTRY_KEY())); + assertEquals(a.ENTRY_KEY(), navigableMap.lowerKey(b.ENTRY_KEY())); + assertEquals(a, navigableMap.lowerEntry(c.ENTRY_KEY())); + assertEquals(a.ENTRY_KEY(), navigableMap.lowerKey(c.ENTRY_KEY())); + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testFloor() { + resetWithHole(); + assertEquals(a, navigableMap.floorEntry(a.ENTRY_KEY())); + assertEquals(a.ENTRY_KEY(), navigableMap.floorKey(a.ENTRY_KEY())); + assertEquals(a, navigableMap.floorEntry(b.ENTRY_KEY())); + assertEquals(a.ENTRY_KEY(), navigableMap.floorKey(b.ENTRY_KEY())); + assertEquals(c, navigableMap.floorEntry(c.ENTRY_KEY())); + assertEquals(c.ENTRY_KEY(), navigableMap.floorKey(c.ENTRY_KEY())); + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testCeiling() { + resetWithHole(); + assertEquals(a, navigableMap.ceilingEntry(a.ENTRY_KEY())); + assertEquals(a.ENTRY_KEY(), navigableMap.ceilingKey(a.ENTRY_KEY())); + assertEquals(c, navigableMap.ceilingEntry(b.ENTRY_KEY())); + assertEquals(c.ENTRY_KEY(), navigableMap.ceilingKey(b.ENTRY_KEY())); + assertEquals(c, navigableMap.ceilingEntry(c.ENTRY_KEY())); + assertEquals(c.ENTRY_KEY(), navigableMap.ceilingKey(c.ENTRY_KEY())); + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testHigher() { + resetWithHole(); + assertEquals(c, navigableMap.higherEntry(a.ENTRY_KEY())); + assertEquals(c.ENTRY_KEY(), navigableMap.higherKey(a.ENTRY_KEY())); + assertEquals(c, navigableMap.higherEntry(b.ENTRY_KEY())); + assertEquals(c.ENTRY_KEY(), navigableMap.higherKey(b.ENTRY_KEY())); + assertEquals(null, navigableMap.higherEntry(c.ENTRY_KEY())); +#if TYPE_OBJECT + assertNull(navigableMap.higherKey(c.ENTRY_KEY())); +#else + assertEquals(CLASS_TYPE.MIN_VALUE, navigableMap.higherKey(c.ENTRY_KEY())); +#endif + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testLast() { + assertEquals(c, navigableMap.lastEntry()); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testPollLast() { + assertEquals(c, navigableMap.pollLastEntry()); + assertEquals(entries.subList(0, entries.size() - 1), ObjectHelpers.copyToList(navigableMap.ENTRY_SET())); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testPollLastUnsupported() { + try { + navigableMap.pollLastEntry(); + fail(); + } catch (UnsupportedOperationException e) { + } + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testDescendingNavigation() { + ObjectList descending = new ObjectArrayList<>(navigableMap.descendingMap().ENTRY_SET()); + Collections.reverse(descending); + assertEquals(entries, descending); + } + +#ignore + @CollectionSize.Require(absent = ZERO) +#endignore + public void testHeadMapExclusive() { + assertFalse(navigableMap.headMap(a.ENTRY_KEY(), false).containsKey(a.ENTRY_KEY())); + } + +#ignore + @CollectionSize.Require(absent = ZERO) +#endignore + public void testHeadMapInclusive() { + assertTrue(navigableMap.headMap(a.ENTRY_KEY(), true).containsKey(a.ENTRY_KEY())); + } + +#ignore + @CollectionSize.Require(absent = ZERO) +#endignore + public void testTailMapExclusive() { + assertFalse(navigableMap.tailMap(a.ENTRY_KEY(), false).containsKey(a.ENTRY_KEY())); + } + +#ignore + @CollectionSize.Require(absent = ZERO) +#endignore + public void testTailMapInclusive() { + assertTrue(navigableMap.tailMap(a.ENTRY_KEY(), true).containsKey(a.ENTRY_KEY())); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/OrderedMapMoveTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/OrderedMapMoveTester.template index 351f2c9..2115eea 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/OrderedMapMoveTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/OrderedMapMoveTester.template @@ -1,374 +1,374 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; -import static org.junit.Assert.assertNotEquals; -#endignore - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; - -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP; -import speiger.src.collections.objects.lists.ObjectList; -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; -import speiger.src.testers.objects.utils.ObjectHelpers; - -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPEOrderedMapMoveTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ - private ORDERED_MAP KEY_VALUE_GENERIC_TYPE orderedMap; - private ObjectList values; - private KEY_TYPE a; - private VALUE_TYPE aValue; - private KEY_TYPE c; - private VALUE_TYPE cValue; - - @Override - public void setUp() throws Exception { - super.setUp(); - orderedMap = (ORDERED_MAP KEY_VALUE_GENERIC_TYPE)getMap(); - values = ObjectHelpers.copyToList(getSampleElements(getSubjectGenerator().getCollectionSize().getNumElements())); - if (values.size() >= 1) { - a = values.get(0).ENTRY_KEY(); - aValue = values.get(0).ENTRY_VALUE(); - if (values.size() >= 3) { - c = values.get(2).ENTRY_KEY(); - cValue = values.get(2).ENTRY_VALUE(); - } - } - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(SEVERAL) -#endignore - public void testaddMoveToFirstMissing() - { - assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); - assertEquals(INVALID_VALUE, orderedMap.putAndMoveToFirst(k4(), v4())); - assertNotEquals(a, orderedMap.FIRST_ENTRY_KEY()); - assertEquals(k4(), orderedMap.FIRST_ENTRY_KEY()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(SEVERAL) -#endignore - public void testaddMoveToFirstPreset() - { - assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); - assertEquals(cValue, orderedMap.putAndMoveToFirst(c, v4())); - assertNotEquals(a, orderedMap.FIRST_ENTRY_KEY()); - assertEquals(c, orderedMap.FIRST_ENTRY_KEY()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(SEVERAL) -#endignore - public void testaddMoveToLastMissing() - { - assertEquals(c, orderedMap.LAST_ENTRY_KEY()); - assertEquals(INVALID_VALUE, orderedMap.putAndMoveToLast(k4(), v4())); - assertNotEquals(c, orderedMap.LAST_ENTRY_KEY()); - assertEquals(k4(), orderedMap.LAST_ENTRY_KEY()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(SEVERAL) -#endignore - public void testaddMoveToLastPreset() - { - assertEquals(c, orderedMap.LAST_ENTRY_KEY()); - assertEquals(aValue, orderedMap.putAndMoveToLast(a, v4())); - assertNotEquals(c, orderedMap.LAST_ENTRY_KEY()); - assertEquals(a, orderedMap.LAST_ENTRY_KEY()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(SEVERAL) -#endignore - public void testMoveToFirstMissing() - { - assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); - assertEquals(false, orderedMap.moveToFirst(k4())); - assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(SEVERAL) -#endignore - public void testMoveToFirstPreset() - { - assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); - assertEquals(true, orderedMap.moveToFirst(c)); - assertNotEquals(a, orderedMap.FIRST_ENTRY_KEY()); - assertEquals(c, orderedMap.FIRST_ENTRY_KEY()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(SEVERAL) -#endignore - public void testMoveToLastMissing() - { - assertEquals(c, orderedMap.LAST_ENTRY_KEY()); - assertEquals(false, orderedMap.moveToLast(k4())); - assertEquals(c, orderedMap.LAST_ENTRY_KEY()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(SEVERAL) -#endignore - public void testMoveToLastPreset() - { - assertEquals(c, orderedMap.LAST_ENTRY_KEY()); - assertEquals(true, orderedMap.moveToLast(a)); - assertNotEquals(c, orderedMap.LAST_ENTRY_KEY()); - assertEquals(a, orderedMap.LAST_ENTRY_KEY()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(SEVERAL) -#endignore - public void testGetAndMoveToFirstMissing() - { - assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); - assertEquals(INVALID_VALUE, orderedMap.getAndMoveToFirst(k4())); - assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(SEVERAL) -#endignore - public void testGetAndMoveToFirstPreset() - { - assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); - assertEquals(cValue, orderedMap.getAndMoveToFirst(c)); - assertNotEquals(a, orderedMap.FIRST_ENTRY_KEY()); - assertEquals(c, orderedMap.FIRST_ENTRY_KEY()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(SEVERAL) -#endignore - public void testGetAndMoveToLastMissing() - { - assertEquals(c, orderedMap.LAST_ENTRY_KEY()); - assertEquals(INVALID_VALUE, orderedMap.getAndMoveToLast(k4())); - assertEquals(c, orderedMap.LAST_ENTRY_KEY()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(SEVERAL) -#endignore - public void testGetAndMoveToLastPreset() - { - assertEquals(c, orderedMap.LAST_ENTRY_KEY()); - assertEquals(aValue, orderedMap.getAndMoveToLast(a)); - assertNotEquals(c, orderedMap.LAST_ENTRY_KEY()); - assertEquals(a, orderedMap.LAST_ENTRY_KEY()); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) -#endignore - public void testaddMoveToFirstUnsupported() - { - try { - orderedMap.putAndMoveToFirst(k4(), v4()); - fail("addAndMoveToFirst should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException e) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) -#endignore - public void testaddMoveToLastUnsupported() - { - try { - orderedMap.putAndMoveToFirst(k4(), v4()); - fail("addAndMoveToLast should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException e) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) -#endignore - public void testMoveToFirstUnsupported() - { - try { - orderedMap.moveToFirst(c); - fail("moveToFirst should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException e) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) -#endignore - public void testMoveToLastUnsupported() - { - try { - orderedMap.moveToLast(a); - fail("moveToLast should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException e) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) -#endignore - public void testGetAndMoveToFirstUnsupported() - { - try { - orderedMap.getAndMoveToFirst(c); - fail("getAndMoveToFirst should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException e) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_PUT) -#endignore - public void testGetMoveToLastUnsupported() - { - try { - orderedMap.getAndMoveToLast(a); - fail("getAndMoveToLast should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException e) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(SEVERAL) -#endignore - public void testMoveCenterToLast() - { - assertEquals(c, orderedMap.LAST_ENTRY_KEY()); - assertTrue(orderedMap.moveToLast(k1())); - assertNotEquals(c, orderedMap.LAST_ENTRY_KEY()); - assertEquals(k1(), orderedMap.LAST_ENTRY_KEY()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(SEVERAL) -#endignore - public void testMoveCenterToFirst() - { - assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); - assertTrue(orderedMap.moveToFirst(k1())); - assertNotEquals(c, orderedMap.FIRST_ENTRY_KEY()); - assertEquals(k1(), orderedMap.FIRST_ENTRY_KEY()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(SEVERAL) -#endignore - public void testMoveForthAndBack() - { - assertEquals(c, orderedMap.LAST_ENTRY_KEY()); - assertTrue(orderedMap.moveToLast(k0())); - assertNotEquals(c, orderedMap.LAST_ENTRY_KEY()); - assertEquals(a, orderedMap.LAST_ENTRY_KEY()); - assertNotEquals(a, orderedMap.FIRST_ENTRY_KEY()); - assertTrue(orderedMap.moveToFirst(k0())); - assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(SEVERAL) -#endignore - public void testMoveBackAndForth() - { - assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); - assertTrue(orderedMap.moveToFirst(k2())); - assertNotEquals(a, orderedMap.FIRST_ENTRY_KEY()); - assertEquals(c, orderedMap.FIRST_ENTRY_KEY()); - assertNotEquals(c, orderedMap.LAST_ENTRY_KEY()); - assertTrue(orderedMap.moveToLast(k2())); - assertEquals(c, orderedMap.LAST_ENTRY_KEY()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(SEVERAL) -#endignore - public void testPutForthAndBack() - { - assertEquals(c, orderedMap.LAST_ENTRY_KEY()); - assertEquals(v0(), orderedMap.putAndMoveToLast(k0(), v0())); - assertNotEquals(c, orderedMap.LAST_ENTRY_KEY()); - assertEquals(a, orderedMap.LAST_ENTRY_KEY()); - assertNotEquals(a, orderedMap.FIRST_ENTRY_KEY()); - assertEquals(v0(), orderedMap.putAndMoveToFirst(k0(), v0())); - assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(SEVERAL) -#endignore - public void testPutBackAndForth() - { - assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); - assertEquals(v2(), orderedMap.putAndMoveToFirst(k2(), v2())); - assertNotEquals(a, orderedMap.FIRST_ENTRY_KEY()); - assertEquals(c, orderedMap.FIRST_ENTRY_KEY()); - assertNotEquals(c, orderedMap.LAST_ENTRY_KEY()); - assertEquals(v2(), orderedMap.putAndMoveToLast(k2(), v2())); - assertEquals(c, orderedMap.LAST_ENTRY_KEY()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(SEVERAL) -#endignore - public void testGetForthAndBack() - { - assertEquals(c, orderedMap.LAST_ENTRY_KEY()); - assertEquals(v0(), orderedMap.getAndMoveToLast(k0())); - assertNotEquals(c, orderedMap.LAST_ENTRY_KEY()); - assertEquals(a, orderedMap.LAST_ENTRY_KEY()); - assertNotEquals(a, orderedMap.FIRST_ENTRY_KEY()); - assertEquals(v0(), orderedMap.getAndMoveToFirst(k0())); - assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(SEVERAL) -#endignore - public void testGetBackAndForth() - { - assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); - assertEquals(v2(), orderedMap.getAndMoveToFirst(k2())); - assertNotEquals(a, orderedMap.FIRST_ENTRY_KEY()); - assertEquals(c, orderedMap.FIRST_ENTRY_KEY()); - assertNotEquals(c, orderedMap.LAST_ENTRY_KEY()); - assertEquals(v2(), orderedMap.getAndMoveToLast(k2())); - assertEquals(c, orderedMap.LAST_ENTRY_KEY()); - } +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; +import static org.junit.Assert.assertNotEquals; +#endignore + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP; +import speiger.src.collections.objects.lists.ObjectList; +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; +import speiger.src.testers.objects.utils.ObjectHelpers; + +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPEOrderedMapMoveTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ + private ORDERED_MAP KEY_VALUE_GENERIC_TYPE orderedMap; + private ObjectList values; + private KEY_TYPE a; + private VALUE_TYPE aValue; + private KEY_TYPE c; + private VALUE_TYPE cValue; + + @Override + public void setUp() throws Exception { + super.setUp(); + orderedMap = (ORDERED_MAP KEY_VALUE_GENERIC_TYPE)getMap(); + values = ObjectHelpers.copyToList(getSampleElements(getSubjectGenerator().getCollectionSize().getNumElements())); + if (values.size() >= 1) { + a = values.get(0).ENTRY_KEY(); + aValue = values.get(0).ENTRY_VALUE(); + if (values.size() >= 3) { + c = values.get(2).ENTRY_KEY(); + cValue = values.get(2).ENTRY_VALUE(); + } + } + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(SEVERAL) +#endignore + public void testaddMoveToFirstMissing() + { + assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); + assertEquals(INVALID_VALUE, orderedMap.putAndMoveToFirst(k4(), v4())); + assertNotEquals(a, orderedMap.FIRST_ENTRY_KEY()); + assertEquals(k4(), orderedMap.FIRST_ENTRY_KEY()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(SEVERAL) +#endignore + public void testaddMoveToFirstPreset() + { + assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); + assertEquals(cValue, orderedMap.putAndMoveToFirst(c, v4())); + assertNotEquals(a, orderedMap.FIRST_ENTRY_KEY()); + assertEquals(c, orderedMap.FIRST_ENTRY_KEY()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(SEVERAL) +#endignore + public void testaddMoveToLastMissing() + { + assertEquals(c, orderedMap.LAST_ENTRY_KEY()); + assertEquals(INVALID_VALUE, orderedMap.putAndMoveToLast(k4(), v4())); + assertNotEquals(c, orderedMap.LAST_ENTRY_KEY()); + assertEquals(k4(), orderedMap.LAST_ENTRY_KEY()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(SEVERAL) +#endignore + public void testaddMoveToLastPreset() + { + assertEquals(c, orderedMap.LAST_ENTRY_KEY()); + assertEquals(aValue, orderedMap.putAndMoveToLast(a, v4())); + assertNotEquals(c, orderedMap.LAST_ENTRY_KEY()); + assertEquals(a, orderedMap.LAST_ENTRY_KEY()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(SEVERAL) +#endignore + public void testMoveToFirstMissing() + { + assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); + assertEquals(false, orderedMap.moveToFirst(k4())); + assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(SEVERAL) +#endignore + public void testMoveToFirstPreset() + { + assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); + assertEquals(true, orderedMap.moveToFirst(c)); + assertNotEquals(a, orderedMap.FIRST_ENTRY_KEY()); + assertEquals(c, orderedMap.FIRST_ENTRY_KEY()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(SEVERAL) +#endignore + public void testMoveToLastMissing() + { + assertEquals(c, orderedMap.LAST_ENTRY_KEY()); + assertEquals(false, orderedMap.moveToLast(k4())); + assertEquals(c, orderedMap.LAST_ENTRY_KEY()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(SEVERAL) +#endignore + public void testMoveToLastPreset() + { + assertEquals(c, orderedMap.LAST_ENTRY_KEY()); + assertEquals(true, orderedMap.moveToLast(a)); + assertNotEquals(c, orderedMap.LAST_ENTRY_KEY()); + assertEquals(a, orderedMap.LAST_ENTRY_KEY()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(SEVERAL) +#endignore + public void testGetAndMoveToFirstMissing() + { + assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); + assertEquals(INVALID_VALUE, orderedMap.getAndMoveToFirst(k4())); + assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(SEVERAL) +#endignore + public void testGetAndMoveToFirstPreset() + { + assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); + assertEquals(cValue, orderedMap.getAndMoveToFirst(c)); + assertNotEquals(a, orderedMap.FIRST_ENTRY_KEY()); + assertEquals(c, orderedMap.FIRST_ENTRY_KEY()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(SEVERAL) +#endignore + public void testGetAndMoveToLastMissing() + { + assertEquals(c, orderedMap.LAST_ENTRY_KEY()); + assertEquals(INVALID_VALUE, orderedMap.getAndMoveToLast(k4())); + assertEquals(c, orderedMap.LAST_ENTRY_KEY()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(SEVERAL) +#endignore + public void testGetAndMoveToLastPreset() + { + assertEquals(c, orderedMap.LAST_ENTRY_KEY()); + assertEquals(aValue, orderedMap.getAndMoveToLast(a)); + assertNotEquals(c, orderedMap.LAST_ENTRY_KEY()); + assertEquals(a, orderedMap.LAST_ENTRY_KEY()); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) +#endignore + public void testaddMoveToFirstUnsupported() + { + try { + orderedMap.putAndMoveToFirst(k4(), v4()); + fail("addAndMoveToFirst should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) +#endignore + public void testaddMoveToLastUnsupported() + { + try { + orderedMap.putAndMoveToFirst(k4(), v4()); + fail("addAndMoveToLast should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) +#endignore + public void testMoveToFirstUnsupported() + { + try { + orderedMap.moveToFirst(c); + fail("moveToFirst should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) +#endignore + public void testMoveToLastUnsupported() + { + try { + orderedMap.moveToLast(a); + fail("moveToLast should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) +#endignore + public void testGetAndMoveToFirstUnsupported() + { + try { + orderedMap.getAndMoveToFirst(c); + fail("getAndMoveToFirst should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_PUT) +#endignore + public void testGetMoveToLastUnsupported() + { + try { + orderedMap.getAndMoveToLast(a); + fail("getAndMoveToLast should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(SEVERAL) +#endignore + public void testMoveCenterToLast() + { + assertEquals(c, orderedMap.LAST_ENTRY_KEY()); + assertTrue(orderedMap.moveToLast(k1())); + assertNotEquals(c, orderedMap.LAST_ENTRY_KEY()); + assertEquals(k1(), orderedMap.LAST_ENTRY_KEY()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(SEVERAL) +#endignore + public void testMoveCenterToFirst() + { + assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); + assertTrue(orderedMap.moveToFirst(k1())); + assertNotEquals(c, orderedMap.FIRST_ENTRY_KEY()); + assertEquals(k1(), orderedMap.FIRST_ENTRY_KEY()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(SEVERAL) +#endignore + public void testMoveForthAndBack() + { + assertEquals(c, orderedMap.LAST_ENTRY_KEY()); + assertTrue(orderedMap.moveToLast(k0())); + assertNotEquals(c, orderedMap.LAST_ENTRY_KEY()); + assertEquals(a, orderedMap.LAST_ENTRY_KEY()); + assertNotEquals(a, orderedMap.FIRST_ENTRY_KEY()); + assertTrue(orderedMap.moveToFirst(k0())); + assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(SEVERAL) +#endignore + public void testMoveBackAndForth() + { + assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); + assertTrue(orderedMap.moveToFirst(k2())); + assertNotEquals(a, orderedMap.FIRST_ENTRY_KEY()); + assertEquals(c, orderedMap.FIRST_ENTRY_KEY()); + assertNotEquals(c, orderedMap.LAST_ENTRY_KEY()); + assertTrue(orderedMap.moveToLast(k2())); + assertEquals(c, orderedMap.LAST_ENTRY_KEY()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(SEVERAL) +#endignore + public void testPutForthAndBack() + { + assertEquals(c, orderedMap.LAST_ENTRY_KEY()); + assertEquals(v0(), orderedMap.putAndMoveToLast(k0(), v0())); + assertNotEquals(c, orderedMap.LAST_ENTRY_KEY()); + assertEquals(a, orderedMap.LAST_ENTRY_KEY()); + assertNotEquals(a, orderedMap.FIRST_ENTRY_KEY()); + assertEquals(v0(), orderedMap.putAndMoveToFirst(k0(), v0())); + assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(SEVERAL) +#endignore + public void testPutBackAndForth() + { + assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); + assertEquals(v2(), orderedMap.putAndMoveToFirst(k2(), v2())); + assertNotEquals(a, orderedMap.FIRST_ENTRY_KEY()); + assertEquals(c, orderedMap.FIRST_ENTRY_KEY()); + assertNotEquals(c, orderedMap.LAST_ENTRY_KEY()); + assertEquals(v2(), orderedMap.putAndMoveToLast(k2(), v2())); + assertEquals(c, orderedMap.LAST_ENTRY_KEY()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(SEVERAL) +#endignore + public void testGetForthAndBack() + { + assertEquals(c, orderedMap.LAST_ENTRY_KEY()); + assertEquals(v0(), orderedMap.getAndMoveToLast(k0())); + assertNotEquals(c, orderedMap.LAST_ENTRY_KEY()); + assertEquals(a, orderedMap.LAST_ENTRY_KEY()); + assertNotEquals(a, orderedMap.FIRST_ENTRY_KEY()); + assertEquals(v0(), orderedMap.getAndMoveToFirst(k0())); + assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(SEVERAL) +#endignore + public void testGetBackAndForth() + { + assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); + assertEquals(v2(), orderedMap.getAndMoveToFirst(k2())); + assertNotEquals(a, orderedMap.FIRST_ENTRY_KEY()); + assertEquals(c, orderedMap.FIRST_ENTRY_KEY()); + assertNotEquals(c, orderedMap.LAST_ENTRY_KEY()); + assertEquals(v2(), orderedMap.getAndMoveToLast(k2())); + assertEquals(c, orderedMap.LAST_ENTRY_KEY()); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/OrderedMapNavigationTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/OrderedMapNavigationTester.template index 706dd93..ccfceb5 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/OrderedMapNavigationTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/OrderedMapNavigationTester.template @@ -1,303 +1,303 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; -#endignore - -import java.util.NoSuchElementException; - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; - -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP; -import speiger.src.collections.objects.lists.ObjectList; -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; -import speiger.src.testers.objects.utils.ObjectHelpers; - -@SuppressWarnings("javadoc") -@Ignore -public class FILE_KEY_TYPE2FILE_VALUE_TYPEOrderedMapNavigationTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ - private ORDERED_MAP KEY_VALUE_GENERIC_TYPE orderedMap; - private ObjectList values; - private KEY_TYPE a; - private VALUE_TYPE aValue; - private KEY_TYPE c; - private VALUE_TYPE cValue; - - @Override - public void setUp() throws Exception { - super.setUp(); - orderedMap = (ORDERED_MAP KEY_VALUE_GENERIC_TYPE) getMap(); - values = ObjectHelpers.copyToList(getSampleElements(getSubjectGenerator().getCollectionSize().getNumElements())); - if (values.size() >= 1) { - a = values.get(0).ENTRY_KEY(); - aValue = values.get(0).ENTRY_VALUE(); - if (values.size() >= 3) { - c = values.get(2).ENTRY_KEY(); - cValue = values.get(2).ENTRY_VALUE(); - } - } - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(ZERO) -#endignore - public void testPutEmptyMapToFirst() { - orderedMap.putAndMoveToFirst(k0(), v0()); - expectAdded(e0()); - } - -#ignore - @MapFeature.Require(SUPPORTS_PUT) - @CollectionSize.Require(ZERO) -#endignore - public void testPutEmptyMapToLast() { - orderedMap.putAndMoveToLast(k0(), v0()); - expectAdded(e0()); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testyMapPollFirstEmpty() { - int polled = 0; - int expectedPolls = orderedMap.size(); - while(polled < expectedPolls) { - orderedMap.POLL_FIRST_ENTRY_KEY(); - polled++; - } - assertTrue("Map should be empty", orderedMap.isEmpty()); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testyMapPollLastEmpty() { - int polled = 0; - int expectedPolls = orderedMap.size(); - while(polled < expectedPolls) { - orderedMap.POLL_LAST_ENTRY_KEY(); - polled++; - } - assertTrue("Map should be empty", orderedMap.isEmpty()); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ZERO) -#endignore - public void testEmptyMapPollFirst() { - try { - orderedMap.POLL_FIRST_ENTRY_KEY(); - fail("OrderedMap.POLL_FIRST_ENTRY_KEY should throw NoSuchElementException"); - } catch (NoSuchElementException e) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ZERO) -#endignore - public void testEmptyMapPollLast() { - try { - orderedMap.POLL_LAST_ENTRY_KEY(); - fail("OrderedMap.POLL_LAST_ENTRY_KEY should throw NoSuchElementException"); - } catch (NoSuchElementException e) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_REMOVE) -#endignore - public void testUnsupportedMapPollFirst() { - try { - orderedMap.POLL_FIRST_ENTRY_KEY(); - fail("OrderedMap.POLL_FIRST_ENTRY_KEY should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException e) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_REMOVE) -#endignore - public void testUnsupportedMapPollLast() { - try { - orderedMap.POLL_LAST_ENTRY_KEY(); - fail("OrderedMap.POLL_LAST_ENTRY_KEY should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException e) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ONE) -#endignore - public void testSingletonMapPollFirst() { - assertEquals(a, orderedMap.POLL_FIRST_ENTRY_KEY()); - assertTrue(orderedMap.isEmpty()); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ONE) -#endignore - public void testSingletonMapPollLast() { - assertEquals(a, orderedMap.POLL_LAST_ENTRY_KEY()); - assertTrue(orderedMap.isEmpty()); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testPollFirst() { - assertEquals(a, orderedMap.POLL_FIRST_ENTRY_KEY()); - assertEquals(values.subList(1, values.size()), ObjectHelpers.copyToList(orderedMap.ENTRY_SET())); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testPollLast() { - assertEquals(c, orderedMap.POLL_LAST_ENTRY_KEY()); - assertEquals(values.subList(0, values.size()-1), ObjectHelpers.copyToList(orderedMap.ENTRY_SET())); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_REMOVE) -#endignore - public void testPollFirstUnsupported() { - try { - orderedMap.POLL_FIRST_ENTRY_KEY(); - fail(); - } catch (UnsupportedOperationException e) { - } - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_REMOVE) -#endignore - public void testPollLastUnsupported() { - try { - orderedMap.POLL_LAST_ENTRY_KEY(); - fail(); - } catch (UnsupportedOperationException e) { - } - } - -#ignore - @CollectionSize.Require(ZERO) -#endignore - public void testEmptyMapFirstKey() { - try { - orderedMap.FIRST_ENTRY_KEY(); - fail(); - } catch (NoSuchElementException e) { - } - } - -#ignore - @CollectionSize.Require(ZERO) -#endignore - public void testEmptyMapFirstValue() { - try { - orderedMap.FIRST_ENTRY_VALUE(); - fail(); - } catch (NoSuchElementException e) { - } - } - -#ignore - @CollectionSize.Require(ZERO) -#endignore - public void testEmptyMapLastKey() { - try { - orderedMap.LAST_ENTRY_KEY(); - fail(); - } catch (NoSuchElementException e) { - } - } - -#ignore - @CollectionSize.Require(ZERO) -#endignore - public void testEmptyMapLastValue() { - try { - orderedMap.LAST_ENTRY_VALUE(); - fail(); - } catch (NoSuchElementException e) { - } - } - -#ignore - @CollectionSize.Require(ONE) -#endignore - public void testSingletonMapFirstKey() { - assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); - } - -#ignore - @CollectionSize.Require(ONE) -#endignore - public void testSingletonMapFirstValue() { - assertEquals(aValue, orderedMap.FIRST_ENTRY_VALUE()); - } - -#ignore - @CollectionSize.Require(ONE) -#endignore - public void testSingletonMapLastKey() { - assertEquals(a, orderedMap.LAST_ENTRY_KEY()); - } - -#ignore - @CollectionSize.Require(ONE) -#endignore - public void testSingletonMapLastValue() { - assertEquals(aValue, orderedMap.FIRST_ENTRY_VALUE()); - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testFirstKey() { - assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testFirstValue() { - assertEquals(aValue, orderedMap.FIRST_ENTRY_VALUE()); - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testLastKey() { - assertEquals(c, orderedMap.LAST_ENTRY_KEY()); - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testLastValue() { - assertEquals(cValue, orderedMap.LAST_ENTRY_VALUE()); - } +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; +#endignore + +import java.util.NoSuchElementException; + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP; +import speiger.src.collections.objects.lists.ObjectList; +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; +import speiger.src.testers.objects.utils.ObjectHelpers; + +@SuppressWarnings("javadoc") +@Ignore +public class FILE_KEY_TYPE2FILE_VALUE_TYPEOrderedMapNavigationTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ + private ORDERED_MAP KEY_VALUE_GENERIC_TYPE orderedMap; + private ObjectList values; + private KEY_TYPE a; + private VALUE_TYPE aValue; + private KEY_TYPE c; + private VALUE_TYPE cValue; + + @Override + public void setUp() throws Exception { + super.setUp(); + orderedMap = (ORDERED_MAP KEY_VALUE_GENERIC_TYPE) getMap(); + values = ObjectHelpers.copyToList(getSampleElements(getSubjectGenerator().getCollectionSize().getNumElements())); + if (values.size() >= 1) { + a = values.get(0).ENTRY_KEY(); + aValue = values.get(0).ENTRY_VALUE(); + if (values.size() >= 3) { + c = values.get(2).ENTRY_KEY(); + cValue = values.get(2).ENTRY_VALUE(); + } + } + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(ZERO) +#endignore + public void testPutEmptyMapToFirst() { + orderedMap.putAndMoveToFirst(k0(), v0()); + expectAdded(e0()); + } + +#ignore + @MapFeature.Require(SUPPORTS_PUT) + @CollectionSize.Require(ZERO) +#endignore + public void testPutEmptyMapToLast() { + orderedMap.putAndMoveToLast(k0(), v0()); + expectAdded(e0()); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testyMapPollFirstEmpty() { + int polled = 0; + int expectedPolls = orderedMap.size(); + while(polled < expectedPolls) { + orderedMap.POLL_FIRST_ENTRY_KEY(); + polled++; + } + assertTrue("Map should be empty", orderedMap.isEmpty()); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testyMapPollLastEmpty() { + int polled = 0; + int expectedPolls = orderedMap.size(); + while(polled < expectedPolls) { + orderedMap.POLL_LAST_ENTRY_KEY(); + polled++; + } + assertTrue("Map should be empty", orderedMap.isEmpty()); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ZERO) +#endignore + public void testEmptyMapPollFirst() { + try { + orderedMap.POLL_FIRST_ENTRY_KEY(); + fail("OrderedMap.POLL_FIRST_ENTRY_KEY should throw NoSuchElementException"); + } catch (NoSuchElementException e) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ZERO) +#endignore + public void testEmptyMapPollLast() { + try { + orderedMap.POLL_LAST_ENTRY_KEY(); + fail("OrderedMap.POLL_LAST_ENTRY_KEY should throw NoSuchElementException"); + } catch (NoSuchElementException e) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_REMOVE) +#endignore + public void testUnsupportedMapPollFirst() { + try { + orderedMap.POLL_FIRST_ENTRY_KEY(); + fail("OrderedMap.POLL_FIRST_ENTRY_KEY should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_REMOVE) +#endignore + public void testUnsupportedMapPollLast() { + try { + orderedMap.POLL_LAST_ENTRY_KEY(); + fail("OrderedMap.POLL_LAST_ENTRY_KEY should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ONE) +#endignore + public void testSingletonMapPollFirst() { + assertEquals(a, orderedMap.POLL_FIRST_ENTRY_KEY()); + assertTrue(orderedMap.isEmpty()); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ONE) +#endignore + public void testSingletonMapPollLast() { + assertEquals(a, orderedMap.POLL_LAST_ENTRY_KEY()); + assertTrue(orderedMap.isEmpty()); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testPollFirst() { + assertEquals(a, orderedMap.POLL_FIRST_ENTRY_KEY()); + assertEquals(values.subList(1, values.size()), ObjectHelpers.copyToList(orderedMap.ENTRY_SET())); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testPollLast() { + assertEquals(c, orderedMap.POLL_LAST_ENTRY_KEY()); + assertEquals(values.subList(0, values.size()-1), ObjectHelpers.copyToList(orderedMap.ENTRY_SET())); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_REMOVE) +#endignore + public void testPollFirstUnsupported() { + try { + orderedMap.POLL_FIRST_ENTRY_KEY(); + fail(); + } catch (UnsupportedOperationException e) { + } + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_REMOVE) +#endignore + public void testPollLastUnsupported() { + try { + orderedMap.POLL_LAST_ENTRY_KEY(); + fail(); + } catch (UnsupportedOperationException e) { + } + } + +#ignore + @CollectionSize.Require(ZERO) +#endignore + public void testEmptyMapFirstKey() { + try { + orderedMap.FIRST_ENTRY_KEY(); + fail(); + } catch (NoSuchElementException e) { + } + } + +#ignore + @CollectionSize.Require(ZERO) +#endignore + public void testEmptyMapFirstValue() { + try { + orderedMap.FIRST_ENTRY_VALUE(); + fail(); + } catch (NoSuchElementException e) { + } + } + +#ignore + @CollectionSize.Require(ZERO) +#endignore + public void testEmptyMapLastKey() { + try { + orderedMap.LAST_ENTRY_KEY(); + fail(); + } catch (NoSuchElementException e) { + } + } + +#ignore + @CollectionSize.Require(ZERO) +#endignore + public void testEmptyMapLastValue() { + try { + orderedMap.LAST_ENTRY_VALUE(); + fail(); + } catch (NoSuchElementException e) { + } + } + +#ignore + @CollectionSize.Require(ONE) +#endignore + public void testSingletonMapFirstKey() { + assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); + } + +#ignore + @CollectionSize.Require(ONE) +#endignore + public void testSingletonMapFirstValue() { + assertEquals(aValue, orderedMap.FIRST_ENTRY_VALUE()); + } + +#ignore + @CollectionSize.Require(ONE) +#endignore + public void testSingletonMapLastKey() { + assertEquals(a, orderedMap.LAST_ENTRY_KEY()); + } + +#ignore + @CollectionSize.Require(ONE) +#endignore + public void testSingletonMapLastValue() { + assertEquals(aValue, orderedMap.FIRST_ENTRY_VALUE()); + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testFirstKey() { + assertEquals(a, orderedMap.FIRST_ENTRY_KEY()); + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testFirstValue() { + assertEquals(aValue, orderedMap.FIRST_ENTRY_VALUE()); + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testLastKey() { + assertEquals(c, orderedMap.LAST_ENTRY_KEY()); + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testLastValue() { + assertEquals(cValue, orderedMap.LAST_ENTRY_VALUE()); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/maps/SortedMapNavigationTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/maps/SortedMapNavigationTester.template index e27a129..8a392c8 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/maps/SortedMapNavigationTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/maps/SortedMapNavigationTester.template @@ -1,328 +1,328 @@ -package speiger.src.testers.PACKAGE.tests.maps; - -#ignore -import static com.google.common.collect.testing.Helpers.assertEqualInOrder; -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; -#endignore - -import java.util.Comparator; -import java.util.Iterator; -import java.util.NoSuchElementException; - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; - -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.functions.COMPARATOR; -#endif -import speiger.src.collections.PACKAGE.maps.interfaces.MAP.Entry; -import speiger.src.collections.PACKAGE.maps.interfaces.SORTED_MAP; -import speiger.src.collections.objects.lists.ObjectList; -import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; -import speiger.src.testers.objects.utils.ObjectHelpers; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPE2FILE_VALUE_TYPESortedMapNavigationTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE -{ - private SORTED_MAP KEY_VALUE_GENERIC_TYPE sortedMap; - private ObjectList entries; - private Entry KEY_VALUE_GENERIC_TYPE a; - private Entry KEY_VALUE_GENERIC_TYPE c; - - @Override - public void setUp() throws Exception { - super.setUp(); - sortedMap = (SORTED_MAP KEY_VALUE_GENERIC_TYPE) getMap(); - entries = ObjectHelpers.copyToList(getSampleElements(getNumElements())); - entries.sort(entryComparator(sortedMap.comparator())); - if (entries.size() >= 1) { - a = entries.get(0); - if (entries.size() >= 3) { - c = entries.get(2); - } - } - } - - public static GENERIC_KEY_VALUE_BRACES Comparator entryComparator(COMPARATOR KEY_GENERIC_TYPE keyComparator) { - return new Comparator() { - @Override - public int compare(Entry KEY_VALUE_GENERIC_TYPE a, Entry KEY_VALUE_GENERIC_TYPE b) { - return (keyComparator == null) ? COMPAREABLE_TO_KEY(a.ENTRY_KEY(), b.ENTRY_KEY()) : keyComparator.compare(a.ENTRY_KEY(), b.ENTRY_KEY()); - } - }; - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ZERO) -#endignore - public void testEmptyMapPollFirst() { -#if TYPE_OBJECT - assertNull(sortedMap.POLL_FIRST_ENTRY_KEY()); -#else - assertEquals(CLASS_TYPE.MAX_VALUE, sortedMap.POLL_FIRST_ENTRY_KEY()); -#endif - expectUnchanged(); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ZERO) -#endignore - public void testEmptyMapPollLast() { -#if TYPE_OBJECT - assertNull(sortedMap.POLL_FIRST_ENTRY_KEY()); -#else - assertEquals(CLASS_TYPE.MIN_VALUE, sortedMap.POLL_LAST_ENTRY_KEY()); -#endif - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_REMOVE) -#endignore - public void testUnsupportedMapPollFirst() { - try { - sortedMap.POLL_FIRST_ENTRY_KEY(); - fail("OrderedMap.POLL_FIRST_ENTRY_KEY should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException e) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_REMOVE) -#endignore - public void testUnsupportedMapPollLast() { - try { - sortedMap.POLL_LAST_ENTRY_KEY(); - fail("OrderedMap.POLL_LAST_ENTRY_KEY should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException e) { - } - expectUnchanged(); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ONE) -#endignore - public void testSingletonMapPollFirst() { - assertEquals(a.ENTRY_KEY(), sortedMap.POLL_FIRST_ENTRY_KEY()); - assertTrue(sortedMap.isEmpty()); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ONE) -#endignore - public void testSingletonMapPollLast() { - assertEquals(a.ENTRY_KEY(), sortedMap.POLL_LAST_ENTRY_KEY()); - assertTrue(sortedMap.isEmpty()); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testPollFirst() { - assertEquals(a.ENTRY_KEY(), sortedMap.POLL_FIRST_ENTRY_KEY()); - assertEquals(entries.subList(1, entries.size()), ObjectHelpers.copyToList(sortedMap.ENTRY_SET())); - } - -#ignore - @MapFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testPollLast() { - assertEquals(c.ENTRY_KEY(), sortedMap.POLL_LAST_ENTRY_KEY()); - assertEquals(entries.subList(0, entries.size()-1), ObjectHelpers.copyToList(sortedMap.ENTRY_SET())); - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_REMOVE) -#endignore - public void testPollFirstUnsupported() { - try { - sortedMap.POLL_FIRST_ENTRY_KEY(); - fail(); - } catch (UnsupportedOperationException e) { - } - } - -#ignore - @MapFeature.Require(absent = SUPPORTS_REMOVE) -#endignore - public void testPollLastUnsupported() { - try { - sortedMap.POLL_LAST_ENTRY_KEY(); - fail(); - } catch (UnsupportedOperationException e) { - } - } - -#ignore - @CollectionSize.Require(ZERO) -#endignore - public void testEmptyMapFirst() { - try { - sortedMap.FIRST_ENTRY_KEY(); - fail(); - } catch (NoSuchElementException e) { - } - } - -#ignore - @CollectionSize.Require(ZERO) -#endignore - public void testEmptyMapLast() { - try { - assertEquals(EMPTY_VALUE, sortedMap.LAST_ENTRY_KEY()); - fail(); - } catch (NoSuchElementException e) { - } - } - -#ignore - @CollectionSize.Require(ZERO) -#endignore - public void testEmptyMapFirstValue() { - try { - sortedMap.FIRST_ENTRY_VALUE(); - fail(); - } catch (NoSuchElementException e) { - } - } - -#ignore - @CollectionSize.Require(ZERO) -#endignore - public void testEmptyMapLastValue() { - try { - sortedMap.LAST_ENTRY_VALUE(); - fail(); - } catch (NoSuchElementException e) { - } - } - -#ignore - @CollectionSize.Require(ONE) -#endignore - public void testSingletonMapFirstValue() { - assertEquals(a.ENTRY_VALUE(), sortedMap.FIRST_ENTRY_VALUE()); - } - -#ignore - @CollectionSize.Require(ONE) -#endignore - public void testSingletonMapLastValue() { - assertEquals(a.ENTRY_VALUE(), sortedMap.FIRST_ENTRY_VALUE()); - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testFirstValue() { - assertEquals(a.ENTRY_VALUE(), sortedMap.FIRST_ENTRY_VALUE()); - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testLastValue() { - assertEquals(c.ENTRY_VALUE(), sortedMap.LAST_ENTRY_VALUE()); - } - -#ignore - @CollectionSize.Require(ONE) -#endignore - public void testSingletonMapFirst() { - assertEquals(a.ENTRY_KEY(), sortedMap.FIRST_ENTRY_KEY()); - } - -#ignore - @CollectionSize.Require(ONE) -#endignore - public void testSingletonMapLast() { - assertEquals(a.ENTRY_KEY(), sortedMap.LAST_ENTRY_KEY()); - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testFirst() { - assertEquals(a.ENTRY_KEY(), sortedMap.FIRST_ENTRY_KEY()); - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testLast() { - assertEquals(c.ENTRY_KEY(), sortedMap.LAST_ENTRY_KEY()); - } - -#ignore - @CollectionSize.Require(absent = ZERO) -#endignore - public void testHeadMapExclusive() { - assertFalse(sortedMap.headMap(a.ENTRY_KEY()).containsKey(a.ENTRY_KEY())); - } - -#ignore - @CollectionSize.Require(absent = ZERO) -#endignore - public void testTailMapInclusive() { - assertTrue(sortedMap.tailMap(a.ENTRY_KEY()).containsKey(a.ENTRY_KEY())); - } - -#ignore - @CollectionSize.Require(absent = SEVERAL) -#endignore - public void testSubMap() { - ObjectList entries = ObjectHelpers.copyToList(getSampleElements(getNumElements())); - entries.sort(entryComparator(sortedMap.comparator())); - for (int i = 0; i < entries.size(); i++) { - for (int j = i + 1; j < entries.size(); j++) { - assertEqualInOrder(entries.subList(i, j), sortedMap.subMap(entries.get(i).ENTRY_KEY(), entries.get(j).ENTRY_KEY()).ENTRY_SET()); - } - } - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testSubMapIllegal() { - try { - sortedMap.subMap(c.ENTRY_KEY(), a.ENTRY_KEY()); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } - } - -#ignore - @CollectionSize.Require(absent = ZERO) -#endignore - public void testOrderedByComparator() { - @SuppressWarnings("unchecked") - COMPARATOR KEY_GENERIC_TYPE comparator = sortedMap.comparator(); - if (comparator == null) { -#if TYPE_OBJECT - comparator = (Comparator)Comparator.naturalOrder(); -#else - comparator = CLASS_TYPE::compare; -#endif - } - Iterator entryItr = sortedMap.ENTRY_SET().iterator(); - Entry KEY_VALUE_GENERIC_TYPE prevEntry = entryItr.next(); - while (entryItr.hasNext()) { - Entry KEY_VALUE_GENERIC_TYPE nextEntry = entryItr.next(); - assertTrue(comparator.compare(prevEntry.ENTRY_KEY(), nextEntry.ENTRY_KEY()) < 0); - prevEntry = nextEntry; - } - } -} +package speiger.src.testers.PACKAGE.tests.maps; + +#ignore +import static com.google.common.collect.testing.Helpers.assertEqualInOrder; +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; +#endignore + +import java.util.Comparator; +import java.util.Iterator; +import java.util.NoSuchElementException; + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.functions.COMPARATOR; +#endif +import speiger.src.collections.PACKAGE.maps.interfaces.MAP.Entry; +import speiger.src.collections.PACKAGE.maps.interfaces.SORTED_MAP; +import speiger.src.collections.objects.lists.ObjectList; +import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER; +import speiger.src.testers.objects.utils.ObjectHelpers; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPE2FILE_VALUE_TYPESortedMapNavigationTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE +{ + private SORTED_MAP KEY_VALUE_GENERIC_TYPE sortedMap; + private ObjectList entries; + private Entry KEY_VALUE_GENERIC_TYPE a; + private Entry KEY_VALUE_GENERIC_TYPE c; + + @Override + public void setUp() throws Exception { + super.setUp(); + sortedMap = (SORTED_MAP KEY_VALUE_GENERIC_TYPE) getMap(); + entries = ObjectHelpers.copyToList(getSampleElements(getNumElements())); + entries.sort(entryComparator(sortedMap.comparator())); + if (entries.size() >= 1) { + a = entries.get(0); + if (entries.size() >= 3) { + c = entries.get(2); + } + } + } + + public static GENERIC_KEY_VALUE_BRACES Comparator entryComparator(COMPARATOR KEY_GENERIC_TYPE keyComparator) { + return new Comparator() { + @Override + public int compare(Entry KEY_VALUE_GENERIC_TYPE a, Entry KEY_VALUE_GENERIC_TYPE b) { + return (keyComparator == null) ? COMPAREABLE_TO_KEY(a.ENTRY_KEY(), b.ENTRY_KEY()) : keyComparator.compare(a.ENTRY_KEY(), b.ENTRY_KEY()); + } + }; + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ZERO) +#endignore + public void testEmptyMapPollFirst() { +#if TYPE_OBJECT + assertNull(sortedMap.POLL_FIRST_ENTRY_KEY()); +#else + assertEquals(CLASS_TYPE.MAX_VALUE, sortedMap.POLL_FIRST_ENTRY_KEY()); +#endif + expectUnchanged(); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ZERO) +#endignore + public void testEmptyMapPollLast() { +#if TYPE_OBJECT + assertNull(sortedMap.POLL_FIRST_ENTRY_KEY()); +#else + assertEquals(CLASS_TYPE.MIN_VALUE, sortedMap.POLL_LAST_ENTRY_KEY()); +#endif + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_REMOVE) +#endignore + public void testUnsupportedMapPollFirst() { + try { + sortedMap.POLL_FIRST_ENTRY_KEY(); + fail("OrderedMap.POLL_FIRST_ENTRY_KEY should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_REMOVE) +#endignore + public void testUnsupportedMapPollLast() { + try { + sortedMap.POLL_LAST_ENTRY_KEY(); + fail("OrderedMap.POLL_LAST_ENTRY_KEY should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + } + expectUnchanged(); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ONE) +#endignore + public void testSingletonMapPollFirst() { + assertEquals(a.ENTRY_KEY(), sortedMap.POLL_FIRST_ENTRY_KEY()); + assertTrue(sortedMap.isEmpty()); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ONE) +#endignore + public void testSingletonMapPollLast() { + assertEquals(a.ENTRY_KEY(), sortedMap.POLL_LAST_ENTRY_KEY()); + assertTrue(sortedMap.isEmpty()); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testPollFirst() { + assertEquals(a.ENTRY_KEY(), sortedMap.POLL_FIRST_ENTRY_KEY()); + assertEquals(entries.subList(1, entries.size()), ObjectHelpers.copyToList(sortedMap.ENTRY_SET())); + } + +#ignore + @MapFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testPollLast() { + assertEquals(c.ENTRY_KEY(), sortedMap.POLL_LAST_ENTRY_KEY()); + assertEquals(entries.subList(0, entries.size()-1), ObjectHelpers.copyToList(sortedMap.ENTRY_SET())); + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_REMOVE) +#endignore + public void testPollFirstUnsupported() { + try { + sortedMap.POLL_FIRST_ENTRY_KEY(); + fail(); + } catch (UnsupportedOperationException e) { + } + } + +#ignore + @MapFeature.Require(absent = SUPPORTS_REMOVE) +#endignore + public void testPollLastUnsupported() { + try { + sortedMap.POLL_LAST_ENTRY_KEY(); + fail(); + } catch (UnsupportedOperationException e) { + } + } + +#ignore + @CollectionSize.Require(ZERO) +#endignore + public void testEmptyMapFirst() { + try { + sortedMap.FIRST_ENTRY_KEY(); + fail(); + } catch (NoSuchElementException e) { + } + } + +#ignore + @CollectionSize.Require(ZERO) +#endignore + public void testEmptyMapLast() { + try { + assertEquals(EMPTY_VALUE, sortedMap.LAST_ENTRY_KEY()); + fail(); + } catch (NoSuchElementException e) { + } + } + +#ignore + @CollectionSize.Require(ZERO) +#endignore + public void testEmptyMapFirstValue() { + try { + sortedMap.FIRST_ENTRY_VALUE(); + fail(); + } catch (NoSuchElementException e) { + } + } + +#ignore + @CollectionSize.Require(ZERO) +#endignore + public void testEmptyMapLastValue() { + try { + sortedMap.LAST_ENTRY_VALUE(); + fail(); + } catch (NoSuchElementException e) { + } + } + +#ignore + @CollectionSize.Require(ONE) +#endignore + public void testSingletonMapFirstValue() { + assertEquals(a.ENTRY_VALUE(), sortedMap.FIRST_ENTRY_VALUE()); + } + +#ignore + @CollectionSize.Require(ONE) +#endignore + public void testSingletonMapLastValue() { + assertEquals(a.ENTRY_VALUE(), sortedMap.FIRST_ENTRY_VALUE()); + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testFirstValue() { + assertEquals(a.ENTRY_VALUE(), sortedMap.FIRST_ENTRY_VALUE()); + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testLastValue() { + assertEquals(c.ENTRY_VALUE(), sortedMap.LAST_ENTRY_VALUE()); + } + +#ignore + @CollectionSize.Require(ONE) +#endignore + public void testSingletonMapFirst() { + assertEquals(a.ENTRY_KEY(), sortedMap.FIRST_ENTRY_KEY()); + } + +#ignore + @CollectionSize.Require(ONE) +#endignore + public void testSingletonMapLast() { + assertEquals(a.ENTRY_KEY(), sortedMap.LAST_ENTRY_KEY()); + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testFirst() { + assertEquals(a.ENTRY_KEY(), sortedMap.FIRST_ENTRY_KEY()); + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testLast() { + assertEquals(c.ENTRY_KEY(), sortedMap.LAST_ENTRY_KEY()); + } + +#ignore + @CollectionSize.Require(absent = ZERO) +#endignore + public void testHeadMapExclusive() { + assertFalse(sortedMap.headMap(a.ENTRY_KEY()).containsKey(a.ENTRY_KEY())); + } + +#ignore + @CollectionSize.Require(absent = ZERO) +#endignore + public void testTailMapInclusive() { + assertTrue(sortedMap.tailMap(a.ENTRY_KEY()).containsKey(a.ENTRY_KEY())); + } + +#ignore + @CollectionSize.Require(absent = SEVERAL) +#endignore + public void testSubMap() { + ObjectList entries = ObjectHelpers.copyToList(getSampleElements(getNumElements())); + entries.sort(entryComparator(sortedMap.comparator())); + for (int i = 0; i < entries.size(); i++) { + for (int j = i + 1; j < entries.size(); j++) { + assertEqualInOrder(entries.subList(i, j), sortedMap.subMap(entries.get(i).ENTRY_KEY(), entries.get(j).ENTRY_KEY()).ENTRY_SET()); + } + } + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testSubMapIllegal() { + try { + sortedMap.subMap(c.ENTRY_KEY(), a.ENTRY_KEY()); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException expected) { + } + } + +#ignore + @CollectionSize.Require(absent = ZERO) +#endignore + public void testOrderedByComparator() { + @SuppressWarnings("unchecked") + COMPARATOR KEY_GENERIC_TYPE comparator = sortedMap.comparator(); + if (comparator == null) { +#if TYPE_OBJECT + comparator = (Comparator)Comparator.naturalOrder(); +#else + comparator = CLASS_TYPE::compare; +#endif + } + Iterator entryItr = sortedMap.ENTRY_SET().iterator(); + Entry KEY_VALUE_GENERIC_TYPE prevEntry = entryItr.next(); + while (entryItr.hasNext()) { + Entry KEY_VALUE_GENERIC_TYPE nextEntry = entryItr.next(); + assertTrue(comparator.compare(prevEntry.ENTRY_KEY(), nextEntry.ENTRY_KEY()) < 0); + prevEntry = nextEntry; + } + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/queue/DequeueDequeueTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/queue/DequeueDequeueTester.template index 200acc2..b4df5c2 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/queue/DequeueDequeueTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/queue/DequeueDequeueTester.template @@ -1,62 +1,62 @@ -package speiger.src.testers.PACKAGE.tests.queue; - -import java.util.NoSuchElementException; - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.queues.PRIORITY_DEQUEUE; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEDequeueDequeueTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE -{ - protected PRIORITY_DEQUEUE KEY_GENERIC_TYPE getDequeue() { - return (PRIORITY_DEQUEUE KEY_GENERIC_TYPE)queue; - } - -#ignore - @CollectionFeature.Require(CollectionFeature.SUPPORTS_REMOVE) - @CollectionSize.Require(CollectionSize.ZERO) -#endignore - public void testDequeueFirst_Empty() { - try { - getDequeue().dequeueLast(); - fail("Queue.dequeue should throw a NoSuchElementException"); - } - catch(NoSuchElementException e) { } - expectUnchanged(); - } - -#ignore - @CollectionFeature.Require(absent = CollectionFeature.SUPPORTS_REMOVE) -#endignore - public void testDequeueFirst_Unsupported() { - try { - getDequeue().dequeueLast(); - fail("Queue.dequeue should throw a UnsupportedOperationException"); - } - catch(UnsupportedOperationException e) { } - } - -#ignore - @CollectionFeature.Require(CollectionFeature.SUPPORTS_REMOVE) - @CollectionSize.Require(CollectionSize.ONE) -#endignore - public void testDequeueFirst() { - assertEquals("Queue.dequeue should match", e0(), getDequeue().dequeueLast()); - expectMissing(e0()); - } - -#ignore - @CollectionFeature.Require(CollectionFeature.SUPPORTS_REMOVE) - @CollectionSize.Require(CollectionSize.SEVERAL) -#endignore - public void testDequeueFirstSeveral() { - assertEquals("Queue.dequeue should match", e2(), getDequeue().dequeueLast()); - expectMissing(e2()); - } +package speiger.src.testers.PACKAGE.tests.queue; + +import java.util.NoSuchElementException; + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.queues.PRIORITY_DEQUEUE; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEDequeueDequeueTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE +{ + protected PRIORITY_DEQUEUE KEY_GENERIC_TYPE getDequeue() { + return (PRIORITY_DEQUEUE KEY_GENERIC_TYPE)queue; + } + +#ignore + @CollectionFeature.Require(CollectionFeature.SUPPORTS_REMOVE) + @CollectionSize.Require(CollectionSize.ZERO) +#endignore + public void testDequeueFirst_Empty() { + try { + getDequeue().dequeueLast(); + fail("Queue.dequeue should throw a NoSuchElementException"); + } + catch(NoSuchElementException e) { } + expectUnchanged(); + } + +#ignore + @CollectionFeature.Require(absent = CollectionFeature.SUPPORTS_REMOVE) +#endignore + public void testDequeueFirst_Unsupported() { + try { + getDequeue().dequeueLast(); + fail("Queue.dequeue should throw a UnsupportedOperationException"); + } + catch(UnsupportedOperationException e) { } + } + +#ignore + @CollectionFeature.Require(CollectionFeature.SUPPORTS_REMOVE) + @CollectionSize.Require(CollectionSize.ONE) +#endignore + public void testDequeueFirst() { + assertEquals("Queue.dequeue should match", e0(), getDequeue().dequeueLast()); + expectMissing(e0()); + } + +#ignore + @CollectionFeature.Require(CollectionFeature.SUPPORTS_REMOVE) + @CollectionSize.Require(CollectionSize.SEVERAL) +#endignore + public void testDequeueFirstSeveral() { + assertEquals("Queue.dequeue should match", e2(), getDequeue().dequeueLast()); + expectMissing(e2()); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/queue/DequeueEnqueueTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/queue/DequeueEnqueueTester.template index 8b658c8..e12f011 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/queue/DequeueEnqueueTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/queue/DequeueEnqueueTester.template @@ -1,73 +1,73 @@ -package speiger.src.testers.PACKAGE.tests.queue; - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionFeature; - -import speiger.src.collections.PACKAGE.collections.COLLECTION; -import speiger.src.collections.PACKAGE.queues.PRIORITY_DEQUEUE; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEDequeueEnqueueTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE -{ - protected PRIORITY_DEQUEUE KEY_GENERIC_TYPE getDequeue() { - return (PRIORITY_DEQUEUE KEY_GENERIC_TYPE)queue; - } - -#ignore - @CollectionFeature.Require(CollectionFeature.SUPPORTS_ADD) -#endignore - public void testEnqueue() { - int initSize = queue.size(); - getDequeue().enqueueFirst(e3()); - assertEquals(initSize+1, queue.size()); - expectAdded(e3()); - } - -#ignore - @CollectionFeature.Require(absent = CollectionFeature.SUPPORTS_ADD) -#endignore - public void testEnqueue_Unsupported() { - try { - getDequeue().enqueueFirst(e3()); - fail("Queue should throw a UnsupportedOperationException"); - } - catch(UnsupportedOperationException e) { - } - } - -#ignore - @CollectionFeature.Require(CollectionFeature.SUPPORTS_ADD) -#endignore - public void testEnqueue_allArray() { - int initSize = queue.size(); - KEY_TYPE[] array = createDisjointArray(); - getDequeue().enqueueAllFirst(array); - assertEquals(initSize+array.length, queue.size()); - expectAdded(array); - } - -#ignore - @CollectionFeature.Require(CollectionFeature.SUPPORTS_ADD) -#endignore - public void testEnqueue_allArrayPartial() { - int initSize = queue.size(); - KEY_TYPE[] array = createDisjointArray(); - getDequeue().enqueueAllFirst(array, 1); - assertEquals(initSize+1, queue.size()); - expectAdded(array[0]); - } - -#ignore - @CollectionFeature.Require(CollectionFeature.SUPPORTS_ADD) -#endignore - public void testEnqueue_all() { - int initSize = queue.size(); - COLLECTION KEY_GENERIC_TYPE collection = createDisjointCollection(); - getDequeue().enqueueAllFirst(collection); - assertEquals(initSize+collection.size(), queue.size()); - expectAdded(collection.TO_ARRAY(NEW_KEY_ARRAY(collection.size()))); - } +package speiger.src.testers.PACKAGE.tests.queue; + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionFeature; + +import speiger.src.collections.PACKAGE.collections.COLLECTION; +import speiger.src.collections.PACKAGE.queues.PRIORITY_DEQUEUE; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEDequeueEnqueueTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE +{ + protected PRIORITY_DEQUEUE KEY_GENERIC_TYPE getDequeue() { + return (PRIORITY_DEQUEUE KEY_GENERIC_TYPE)queue; + } + +#ignore + @CollectionFeature.Require(CollectionFeature.SUPPORTS_ADD) +#endignore + public void testEnqueue() { + int initSize = queue.size(); + getDequeue().enqueueFirst(e3()); + assertEquals(initSize+1, queue.size()); + expectAdded(e3()); + } + +#ignore + @CollectionFeature.Require(absent = CollectionFeature.SUPPORTS_ADD) +#endignore + public void testEnqueue_Unsupported() { + try { + getDequeue().enqueueFirst(e3()); + fail("Queue should throw a UnsupportedOperationException"); + } + catch(UnsupportedOperationException e) { + } + } + +#ignore + @CollectionFeature.Require(CollectionFeature.SUPPORTS_ADD) +#endignore + public void testEnqueue_allArray() { + int initSize = queue.size(); + KEY_TYPE[] array = createDisjointArray(); + getDequeue().enqueueAllFirst(array); + assertEquals(initSize+array.length, queue.size()); + expectAdded(array); + } + +#ignore + @CollectionFeature.Require(CollectionFeature.SUPPORTS_ADD) +#endignore + public void testEnqueue_allArrayPartial() { + int initSize = queue.size(); + KEY_TYPE[] array = createDisjointArray(); + getDequeue().enqueueAllFirst(array, 1); + assertEquals(initSize+1, queue.size()); + expectAdded(array[0]); + } + +#ignore + @CollectionFeature.Require(CollectionFeature.SUPPORTS_ADD) +#endignore + public void testEnqueue_all() { + int initSize = queue.size(); + COLLECTION KEY_GENERIC_TYPE collection = createDisjointCollection(); + getDequeue().enqueueAllFirst(collection); + assertEquals(initSize+collection.size(), queue.size()); + expectAdded(collection.TO_ARRAY(NEW_KEY_ARRAY(collection.size()))); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/queue/DequeueLastTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/queue/DequeueLastTester.template index b3c8e52..9cb05da 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/queue/DequeueLastTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/queue/DequeueLastTester.template @@ -1,48 +1,48 @@ -package speiger.src.testers.PACKAGE.tests.queue; - -import java.util.NoSuchElementException; - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.queues.PRIORITY_DEQUEUE; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEDequeueLastTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE -{ - protected PRIORITY_DEQUEUE KEY_GENERIC_TYPE getDequeue() { - return (PRIORITY_DEQUEUE KEY_GENERIC_TYPE)queue; - } - -#ignore - @CollectionSize.Require(CollectionSize.ZERO) -#endignore - public void testQueueTopEmpty() { - try { - getDequeue().last(); - fail("Queue Should throw a NoSuchElementException"); - } - catch(NoSuchElementException e) {} - } - -#ignore - @CollectionSize.Require(CollectionSize.ONE) -#endignore - public void testQueueTopOne() { - assertEquals("PriorityQueue.first should be equal", e0(), getDequeue().last()); - expectUnchanged(); - } - -#ignore - @CollectionFeature.Require(CollectionFeature.KNOWN_ORDER) - @CollectionSize.Require(CollectionSize.SEVERAL) -#endignore - public void testQueueTopSeveral() { - assertEquals("PriorityQueue.first should be equal", e2(), getDequeue().last()); - expectUnchanged(); - } -} +package speiger.src.testers.PACKAGE.tests.queue; + +import java.util.NoSuchElementException; + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.queues.PRIORITY_DEQUEUE; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEDequeueLastTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE +{ + protected PRIORITY_DEQUEUE KEY_GENERIC_TYPE getDequeue() { + return (PRIORITY_DEQUEUE KEY_GENERIC_TYPE)queue; + } + +#ignore + @CollectionSize.Require(CollectionSize.ZERO) +#endignore + public void testQueueTopEmpty() { + try { + getDequeue().last(); + fail("Queue Should throw a NoSuchElementException"); + } + catch(NoSuchElementException e) {} + } + +#ignore + @CollectionSize.Require(CollectionSize.ONE) +#endignore + public void testQueueTopOne() { + assertEquals("PriorityQueue.first should be equal", e0(), getDequeue().last()); + expectUnchanged(); + } + +#ignore + @CollectionFeature.Require(CollectionFeature.KNOWN_ORDER) + @CollectionSize.Require(CollectionSize.SEVERAL) +#endignore + public void testQueueTopSeveral() { + assertEquals("PriorityQueue.first should be equal", e2(), getDequeue().last()); + expectUnchanged(); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/queue/QueueDequeueTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/queue/QueueDequeueTester.template index 3fcb07a..f6b45f6 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/queue/QueueDequeueTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/queue/QueueDequeueTester.template @@ -1,48 +1,48 @@ -package speiger.src.testers.PACKAGE.tests.queue; - -import java.util.NoSuchElementException; - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEQueueDequeueTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(CollectionFeature.SUPPORTS_REMOVE) - @CollectionSize.Require(CollectionSize.ZERO) -#endignore - public void testDequeueFirst_Empty() { - try { - queue.dequeue(); - fail("Queue.dequeue should throw a NoSuchElementException"); - } - catch(NoSuchElementException e) { } - expectUnchanged(); - } - -#ignore - @CollectionFeature.Require(absent = CollectionFeature.SUPPORTS_REMOVE) -#endignore - public void testDequeueFirst_Unsupported() { - try { - queue.dequeue(); - fail("Queue.dequeue should throw a UnsupportedOperationException"); - } - catch(UnsupportedOperationException e) { } - } - -#ignore - @CollectionFeature.Require(CollectionFeature.SUPPORTS_REMOVE) - @CollectionSize.Require(absent = CollectionSize.ZERO) -#endignore - public void testDequeueFirst() { - assertEquals("Queue.dequeue should match", e0(), queue.dequeue()); - expectMissing(e0()); - } -} +package speiger.src.testers.PACKAGE.tests.queue; + +import java.util.NoSuchElementException; + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEQueueDequeueTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(CollectionFeature.SUPPORTS_REMOVE) + @CollectionSize.Require(CollectionSize.ZERO) +#endignore + public void testDequeueFirst_Empty() { + try { + queue.dequeue(); + fail("Queue.dequeue should throw a NoSuchElementException"); + } + catch(NoSuchElementException e) { } + expectUnchanged(); + } + +#ignore + @CollectionFeature.Require(absent = CollectionFeature.SUPPORTS_REMOVE) +#endignore + public void testDequeueFirst_Unsupported() { + try { + queue.dequeue(); + fail("Queue.dequeue should throw a UnsupportedOperationException"); + } + catch(UnsupportedOperationException e) { } + } + +#ignore + @CollectionFeature.Require(CollectionFeature.SUPPORTS_REMOVE) + @CollectionSize.Require(absent = CollectionSize.ZERO) +#endignore + public void testDequeueFirst() { + assertEquals("Queue.dequeue should match", e0(), queue.dequeue()); + expectMissing(e0()); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/queue/QueueEnqueueTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/queue/QueueEnqueueTester.template index 52a7f20..7a26add 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/queue/QueueEnqueueTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/queue/QueueEnqueueTester.template @@ -1,68 +1,68 @@ -package speiger.src.testers.PACKAGE.tests.queue; - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionFeature; - -import speiger.src.collections.PACKAGE.collections.COLLECTION; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEQueueEnqueueTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(CollectionFeature.SUPPORTS_ADD) -#endignore - public void testEnqueue() { - int initSize = queue.size(); - queue.enqueue(e3()); - assertEquals(initSize+1, queue.size()); - expectAdded(e3()); - } - -#ignore - @CollectionFeature.Require(absent = CollectionFeature.SUPPORTS_ADD) -#endignore - public void testEnqueue_Unsupported() { - try { - queue.enqueue(e3()); - fail("Queue should throw a UnsupportedOperationException"); - } - catch(UnsupportedOperationException e) { - } - } - -#ignore - @CollectionFeature.Require(CollectionFeature.SUPPORTS_ADD) -#endignore - public void testEnqueue_allArray() { - int initSize = queue.size(); - KEY_TYPE[] array = createDisjointArray(); - queue.enqueueAll(array); - assertEquals(initSize+array.length, queue.size()); - expectAdded(array); - } - -#ignore - @CollectionFeature.Require(CollectionFeature.SUPPORTS_ADD) -#endignore - public void testEnqueue_allArrayPartial() { - int initSize = queue.size(); - KEY_TYPE[] array = createDisjointArray(); - queue.enqueueAll(array, 1); - assertEquals(initSize+1, queue.size()); - expectAdded(array[0]); - } - -#ignore - @CollectionFeature.Require(CollectionFeature.SUPPORTS_ADD) -#endignore - public void testEnqueue_all() { - int initSize = queue.size(); - COLLECTION KEY_GENERIC_TYPE collection = createDisjointCollection(); - queue.enqueueAll(collection); - assertEquals(initSize+collection.size(), queue.size()); - expectAdded(collection.TO_ARRAY(NEW_KEY_ARRAY(collection.size()))); - } +package speiger.src.testers.PACKAGE.tests.queue; + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionFeature; + +import speiger.src.collections.PACKAGE.collections.COLLECTION; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEQueueEnqueueTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(CollectionFeature.SUPPORTS_ADD) +#endignore + public void testEnqueue() { + int initSize = queue.size(); + queue.enqueue(e3()); + assertEquals(initSize+1, queue.size()); + expectAdded(e3()); + } + +#ignore + @CollectionFeature.Require(absent = CollectionFeature.SUPPORTS_ADD) +#endignore + public void testEnqueue_Unsupported() { + try { + queue.enqueue(e3()); + fail("Queue should throw a UnsupportedOperationException"); + } + catch(UnsupportedOperationException e) { + } + } + +#ignore + @CollectionFeature.Require(CollectionFeature.SUPPORTS_ADD) +#endignore + public void testEnqueue_allArray() { + int initSize = queue.size(); + KEY_TYPE[] array = createDisjointArray(); + queue.enqueueAll(array); + assertEquals(initSize+array.length, queue.size()); + expectAdded(array); + } + +#ignore + @CollectionFeature.Require(CollectionFeature.SUPPORTS_ADD) +#endignore + public void testEnqueue_allArrayPartial() { + int initSize = queue.size(); + KEY_TYPE[] array = createDisjointArray(); + queue.enqueueAll(array, 1); + assertEquals(initSize+1, queue.size()); + expectAdded(array[0]); + } + +#ignore + @CollectionFeature.Require(CollectionFeature.SUPPORTS_ADD) +#endignore + public void testEnqueue_all() { + int initSize = queue.size(); + COLLECTION KEY_GENERIC_TYPE collection = createDisjointCollection(); + queue.enqueueAll(collection); + assertEquals(initSize+collection.size(), queue.size()); + expectAdded(collection.TO_ARRAY(NEW_KEY_ARRAY(collection.size()))); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/queue/QueueFirstTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/queue/QueueFirstTester.template index d18a124..c47a132 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/queue/QueueFirstTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/queue/QueueFirstTester.template @@ -1,43 +1,43 @@ -package speiger.src.testers.PACKAGE.tests.queue; - -import java.util.NoSuchElementException; - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEQueueFirstTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionSize.Require(CollectionSize.ZERO) -#endignore - public void testQueueTopEmpty() { - try { - queue.first(); - fail("Queue Should throw a NoSuchElementException"); - } - catch(NoSuchElementException e) {} - } - -#ignore - @CollectionSize.Require(CollectionSize.ONE) -#endignore - public void testQueueTopOne() { - assertEquals("PriorityQueue.first should be equal", e0(), queue.first()); - expectUnchanged(); - } - -#ignore - @CollectionFeature.Require(CollectionFeature.KNOWN_ORDER) - @CollectionSize.Require(CollectionSize.SEVERAL) -#endignore - public void testQueueTopSeveral() { - assertEquals("PriorityQueue.first should be equal", e0(), queue.first()); - expectUnchanged(); - } -} +package speiger.src.testers.PACKAGE.tests.queue; + +import java.util.NoSuchElementException; + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEQueueFirstTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionSize.Require(CollectionSize.ZERO) +#endignore + public void testQueueTopEmpty() { + try { + queue.first(); + fail("Queue Should throw a NoSuchElementException"); + } + catch(NoSuchElementException e) {} + } + +#ignore + @CollectionSize.Require(CollectionSize.ONE) +#endignore + public void testQueueTopOne() { + assertEquals("PriorityQueue.first should be equal", e0(), queue.first()); + expectUnchanged(); + } + +#ignore + @CollectionFeature.Require(CollectionFeature.KNOWN_ORDER) + @CollectionSize.Require(CollectionSize.SEVERAL) +#endignore + public void testQueueTopSeveral() { + assertEquals("PriorityQueue.first should be equal", e0(), queue.first()); + expectUnchanged(); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/queue/QueueRemoveTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/queue/QueueRemoveTester.template index a2d02e1..de98efc 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/queue/QueueRemoveTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/queue/QueueRemoveTester.template @@ -1,71 +1,71 @@ -package speiger.src.testers.PACKAGE.tests.queue; - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEQueueRemoveTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(CollectionFeature.SUPPORTS_REMOVE) -#endignore - public void testRemoveFirst_Missing() { - assertFalse("Queue.removeFirst(missing) should return false", queue.removeFirst(e3())); - expectUnchanged(); - } - -#ignore - @CollectionFeature.Require(CollectionFeature.SUPPORTS_REMOVE) - @CollectionSize.Require(absent = CollectionSize.ZERO) -#endignore - public void testRemoveFirst_Present() { - assertTrue("Queue.removeFirst(present) should return true", queue.removeFirst(e0())); - expectMissing(e0()); - } - -#ignore - @CollectionFeature.Require(CollectionFeature.SUPPORTS_REMOVE) -#endignore - public void testRemoveLast_Missing() { - assertFalse("Queue.removeLast(missing) should return false", queue.removeLast(e3())); - expectUnchanged(); - } - -#ignore - @CollectionFeature.Require(CollectionFeature.SUPPORTS_REMOVE) - @CollectionSize.Require(absent = CollectionSize.ZERO) -#endignore - public void testRemoveLast_Present() { - assertTrue("Queue.removeLast(present) should return true", queue.removeLast(e0())); - expectMissing(e0()); - } - -#ignore - @CollectionFeature.Require(absent = CollectionFeature.SUPPORTS_REMOVE) -#endignore - public void testRemoveFirst_Unsupported() { - try { - queue.removeFirst(e3()); - fail("Queue.removeFirst should throw UnsupportedOperationException"); - } - catch(UnsupportedOperationException e) {} - expectUnchanged(); - } - -#ignore - @CollectionFeature.Require(absent = CollectionFeature.SUPPORTS_REMOVE) -#endignore - public void testRemoveLast_Unsupported() { - try { - queue.removeLast(e3()); - fail("Queue.removeLast should throw UnsupportedOperationException"); - } - catch(UnsupportedOperationException e) {} - expectUnchanged(); - } -} +package speiger.src.testers.PACKAGE.tests.queue; + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEQueueRemoveTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(CollectionFeature.SUPPORTS_REMOVE) +#endignore + public void testRemoveFirst_Missing() { + assertFalse("Queue.removeFirst(missing) should return false", queue.removeFirst(e3())); + expectUnchanged(); + } + +#ignore + @CollectionFeature.Require(CollectionFeature.SUPPORTS_REMOVE) + @CollectionSize.Require(absent = CollectionSize.ZERO) +#endignore + public void testRemoveFirst_Present() { + assertTrue("Queue.removeFirst(present) should return true", queue.removeFirst(e0())); + expectMissing(e0()); + } + +#ignore + @CollectionFeature.Require(CollectionFeature.SUPPORTS_REMOVE) +#endignore + public void testRemoveLast_Missing() { + assertFalse("Queue.removeLast(missing) should return false", queue.removeLast(e3())); + expectUnchanged(); + } + +#ignore + @CollectionFeature.Require(CollectionFeature.SUPPORTS_REMOVE) + @CollectionSize.Require(absent = CollectionSize.ZERO) +#endignore + public void testRemoveLast_Present() { + assertTrue("Queue.removeLast(present) should return true", queue.removeLast(e0())); + expectMissing(e0()); + } + +#ignore + @CollectionFeature.Require(absent = CollectionFeature.SUPPORTS_REMOVE) +#endignore + public void testRemoveFirst_Unsupported() { + try { + queue.removeFirst(e3()); + fail("Queue.removeFirst should throw UnsupportedOperationException"); + } + catch(UnsupportedOperationException e) {} + expectUnchanged(); + } + +#ignore + @CollectionFeature.Require(absent = CollectionFeature.SUPPORTS_REMOVE) +#endignore + public void testRemoveLast_Unsupported() { + try { + queue.removeLast(e3()); + fail("Queue.removeLast should throw UnsupportedOperationException"); + } + catch(UnsupportedOperationException e) {} + expectUnchanged(); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueCountTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueCountTester.template index c6e096f..4147754 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueCountTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueCountTester.template @@ -1,47 +1,47 @@ -package speiger.src.testers.PACKAGE.tests.queue.iterators; - -#if TYPE_OBJECT -import java.util.Objects; - -#endif -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEQueueCountTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE -{ - public void testQueueCount_null() { - try { - queue.count(null); - fail("This should throw a NullPointerException"); - } catch (NullPointerException e) { - } - } - - public void testQueueCount_NoneFound() { - assertEquals("Expected none to be found", 0, queue.count(T -> false)); - } - - public void testQueueCount_AllFound() { - assertEquals("Expected All to be found", getNumElements(), queue.count(T -> true)); - } - -#ignore - @CollectionSize.Require(absent = CollectionSize.ZERO) -#endignore - public void testQueueCount_FindFirst() - { - assertEquals("First element should be found", 1, queue.count(T -> KEY_EQUALS(T, e0()))); - } - -#ignore - @CollectionSize.Require(CollectionSize.SEVERAL) -#endignore - public void testQueueCount_FindLast() { - assertEquals("Last element should be found", 1, queue.count(T -> KEY_EQUALS(T, e2()))); - } +package speiger.src.testers.PACKAGE.tests.queue.iterators; + +#if TYPE_OBJECT +import java.util.Objects; + +#endif +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEQueueCountTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE +{ + public void testQueueCount_null() { + try { + queue.count(null); + fail("This should throw a NullPointerException"); + } catch (NullPointerException e) { + } + } + + public void testQueueCount_NoneFound() { + assertEquals("Expected none to be found", 0, queue.count(T -> false)); + } + + public void testQueueCount_AllFound() { + assertEquals("Expected All to be found", getNumElements(), queue.count(T -> true)); + } + +#ignore + @CollectionSize.Require(absent = CollectionSize.ZERO) +#endignore + public void testQueueCount_FindFirst() + { + assertEquals("First element should be found", 1, queue.count(T -> KEY_EQUALS(T, e0()))); + } + +#ignore + @CollectionSize.Require(CollectionSize.SEVERAL) +#endignore + public void testQueueCount_FindLast() { + assertEquals("Last element should be found", 1, queue.count(T -> KEY_EQUALS(T, e2()))); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueDistinctTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueDistinctTester.template index 46187e0..f00f6d0 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueDistinctTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueDistinctTester.template @@ -1,24 +1,24 @@ -package speiger.src.testers.PACKAGE.tests.queue.iterators; - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEQueueDistinctTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionSize.Require(CollectionSize.SEVERAL) -#endignore - public void testDistinct() - { - ArrayWithDuplicate KEY_GENERIC_TYPE duplicate = createArrayWithDuplicateElement(); - resetContainer(queueGenerator.create(duplicate.elements)); - LIST KEY_GENERIC_TYPE list = queue.distinct().pourAsList(); - assertEquals("Distinct should remove duplicate elements", list.indexOf(duplicate.duplicate), list.lastIndexOf(duplicate.duplicate)); - } -} +package speiger.src.testers.PACKAGE.tests.queue.iterators; + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEQueueDistinctTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionSize.Require(CollectionSize.SEVERAL) +#endignore + public void testDistinct() + { + ArrayWithDuplicate KEY_GENERIC_TYPE duplicate = createArrayWithDuplicateElement(); + resetContainer(queueGenerator.create(duplicate.elements)); + LIST KEY_GENERIC_TYPE list = queue.distinct().pourAsList(); + assertEquals("Distinct should remove duplicate elements", list.indexOf(duplicate.duplicate), list.lastIndexOf(duplicate.duplicate)); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueFindFirstTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueFindFirstTester.template index d20b1b7..aa90be0 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueFindFirstTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueFindFirstTester.template @@ -1,43 +1,43 @@ -package speiger.src.testers.PACKAGE.tests.queue.iterators; - -#if TYPE_OBJECT -import java.util.Objects; - -#endif -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEQueueFindFirstTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE -{ - public void testQueueFindFirst_null() { - try { - queue.findFirst(null); - fail("This should throw a NullPointerException"); - } - catch (NullPointerException e) { - } - } - -#ignore - @CollectionSize.Require(absent = CollectionSize.ZERO) -#endignore - public void testQueueFindFirst_FindFirstElements() { - assertEquals("First Element should be found", e0(), queue.findFirst(T -> KEY_EQUALS(T, e0()))); - } - - public void testQueueFindFirst_FindNothing() { - assertEquals("No element should be found", EMPTY_KEY_VALUE, queue.findFirst(T -> KEY_EQUALS(T, e4()))); - } - -#ignore - @CollectionSize.Require(CollectionSize.SEVERAL) -#endignore - public void testQueueFindFirst_FindLastElement() { - assertEquals("Last Element should be found", e2(), queue.findFirst(T -> KEY_EQUALS(T, e2()))); - } -} +package speiger.src.testers.PACKAGE.tests.queue.iterators; + +#if TYPE_OBJECT +import java.util.Objects; + +#endif +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEQueueFindFirstTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE +{ + public void testQueueFindFirst_null() { + try { + queue.findFirst(null); + fail("This should throw a NullPointerException"); + } + catch (NullPointerException e) { + } + } + +#ignore + @CollectionSize.Require(absent = CollectionSize.ZERO) +#endignore + public void testQueueFindFirst_FindFirstElements() { + assertEquals("First Element should be found", e0(), queue.findFirst(T -> KEY_EQUALS(T, e0()))); + } + + public void testQueueFindFirst_FindNothing() { + assertEquals("No element should be found", EMPTY_KEY_VALUE, queue.findFirst(T -> KEY_EQUALS(T, e4()))); + } + +#ignore + @CollectionSize.Require(CollectionSize.SEVERAL) +#endignore + public void testQueueFindFirst_FindLastElement() { + assertEquals("Last Element should be found", e2(), queue.findFirst(T -> KEY_EQUALS(T, e2()))); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueForEachTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueForEachTester.template index d1ad591..e7e8a8b 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueForEachTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueForEachTester.template @@ -1,19 +1,19 @@ -package speiger.src.testers.PACKAGE.tests.queue.iterators; - -import org.junit.Ignore; - -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEQueueForEachTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE -{ - public void testQueueForEach() { - LIST KEY_GENERIC_TYPE peeked = new ARRAY_LISTBRACES(); - LIST KEY_GENERIC_TYPE result = new ARRAY_LISTBRACES(); - queue.peek(peeked::add).forEach(result, LIST::add); - assertEquals("Collections should match since peek is just a preview of foreach", result, peeked); - } -} +package speiger.src.testers.PACKAGE.tests.queue.iterators; + +import org.junit.Ignore; + +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEQueueForEachTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE +{ + public void testQueueForEach() { + LIST KEY_GENERIC_TYPE peeked = new ARRAY_LISTBRACES(); + LIST KEY_GENERIC_TYPE result = new ARRAY_LISTBRACES(); + queue.peek(peeked::add).forEach(result, LIST::add); + assertEquals("Collections should match since peek is just a preview of foreach", result, peeked); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueLimitTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueLimitTester.template index 138122b..a7ca018 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueLimitTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueLimitTester.template @@ -1,25 +1,25 @@ -package speiger.src.testers.PACKAGE.tests.queue.iterators; - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEQueueLimitTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionSize.Require(absent = CollectionSize.ZERO) -#endignore - public void testQueueLimit() { - LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(queue.TO_ARRAY()); - list.REMOVE(list.size()-1); - LIST KEY_GENERIC_TYPE result = queue.limit(getNumElements()-1).pourAsList(); - assertEquals(list.size(), result.size()); - assertEquals("Limit does not retain the iteration order", list, result); - } -} +package speiger.src.testers.PACKAGE.tests.queue.iterators; + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEQueueLimitTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionSize.Require(absent = CollectionSize.ZERO) +#endignore + public void testQueueLimit() { + LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(queue.TO_ARRAY()); + list.REMOVE(list.size()-1); + LIST KEY_GENERIC_TYPE result = queue.limit(getNumElements()-1).pourAsList(); + assertEquals(list.size(), result.size()); + assertEquals("Limit does not retain the iteration order", list, result); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueMapTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueMapTester.template index e7eeb37..4a9c2f8 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueMapTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueMapTester.template @@ -1,182 +1,182 @@ -package speiger.src.testers.PACKAGE.tests.queue.iterators; - -#if TYPE_OBJECT || TYPE_BOOLEAN -import java.util.Objects; -#endif - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionFeature; - -#if TYPE_OBJECT || TYPE_BOOLEAN -import speiger.src.collections.chars.utils.CharArrays; -#endif -import speiger.src.collections.objects.lists.ObjectArrayList; -import speiger.src.collections.objects.lists.ObjectList; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; -import speiger.src.testers.PACKAGE.utils.HELPERS; -#if !TYPE_OBJECT -import speiger.src.testers.objects.utils.ObjectHelpers; -#endif - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEQueueMapTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE -{ - public void testQueueMap_ToString() { - assertEquals(HELPERS.copyToList(queue.TO_ARRAY()).toString(), queue.map(CLASS_OBJECT_TYPE::toString).pourAsList().toString()); - } -#if TYPE_BOOLEAN - -#ignore - @CollectionFeature.Require(CollectionFeature.KNOWN_ORDER) -#endignore - public void testQueueMap_Collection() { - ObjectList result = new ObjectArrayList<>(); - for(KEY_TYPE entry : getOrderedElements()) { - result.addAll(toRange(entry)); - } - assertEquals(result, queue.flatMap(T -> ObjectArrayList.wrap(toRange(T))).pourAsList()); - } - -#ignore - @CollectionFeature.Require(CollectionFeature.KNOWN_ORDER) -#endignore - public void testQueueMap_Array() { - ObjectList result = new ObjectArrayList<>(); - for(KEY_TYPE entry : getOrderedElements()) { - result.addAll(toRange(entry)); - } - assertEquals(result, queue.arrayflatMap(this::toRange).pourAsList()); - } - -#ignore - @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) -#endignore - public void testQueueMap_CollectionUnordered() { - ObjectList result = new ObjectArrayList<>(); - for(KEY_TYPE entry : getOrderedElements()) { - result.addAll(toRange(entry)); - } - ObjectHelpers.assertEqualIgnoringOrder(result, queue.flatMap(T -> ObjectArrayList.wrap(toRange(T))).pourAsList()); - } - -#ignore - @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) -#endignore - public void testQueueMap_ArrayUnordered() { - ObjectList result = new ObjectArrayList<>(); - for(KEY_TYPE entry : getOrderedElements()) { - result.addAll(toRange(entry)); - } - ObjectHelpers.assertEqualIgnoringOrder(result, queue.arrayflatMap(this::toRange).pourAsList()); - } - - private Character[] toRange(boolean value) { - return CharArrays.wrap(Objects.toString(value).toCharArray()); - - } -#else if !TYPE_OBJECT - -#ignore - @CollectionFeature.Require(CollectionFeature.KNOWN_ORDER) -#endignore - public void testQueueMap_Collection() { - ObjectList result = new ObjectArrayList<>(); - for(KEY_TYPE entry : getOrderedElements()) { - result.addAll(toRange((int)entry)); - } - assertEquals(result, queue.flatMap(T -> ObjectArrayList.wrap(toRange((int)T))).pourAsList()); - } - -#ignore - @CollectionFeature.Require(CollectionFeature.KNOWN_ORDER) -#endignore - public void testQueueMap_Array() { - ObjectList result = new ObjectArrayList<>(); - for(KEY_TYPE entry : getOrderedElements()) { - result.addAll(toRange((int)entry)); - } - assertEquals(result, queue.arrayflatMap(T -> toRange((int)T)).pourAsList()); - } - -#ignore - @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) -#endignore - public void testQueueMap_CollectionUnordered() { - ObjectList result = new ObjectArrayList<>(); - for(KEY_TYPE entry : getOrderedElements()) { - result.addAll(toRange((int)entry)); - } - ObjectHelpers.assertEqualIgnoringOrder(result, queue.flatMap(T -> ObjectArrayList.wrap(toRange((int)T))).pourAsList()); - } - -#ignore - @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) -#endignore - public void testQueueMap_ArrayUnordered() { - ObjectList result = new ObjectArrayList<>(); - for(KEY_TYPE entry : getOrderedElements()) { - result.addAll(toRange((int)entry)); - } - ObjectHelpers.assertEqualIgnoringOrder(result, queue.arrayflatMap(T -> toRange((int)T)).pourAsList()); - } - - private Integer[] toRange(int range) { - Integer[] result = new Integer[range]; - for(int i = 0;i result = new ObjectArrayList<>(); - for(KEY_TYPE entry : getOrderedElements()) { - result.addAll(toRange(entry)); - } - assertEquals(result, queue.flatMap(T -> ObjectArrayList.wrap(toRange(T))).pourAsList()); - } - -#ignore - @CollectionFeature.Require(CollectionFeature.KNOWN_ORDER) -#endignore - public void testQueueMap_Array() { - ObjectList result = new ObjectArrayList<>(); - for(KEY_TYPE entry : getOrderedElements()) { - result.addAll(toRange(entry)); - } - assertEquals(result, queue.arrayflatMap(this::toRange).pourAsList()); - } - -#ignore - @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) -#endignore - public void testQueueMap_CollectionUnordered() { - ObjectList result = new ObjectArrayList<>(); - for(KEY_TYPE entry : getOrderedElements()) { - result.addAll(toRange(entry)); - } - ObjectHelpers.assertEqualIgnoringOrder(result, queue.flatMap(T -> ObjectArrayList.wrap(toRange(T))).pourAsList()); - } - -#ignore - @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) -#endignore - public void testQueueMap_ArrayUnordered() { - ObjectList result = new ObjectArrayList<>(); - for(KEY_TYPE entry : getOrderedElements()) { - result.addAll(toRange(entry)); - } - ObjectHelpers.assertEqualIgnoringOrder(result, queue.arrayflatMap(this::toRange).pourAsList()); - } - - private Character[] toRange(T obj) { - return CharArrays.wrap(Objects.toString(obj).toCharArray()); - } -#endif -} +package speiger.src.testers.PACKAGE.tests.queue.iterators; + +#if TYPE_OBJECT || TYPE_BOOLEAN +import java.util.Objects; +#endif + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionFeature; + +#if TYPE_OBJECT || TYPE_BOOLEAN +import speiger.src.collections.chars.utils.CharArrays; +#endif +import speiger.src.collections.objects.lists.ObjectArrayList; +import speiger.src.collections.objects.lists.ObjectList; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; +import speiger.src.testers.PACKAGE.utils.HELPERS; +#if !TYPE_OBJECT +import speiger.src.testers.objects.utils.ObjectHelpers; +#endif + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEQueueMapTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE +{ + public void testQueueMap_ToString() { + assertEquals(HELPERS.copyToList(queue.TO_ARRAY()).toString(), queue.map(CLASS_OBJECT_TYPE::toString).pourAsList().toString()); + } +#if TYPE_BOOLEAN + +#ignore + @CollectionFeature.Require(CollectionFeature.KNOWN_ORDER) +#endignore + public void testQueueMap_Collection() { + ObjectList result = new ObjectArrayList<>(); + for(KEY_TYPE entry : getOrderedElements()) { + result.addAll(toRange(entry)); + } + assertEquals(result, queue.flatMap(T -> ObjectArrayList.wrap(toRange(T))).pourAsList()); + } + +#ignore + @CollectionFeature.Require(CollectionFeature.KNOWN_ORDER) +#endignore + public void testQueueMap_Array() { + ObjectList result = new ObjectArrayList<>(); + for(KEY_TYPE entry : getOrderedElements()) { + result.addAll(toRange(entry)); + } + assertEquals(result, queue.arrayflatMap(this::toRange).pourAsList()); + } + +#ignore + @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) +#endignore + public void testQueueMap_CollectionUnordered() { + ObjectList result = new ObjectArrayList<>(); + for(KEY_TYPE entry : getOrderedElements()) { + result.addAll(toRange(entry)); + } + ObjectHelpers.assertEqualIgnoringOrder(result, queue.flatMap(T -> ObjectArrayList.wrap(toRange(T))).pourAsList()); + } + +#ignore + @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) +#endignore + public void testQueueMap_ArrayUnordered() { + ObjectList result = new ObjectArrayList<>(); + for(KEY_TYPE entry : getOrderedElements()) { + result.addAll(toRange(entry)); + } + ObjectHelpers.assertEqualIgnoringOrder(result, queue.arrayflatMap(this::toRange).pourAsList()); + } + + private Character[] toRange(boolean value) { + return CharArrays.wrap(Objects.toString(value).toCharArray()); + + } +#else if !TYPE_OBJECT + +#ignore + @CollectionFeature.Require(CollectionFeature.KNOWN_ORDER) +#endignore + public void testQueueMap_Collection() { + ObjectList result = new ObjectArrayList<>(); + for(KEY_TYPE entry : getOrderedElements()) { + result.addAll(toRange((int)entry)); + } + assertEquals(result, queue.flatMap(T -> ObjectArrayList.wrap(toRange((int)T))).pourAsList()); + } + +#ignore + @CollectionFeature.Require(CollectionFeature.KNOWN_ORDER) +#endignore + public void testQueueMap_Array() { + ObjectList result = new ObjectArrayList<>(); + for(KEY_TYPE entry : getOrderedElements()) { + result.addAll(toRange((int)entry)); + } + assertEquals(result, queue.arrayflatMap(T -> toRange((int)T)).pourAsList()); + } + +#ignore + @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) +#endignore + public void testQueueMap_CollectionUnordered() { + ObjectList result = new ObjectArrayList<>(); + for(KEY_TYPE entry : getOrderedElements()) { + result.addAll(toRange((int)entry)); + } + ObjectHelpers.assertEqualIgnoringOrder(result, queue.flatMap(T -> ObjectArrayList.wrap(toRange((int)T))).pourAsList()); + } + +#ignore + @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) +#endignore + public void testQueueMap_ArrayUnordered() { + ObjectList result = new ObjectArrayList<>(); + for(KEY_TYPE entry : getOrderedElements()) { + result.addAll(toRange((int)entry)); + } + ObjectHelpers.assertEqualIgnoringOrder(result, queue.arrayflatMap(T -> toRange((int)T)).pourAsList()); + } + + private Integer[] toRange(int range) { + Integer[] result = new Integer[range]; + for(int i = 0;i result = new ObjectArrayList<>(); + for(KEY_TYPE entry : getOrderedElements()) { + result.addAll(toRange(entry)); + } + assertEquals(result, queue.flatMap(T -> ObjectArrayList.wrap(toRange(T))).pourAsList()); + } + +#ignore + @CollectionFeature.Require(CollectionFeature.KNOWN_ORDER) +#endignore + public void testQueueMap_Array() { + ObjectList result = new ObjectArrayList<>(); + for(KEY_TYPE entry : getOrderedElements()) { + result.addAll(toRange(entry)); + } + assertEquals(result, queue.arrayflatMap(this::toRange).pourAsList()); + } + +#ignore + @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) +#endignore + public void testQueueMap_CollectionUnordered() { + ObjectList result = new ObjectArrayList<>(); + for(KEY_TYPE entry : getOrderedElements()) { + result.addAll(toRange(entry)); + } + ObjectHelpers.assertEqualIgnoringOrder(result, queue.flatMap(T -> ObjectArrayList.wrap(toRange(T))).pourAsList()); + } + +#ignore + @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) +#endignore + public void testQueueMap_ArrayUnordered() { + ObjectList result = new ObjectArrayList<>(); + for(KEY_TYPE entry : getOrderedElements()) { + result.addAll(toRange(entry)); + } + ObjectHelpers.assertEqualIgnoringOrder(result, queue.arrayflatMap(this::toRange).pourAsList()); + } + + private Character[] toRange(T obj) { + return CharArrays.wrap(Objects.toString(obj).toCharArray()); + } +#endif +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueMatchesTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueMatchesTester.template index 2e8454c..ae86189 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueMatchesTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueMatchesTester.template @@ -1,107 +1,107 @@ -package speiger.src.testers.PACKAGE.tests.queue.iterators; - -#if TYPE_OBJECT -import java.util.Objects; - -#endif -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.collections.COLLECTION; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEQueueMatchesTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE -{ - public void testQueueMatch_AnyNull() { - try { - queue.matchesAny(null); - fail("MatchesAny should throw a NullPointException"); - } - catch (NullPointerException e) { - } - } - -#ignore - @CollectionSize.Require(absent = CollectionSize.ZERO) -#endignore - public void testQueueMatch_AnyFoundFirstElement() { - assertTrue("Element ["+e0()+"] should be found", queue.matchesAny(T -> KEY_EQUALS(T, e0()))); - } - -#ignore - @CollectionSize.Require(CollectionSize.SEVERAL) -#endignore - public void testQueueMatch_AnyFoundLastElement() { - assertTrue("Element ["+e2()+"] should be found", queue.matchesAny(T -> KEY_EQUALS(T, e2()))); - } - - public void testQueueMatch_AnyFoundNoElement() { - assertFalse("Element ["+e4()+"] should not be found", queue.matchesAny(T -> KEY_EQUALS(T, e4()))); - } - - public void testQueueMatch_NoneNull() { - try { - queue.matchesNone(null); - fail("MatchesNone should throw a NullPointException"); - } - catch (NullPointerException e) { - } - } - -#ignore - @CollectionSize.Require(absent = CollectionSize.ZERO) -#endignore - public void testQueueMatch_NoneFoundFirstElement() { - assertFalse("Element ["+e0()+"] should not be found", queue.matchesNone(T -> KEY_EQUALS(T, e0()))); - } - -#ignore - @CollectionSize.Require(CollectionSize.SEVERAL) -#endignore - public void testQueueMatch_NoneFoundLastElement() { - assertFalse("Element ["+e2()+"] should not be found", queue.matchesNone(T -> KEY_EQUALS(T, e2()))); - } - - public void testQueueMatch_NoneFoundNoElement() { - assertTrue("Element ["+e4()+"] should not be found", queue.matchesNone(T -> KEY_EQUALS(T, e4()))); - } - - public void testQueueMatch_AllNull() { - try { - queue.matchesAll(null); - fail("MatchesAny should throw a NullPointException"); - } - catch (NullPointerException e) { - } - } - - public void testQueueMatch_AllFoundAllElements() { - COLLECTION KEY_GENERIC_TYPE lists = new ARRAY_LISTBRACES(queue.TO_ARRAY()); - assertTrue("All elements should be found", queue.matchesAll(lists::contains)); - } - -#ignore - @CollectionSize.Require(absent = CollectionSize.ZERO) -#endignore - public void testQueueMatch_AllFoundNone() { - assertFalse("It should not find anything", queue.matchesAll(T -> false)); - } - -#ignore - @CollectionSize.Require(CollectionSize.ZERO) -#endignore - public void testQueueMatch_AllFoundNoneEmpty() { - assertTrue("Empty Collections should return true even if all have to be found", queue.matchesAll(T -> false)); - } - -#ignore - @CollectionSize.Require(CollectionSize.SEVERAL) -#endignore - public void testQueueMatches_AllPartical() { - assertFalse("Even if some elements were found, it should return false", queue.matchesAll(T -> KEY_EQUALS(T, e0()))); - } -} +package speiger.src.testers.PACKAGE.tests.queue.iterators; + +#if TYPE_OBJECT +import java.util.Objects; + +#endif +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.collections.COLLECTION; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEQueueMatchesTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE +{ + public void testQueueMatch_AnyNull() { + try { + queue.matchesAny(null); + fail("MatchesAny should throw a NullPointException"); + } + catch (NullPointerException e) { + } + } + +#ignore + @CollectionSize.Require(absent = CollectionSize.ZERO) +#endignore + public void testQueueMatch_AnyFoundFirstElement() { + assertTrue("Element ["+e0()+"] should be found", queue.matchesAny(T -> KEY_EQUALS(T, e0()))); + } + +#ignore + @CollectionSize.Require(CollectionSize.SEVERAL) +#endignore + public void testQueueMatch_AnyFoundLastElement() { + assertTrue("Element ["+e2()+"] should be found", queue.matchesAny(T -> KEY_EQUALS(T, e2()))); + } + + public void testQueueMatch_AnyFoundNoElement() { + assertFalse("Element ["+e4()+"] should not be found", queue.matchesAny(T -> KEY_EQUALS(T, e4()))); + } + + public void testQueueMatch_NoneNull() { + try { + queue.matchesNone(null); + fail("MatchesNone should throw a NullPointException"); + } + catch (NullPointerException e) { + } + } + +#ignore + @CollectionSize.Require(absent = CollectionSize.ZERO) +#endignore + public void testQueueMatch_NoneFoundFirstElement() { + assertFalse("Element ["+e0()+"] should not be found", queue.matchesNone(T -> KEY_EQUALS(T, e0()))); + } + +#ignore + @CollectionSize.Require(CollectionSize.SEVERAL) +#endignore + public void testQueueMatch_NoneFoundLastElement() { + assertFalse("Element ["+e2()+"] should not be found", queue.matchesNone(T -> KEY_EQUALS(T, e2()))); + } + + public void testQueueMatch_NoneFoundNoElement() { + assertTrue("Element ["+e4()+"] should not be found", queue.matchesNone(T -> KEY_EQUALS(T, e4()))); + } + + public void testQueueMatch_AllNull() { + try { + queue.matchesAll(null); + fail("MatchesAny should throw a NullPointException"); + } + catch (NullPointerException e) { + } + } + + public void testQueueMatch_AllFoundAllElements() { + COLLECTION KEY_GENERIC_TYPE lists = new ARRAY_LISTBRACES(queue.TO_ARRAY()); + assertTrue("All elements should be found", queue.matchesAll(lists::contains)); + } + +#ignore + @CollectionSize.Require(absent = CollectionSize.ZERO) +#endignore + public void testQueueMatch_AllFoundNone() { + assertFalse("It should not find anything", queue.matchesAll(T -> false)); + } + +#ignore + @CollectionSize.Require(CollectionSize.ZERO) +#endignore + public void testQueueMatch_AllFoundNoneEmpty() { + assertTrue("Empty Collections should return true even if all have to be found", queue.matchesAll(T -> false)); + } + +#ignore + @CollectionSize.Require(CollectionSize.SEVERAL) +#endignore + public void testQueueMatches_AllPartical() { + assertFalse("Even if some elements were found, it should return false", queue.matchesAll(T -> KEY_EQUALS(T, e0()))); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueuePeekTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueuePeekTester.template index 000a309..9b5717c 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueuePeekTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueuePeekTester.template @@ -1,19 +1,19 @@ -package speiger.src.testers.PACKAGE.tests.queue.iterators; - -import org.junit.Ignore; - -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEQueuePeekTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE -{ - public void testQueuePeek() { - LIST KEY_GENERIC_TYPE peeked = new ARRAY_LISTBRACES(); - LIST KEY_GENERIC_TYPE result = new ARRAY_LISTBRACES(); - queue.peek(peeked::add).forEach(result::add); - assertEquals("Collections should match since peek is just a preview of foreach", result, peeked); - } -} +package speiger.src.testers.PACKAGE.tests.queue.iterators; + +import org.junit.Ignore; + +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEQueuePeekTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE +{ + public void testQueuePeek() { + LIST KEY_GENERIC_TYPE peeked = new ARRAY_LISTBRACES(); + LIST KEY_GENERIC_TYPE result = new ARRAY_LISTBRACES(); + queue.peek(peeked::add).forEach(result::add); + assertEquals("Collections should match since peek is just a preview of foreach", result, peeked); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueReduceTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueReduceTester.template index 590140e..5cc29b6 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueReduceTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueReduceTester.template @@ -1,80 +1,80 @@ -package speiger.src.testers.PACKAGE.tests.queue.iterators; - -#if TYPE_OBJECT -import java.util.Objects; - -#endif -import org.junit.Ignore; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEQueueReduceTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE -{ - public void testQueueReduce_Null() { - try { - queue.reduce(null); - fail("This should crash"); - } catch (NullPointerException e) { - } - } - - public void testQueueReduce_extraNull() { - try { - queue.reduce(EMPTY_KEY_VALUE, null); - fail("This should crash"); - } catch (NullPointerException e) { - } - } - - public void testQueueReduce() { - assertEquals("The sum of the queue should match", getSum(), queue.reduce(this::sum)); - } - - public void testQueueExtraReduce() { -#if TYPE_OBJECT - assertEquals("The sum of the queue should match", getObjectSum(), queue.reduce(new StringBuilder(), this::sum).toString()); -#else - assertEquals("The sum of the queue should match", getSum(), queue.reduce(EMPTY_KEY_VALUE, this::sum)); -#endif - } - - public KEY_TYPE getSum() - { - KEY_TYPE result = EMPTY_KEY_VALUE; - for(KEY_TYPE key : queue.TO_ARRAY(NEW_KEY_ARRAY(queue.size()))) - { - result = sum(result, key); - } - return result; - } - - public KEY_TYPE sum(KEY_TYPE key, KEY_TYPE value) - { -#if TYPE_BYTE || TYPE_SHORT || TYPE_CHAR - return (KEY_TYPE)(key + value); -#else if TYPE_OBJECT - return value; -#else if TYPE_BOOLEAN - return key ^ value; -#else - return key + value; -#endif - } - -#if TYPE_OBJECT - public StringBuilder sum(StringBuilder builder, T value) { - return builder.append(Objects.toString(value)); - } - - public String getObjectSum() { - StringBuilder builder = new StringBuilder(); - for(T key : queue.TO_ARRAY(NEW_KEY_ARRAY(queue.size()))) - { - builder = sum(builder, key); - } - return builder.toString(); - } -#endif -} +package speiger.src.testers.PACKAGE.tests.queue.iterators; + +#if TYPE_OBJECT +import java.util.Objects; + +#endif +import org.junit.Ignore; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEQueueReduceTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE +{ + public void testQueueReduce_Null() { + try { + queue.reduce(null); + fail("This should crash"); + } catch (NullPointerException e) { + } + } + + public void testQueueReduce_extraNull() { + try { + queue.reduce(EMPTY_KEY_VALUE, null); + fail("This should crash"); + } catch (NullPointerException e) { + } + } + + public void testQueueReduce() { + assertEquals("The sum of the queue should match", getSum(), queue.reduce(this::sum)); + } + + public void testQueueExtraReduce() { +#if TYPE_OBJECT + assertEquals("The sum of the queue should match", getObjectSum(), queue.reduce(new StringBuilder(), this::sum).toString()); +#else + assertEquals("The sum of the queue should match", getSum(), queue.reduce(EMPTY_KEY_VALUE, this::sum)); +#endif + } + + public KEY_TYPE getSum() + { + KEY_TYPE result = EMPTY_KEY_VALUE; + for(KEY_TYPE key : queue.TO_ARRAY(NEW_KEY_ARRAY(queue.size()))) + { + result = sum(result, key); + } + return result; + } + + public KEY_TYPE sum(KEY_TYPE key, KEY_TYPE value) + { +#if TYPE_BYTE || TYPE_SHORT || TYPE_CHAR + return (KEY_TYPE)(key + value); +#else if TYPE_OBJECT + return value; +#else if TYPE_BOOLEAN + return key ^ value; +#else + return key + value; +#endif + } + +#if TYPE_OBJECT + public StringBuilder sum(StringBuilder builder, T value) { + return builder.append(Objects.toString(value)); + } + + public String getObjectSum() { + StringBuilder builder = new StringBuilder(); + for(T key : queue.TO_ARRAY(NEW_KEY_ARRAY(queue.size()))) + { + builder = sum(builder, key); + } + return builder.toString(); + } +#endif +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueSortedTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueSortedTester.template index 0c923f4..845283d 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueSortedTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/queue/iterators/QueueSortedTester.template @@ -1,43 +1,43 @@ -package speiger.src.testers.PACKAGE.tests.queue.iterators; - -import org.junit.Ignore; - -#if TYPE_OBJECT -import java.util.Comparator; -import java.util.Map; -#endif - -import com.google.common.collect.testing.features.CollectionFeature; - -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; -import speiger.src.testers.utils.SpecialFeature; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEQueueSortedTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) - @SpecialFeature.Require(absent = SpecialFeature.MAP_ENTRY) -#endignore - public void testQueueSorted() { - LIST KEY_GENERIC_TYPE expected = new ARRAY_LISTBRACES(queue.TO_ARRAY()); - expected.sort(null); - assertEquals("Elements were expected to be sorted", expected, queue.sorted(null).pourAsList()); - } - -#if TYPE_OBJECT -#ignore - @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) - @SpecialFeature.Require(SpecialFeature.MAP_ENTRY) -#endignore - public void testQueueSortedEntry() { - ObjectList expected = new ObjectArrayList<>(queue.TO_ARRAY()); - Comparator comparator = Comparator.comparing(T -> (Comparable)((Map.Entry)T).getKey()); - expected.sort(comparator); - assertEquals("Elements were expected to be sorted", expected, queue.sorted(comparator).pourAsList()); - } -#endif -} +package speiger.src.testers.PACKAGE.tests.queue.iterators; + +import org.junit.Ignore; + +#if TYPE_OBJECT +import java.util.Comparator; +import java.util.Map; +#endif + +import com.google.common.collect.testing.features.CollectionFeature; + +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; +import speiger.src.testers.utils.SpecialFeature; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEQueueSortedTester KEY_GENERIC_TYPE extends ABSTRACT_QUEUE_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) + @SpecialFeature.Require(absent = SpecialFeature.MAP_ENTRY) +#endignore + public void testQueueSorted() { + LIST KEY_GENERIC_TYPE expected = new ARRAY_LISTBRACES(queue.TO_ARRAY()); + expected.sort(null); + assertEquals("Elements were expected to be sorted", expected, queue.sorted(null).pourAsList()); + } + +#if TYPE_OBJECT +#ignore + @CollectionFeature.Require(absent = CollectionFeature.KNOWN_ORDER) + @SpecialFeature.Require(SpecialFeature.MAP_ENTRY) +#endignore + public void testQueueSortedEntry() { + ObjectList expected = new ObjectArrayList<>(queue.TO_ARRAY()); + Comparator comparator = Comparator.comparing(T -> (Comparable)((Map.Entry)T).getKey()); + expected.sort(comparator); + assertEquals("Elements were expected to be sorted", expected, queue.sorted(comparator).pourAsList()); + } +#endif +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/set/NavigableSetNavigationTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/set/NavigableSetNavigationTester.template index b3d5a53..9d9d7a2 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/set/NavigableSetNavigationTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/set/NavigableSetNavigationTester.template @@ -1,285 +1,285 @@ -package speiger.src.testers.PACKAGE.tests.set; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import java.util.TreeSet; - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.collections.ITERATOR; -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET; -import speiger.src.collections.PACKAGE.utils.LISTS; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_SET_TESTER; -import speiger.src.testers.PACKAGE.utils.HELPERS; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPENavigableSetNavigationTester KEY_GENERIC_TYPE extends ABSTRACT_SET_TESTER KEY_GENERIC_TYPE -{ - private NAVIGABLE_SET KEY_GENERIC_TYPE navigableSet; - private LIST KEY_GENERIC_TYPE values; - private KEY_TYPE a; - private KEY_TYPE b; - private KEY_TYPE c; - - @Override - public void setUp() throws Exception { - super.setUp(); - navigableSet = (NAVIGABLE_SET KEY_GENERIC_TYPE) getSet(); - values = HELPERS.copyToList(getSampleElements(getSubjectGenerator().getCollectionSize().getNumElements())); - values.sort(navigableSet.comparator()); - if (values.size() >= 1) { - a = values.GET_KEY(0); - if (values.size() >= 3) { - b = values.GET_KEY(1); - c = values.GET_KEY(2); - } - } - } - - protected void resetWithHole() { - super.resetContainer(primitiveGenerator.create(createArray(a, c))); - navigableSet = (NAVIGABLE_SET KEY_GENERIC_TYPE) getSet(); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ZERO) -#endignore - public void testEmptySetPollFirst() { -#if TYPE_OBJECT - assertEquals(null, navigableSet.POLL_FIRST_KEY()); -#else - assertEquals(navigableSet.getDefaultMinValue(), navigableSet.POLL_FIRST_KEY()); -#endif - } - -#ignore - @CollectionSize.Require(ZERO) -#endignore - public void testEmptySetNearby() { -#if TYPE_OBJECT - assertEquals(null, navigableSet.lower(e0())); - assertEquals(null, navigableSet.floor(e0())); - assertEquals(null, navigableSet.ceiling(e0())); - assertEquals(null, navigableSet.higher(e0())); -#else - assertEquals(navigableSet.getDefaultMinValue(), navigableSet.lower(e0())); - assertEquals(navigableSet.getDefaultMinValue(), navigableSet.floor(e0())); - assertEquals(navigableSet.getDefaultMaxValue(), navigableSet.ceiling(e0())); - assertEquals(navigableSet.getDefaultMaxValue(), navigableSet.higher(e0())); -#endif - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ZERO) -#endignore - public void testEmptySetPollLast() { -#if TYPE_OBJECT - assertEquals(null, navigableSet.POLL_LAST_KEY()); -#else - assertEquals(navigableSet.getDefaultMaxValue(), navigableSet.POLL_LAST_KEY()); -#endif - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ONE) -#endignore - public void testSingletonSetPollFirst() { - assertEquals(a, navigableSet.POLL_FIRST_KEY()); - assertTrue(navigableSet.isEmpty()); - } - -#ignore - @CollectionSize.Require(ONE) -#endignore - public void testSingletonSetNearby() { -#if TYPE_OBJECT - assertEquals(null, navigableSet.lower(e0())); - assertEquals(a, navigableSet.floor(e0())); - assertEquals(a, navigableSet.ceiling(e0())); - assertEquals(null, navigableSet.higher(e0())); -#else - assertEquals(navigableSet.getDefaultMinValue(), navigableSet.lower(e0())); - assertEquals(a, navigableSet.floor(e0())); - assertEquals(a, navigableSet.ceiling(e0())); - assertEquals(navigableSet.getDefaultMaxValue(), navigableSet.higher(e0())); -#endif - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ONE) -#endignore - public void testSingletonSetPollLast() { - assertEquals(a, navigableSet.POLL_LAST_KEY()); - assertTrue(navigableSet.isEmpty()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testPollFirst() { - assertEquals(a, navigableSet.POLL_FIRST_KEY()); - assertEquals(values.subList(1, values.size()), HELPERS.copyToList(navigableSet)); - } - -#ignore - @CollectionFeature.Require(absent = SUPPORTS_REMOVE) -#endignore - public void testPollFirstUnsupported() { - try { - navigableSet.POLL_FIRST_KEY(); - fail(); - } catch (UnsupportedOperationException e) { - } - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testLowerHole() { - resetWithHole(); -#if TYPE_OBJECT - assertEquals(null, navigableSet.lower(a)); -#else - assertEquals(navigableSet.getDefaultMinValue(), navigableSet.lower(a)); -#endif - assertEquals(a, navigableSet.lower(b)); - assertEquals(a, navigableSet.lower(c)); - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testFloorHole() { - resetWithHole(); - assertEquals(a, navigableSet.floor(a)); - assertEquals(a, navigableSet.floor(b)); - assertEquals(c, navigableSet.floor(c)); - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testCeilingHole() { - resetWithHole(); - assertEquals(a, navigableSet.ceiling(a)); - assertEquals(c, navigableSet.ceiling(b)); - assertEquals(c, navigableSet.ceiling(c)); - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testHigherHole() { - resetWithHole(); - assertEquals(c, navigableSet.higher(a)); - assertEquals(c, navigableSet.higher(b)); -#if TYPE_OBJECT - assertEquals(null, navigableSet.higher(c)); -#else - assertEquals(navigableSet.getDefaultMaxValue(), navigableSet.higher(c)); -#endif - } - - /* - * TODO(cpovirk): make "too small" and "too large" elements available for - * better navigation testing. At that point, we may be able to eliminate the - * "hole" tests, which would mean that ContiguousSet's tests would no longer - * need to suppress them. - */ -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testLower() { -#if TYPE_OBJECT - assertEquals(null, navigableSet.lower(a)); -#else - assertEquals(navigableSet.getDefaultMinValue(), navigableSet.lower(a)); -#endif - assertEquals(a, navigableSet.lower(b)); - assertEquals(b, navigableSet.lower(c)); - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testFloor() { - assertEquals(a, navigableSet.floor(a)); - assertEquals(b, navigableSet.floor(b)); - assertEquals(c, navigableSet.floor(c)); - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testCeiling() { - assertEquals(a, navigableSet.ceiling(a)); - assertEquals(b, navigableSet.ceiling(b)); - assertEquals(c, navigableSet.ceiling(c)); - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testHigher() { - assertEquals(b, navigableSet.higher(a)); - assertEquals(c, navigableSet.higher(b)); -#if TYPE_OBJECT - assertEquals(null, navigableSet.higher(c)); -#else - assertEquals(navigableSet.getDefaultMaxValue(), navigableSet.higher(c)); -#endif - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testPollLast() { - assertEquals(c, navigableSet.POLL_LAST_KEY()); - assertEquals(values.subList(0, values.size() - 1), HELPERS.copyToList(navigableSet)); - } - -#ignore - @CollectionFeature.Require(absent = SUPPORTS_REMOVE) -#endignore - public void testPollLastUnsupported() { - try { - navigableSet.POLL_LAST_KEY(); - fail(); - } catch (UnsupportedOperationException e) { - } - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testDescendingNavigation() { - LIST KEY_GENERIC_TYPE descending = new ARRAY_LISTBRACES(); - for (ITERATOR KEY_GENERIC_TYPE i = navigableSet.descendingIterator(); i.hasNext();) { - descending.add(i.NEXT()); - } - LISTS.reverse(descending); - assertEquals(values, descending); - } - - public void testEmptySubSet() { - NAVIGABLE_SET KEY_GENERIC_TYPE empty = navigableSet.subSet(e0(), false, e0(), false); - assertEquals(new TreeSet<>(), empty); - } -} +package speiger.src.testers.PACKAGE.tests.set; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import java.util.TreeSet; + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.collections.ITERATOR; +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET; +import speiger.src.collections.PACKAGE.utils.LISTS; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_SET_TESTER; +import speiger.src.testers.PACKAGE.utils.HELPERS; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPENavigableSetNavigationTester KEY_GENERIC_TYPE extends ABSTRACT_SET_TESTER KEY_GENERIC_TYPE +{ + private NAVIGABLE_SET KEY_GENERIC_TYPE navigableSet; + private LIST KEY_GENERIC_TYPE values; + private KEY_TYPE a; + private KEY_TYPE b; + private KEY_TYPE c; + + @Override + public void setUp() throws Exception { + super.setUp(); + navigableSet = (NAVIGABLE_SET KEY_GENERIC_TYPE) getSet(); + values = HELPERS.copyToList(getSampleElements(getSubjectGenerator().getCollectionSize().getNumElements())); + values.sort(navigableSet.comparator()); + if (values.size() >= 1) { + a = values.GET_KEY(0); + if (values.size() >= 3) { + b = values.GET_KEY(1); + c = values.GET_KEY(2); + } + } + } + + protected void resetWithHole() { + super.resetContainer(primitiveGenerator.create(createArray(a, c))); + navigableSet = (NAVIGABLE_SET KEY_GENERIC_TYPE) getSet(); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ZERO) +#endignore + public void testEmptySetPollFirst() { +#if TYPE_OBJECT + assertEquals(null, navigableSet.POLL_FIRST_KEY()); +#else + assertEquals(navigableSet.getDefaultMinValue(), navigableSet.POLL_FIRST_KEY()); +#endif + } + +#ignore + @CollectionSize.Require(ZERO) +#endignore + public void testEmptySetNearby() { +#if TYPE_OBJECT + assertEquals(null, navigableSet.lower(e0())); + assertEquals(null, navigableSet.floor(e0())); + assertEquals(null, navigableSet.ceiling(e0())); + assertEquals(null, navigableSet.higher(e0())); +#else + assertEquals(navigableSet.getDefaultMinValue(), navigableSet.lower(e0())); + assertEquals(navigableSet.getDefaultMinValue(), navigableSet.floor(e0())); + assertEquals(navigableSet.getDefaultMaxValue(), navigableSet.ceiling(e0())); + assertEquals(navigableSet.getDefaultMaxValue(), navigableSet.higher(e0())); +#endif + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ZERO) +#endignore + public void testEmptySetPollLast() { +#if TYPE_OBJECT + assertEquals(null, navigableSet.POLL_LAST_KEY()); +#else + assertEquals(navigableSet.getDefaultMaxValue(), navigableSet.POLL_LAST_KEY()); +#endif + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ONE) +#endignore + public void testSingletonSetPollFirst() { + assertEquals(a, navigableSet.POLL_FIRST_KEY()); + assertTrue(navigableSet.isEmpty()); + } + +#ignore + @CollectionSize.Require(ONE) +#endignore + public void testSingletonSetNearby() { +#if TYPE_OBJECT + assertEquals(null, navigableSet.lower(e0())); + assertEquals(a, navigableSet.floor(e0())); + assertEquals(a, navigableSet.ceiling(e0())); + assertEquals(null, navigableSet.higher(e0())); +#else + assertEquals(navigableSet.getDefaultMinValue(), navigableSet.lower(e0())); + assertEquals(a, navigableSet.floor(e0())); + assertEquals(a, navigableSet.ceiling(e0())); + assertEquals(navigableSet.getDefaultMaxValue(), navigableSet.higher(e0())); +#endif + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ONE) +#endignore + public void testSingletonSetPollLast() { + assertEquals(a, navigableSet.POLL_LAST_KEY()); + assertTrue(navigableSet.isEmpty()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testPollFirst() { + assertEquals(a, navigableSet.POLL_FIRST_KEY()); + assertEquals(values.subList(1, values.size()), HELPERS.copyToList(navigableSet)); + } + +#ignore + @CollectionFeature.Require(absent = SUPPORTS_REMOVE) +#endignore + public void testPollFirstUnsupported() { + try { + navigableSet.POLL_FIRST_KEY(); + fail(); + } catch (UnsupportedOperationException e) { + } + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testLowerHole() { + resetWithHole(); +#if TYPE_OBJECT + assertEquals(null, navigableSet.lower(a)); +#else + assertEquals(navigableSet.getDefaultMinValue(), navigableSet.lower(a)); +#endif + assertEquals(a, navigableSet.lower(b)); + assertEquals(a, navigableSet.lower(c)); + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testFloorHole() { + resetWithHole(); + assertEquals(a, navigableSet.floor(a)); + assertEquals(a, navigableSet.floor(b)); + assertEquals(c, navigableSet.floor(c)); + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testCeilingHole() { + resetWithHole(); + assertEquals(a, navigableSet.ceiling(a)); + assertEquals(c, navigableSet.ceiling(b)); + assertEquals(c, navigableSet.ceiling(c)); + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testHigherHole() { + resetWithHole(); + assertEquals(c, navigableSet.higher(a)); + assertEquals(c, navigableSet.higher(b)); +#if TYPE_OBJECT + assertEquals(null, navigableSet.higher(c)); +#else + assertEquals(navigableSet.getDefaultMaxValue(), navigableSet.higher(c)); +#endif + } + + /* + * TODO(cpovirk): make "too small" and "too large" elements available for + * better navigation testing. At that point, we may be able to eliminate the + * "hole" tests, which would mean that ContiguousSet's tests would no longer + * need to suppress them. + */ +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testLower() { +#if TYPE_OBJECT + assertEquals(null, navigableSet.lower(a)); +#else + assertEquals(navigableSet.getDefaultMinValue(), navigableSet.lower(a)); +#endif + assertEquals(a, navigableSet.lower(b)); + assertEquals(b, navigableSet.lower(c)); + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testFloor() { + assertEquals(a, navigableSet.floor(a)); + assertEquals(b, navigableSet.floor(b)); + assertEquals(c, navigableSet.floor(c)); + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testCeiling() { + assertEquals(a, navigableSet.ceiling(a)); + assertEquals(b, navigableSet.ceiling(b)); + assertEquals(c, navigableSet.ceiling(c)); + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testHigher() { + assertEquals(b, navigableSet.higher(a)); + assertEquals(c, navigableSet.higher(b)); +#if TYPE_OBJECT + assertEquals(null, navigableSet.higher(c)); +#else + assertEquals(navigableSet.getDefaultMaxValue(), navigableSet.higher(c)); +#endif + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testPollLast() { + assertEquals(c, navigableSet.POLL_LAST_KEY()); + assertEquals(values.subList(0, values.size() - 1), HELPERS.copyToList(navigableSet)); + } + +#ignore + @CollectionFeature.Require(absent = SUPPORTS_REMOVE) +#endignore + public void testPollLastUnsupported() { + try { + navigableSet.POLL_LAST_KEY(); + fail(); + } catch (UnsupportedOperationException e) { + } + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testDescendingNavigation() { + LIST KEY_GENERIC_TYPE descending = new ARRAY_LISTBRACES(); + for (ITERATOR KEY_GENERIC_TYPE i = navigableSet.descendingIterator(); i.hasNext();) { + descending.add(i.NEXT()); + } + LISTS.reverse(descending); + assertEquals(values, descending); + } + + public void testEmptySubSet() { + NAVIGABLE_SET KEY_GENERIC_TYPE empty = navigableSet.subSet(e0(), false, e0(), false); + assertEquals(new TreeSet<>(), empty); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/set/OrderedSetIterationTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/set/OrderedSetIterationTester.template index 533b3dc..137741f 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/set/OrderedSetIterationTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/set/OrderedSetIterationTester.template @@ -1,56 +1,56 @@ -package speiger.src.testers.PACKAGE.tests.set; - -import java.util.NoSuchElementException; - -import org.junit.Assert; -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.sets.ORDERED_SET; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_SET_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEOrderedSetIterationTester KEY_GENERIC_TYPE extends ABSTRACT_SET_TESTER KEY_GENERIC_TYPE -{ - private ORDERED_SET KEY_GENERIC_TYPE orderedSet; - - @Override - public void setUp() throws Exception { - super.setUp(); - orderedSet = (ORDERED_SET KEY_GENERIC_TYPE) getSet(); - } - -#ignore - @CollectionSize.Require(absent = CollectionSize.ZERO) -#endignore - public void testMissingIterator() { - try { - orderedSet.iterator(e3()); - fail("Iterator with missing Element should throw NoSuchElementException"); - } - catch(NoSuchElementException e) {} - } - -#ignore - @CollectionSize.Require(absent = CollectionSize.ZERO) -#endignore - public void testFirstElement() { - Assert.assertTrue(orderedSet.iterator(e0()) != null); - } - -#ignore - @CollectionSize.Require(CollectionSize.SEVERAL) -#endignore - public void testLastElement() { - Assert.assertTrue(orderedSet.iterator(e2()) != null); - } - -#ignore - @CollectionSize.Require(CollectionSize.SEVERAL) -#endignore - public void testCenterElement() { - Assert.assertTrue(orderedSet.iterator(e1()) != null); - } +package speiger.src.testers.PACKAGE.tests.set; + +import java.util.NoSuchElementException; + +import org.junit.Assert; +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.sets.ORDERED_SET; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_SET_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEOrderedSetIterationTester KEY_GENERIC_TYPE extends ABSTRACT_SET_TESTER KEY_GENERIC_TYPE +{ + private ORDERED_SET KEY_GENERIC_TYPE orderedSet; + + @Override + public void setUp() throws Exception { + super.setUp(); + orderedSet = (ORDERED_SET KEY_GENERIC_TYPE) getSet(); + } + +#ignore + @CollectionSize.Require(absent = CollectionSize.ZERO) +#endignore + public void testMissingIterator() { + try { + orderedSet.iterator(e3()); + fail("Iterator with missing Element should throw NoSuchElementException"); + } + catch(NoSuchElementException e) {} + } + +#ignore + @CollectionSize.Require(absent = CollectionSize.ZERO) +#endignore + public void testFirstElement() { + Assert.assertTrue(orderedSet.iterator(e0()) != null); + } + +#ignore + @CollectionSize.Require(CollectionSize.SEVERAL) +#endignore + public void testLastElement() { + Assert.assertTrue(orderedSet.iterator(e2()) != null); + } + +#ignore + @CollectionSize.Require(CollectionSize.SEVERAL) +#endignore + public void testCenterElement() { + Assert.assertTrue(orderedSet.iterator(e1()) != null); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/set/OrderedSetMoveTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/set/OrderedSetMoveTester.template index b45cd1d..55f70f6 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/set/OrderedSetMoveTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/set/OrderedSetMoveTester.template @@ -1,271 +1,271 @@ -package speiger.src.testers.PACKAGE.tests.set; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; -import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; -import static org.junit.Assert.assertNotEquals; -#endignore - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.collections.PACKAGE.sets.ORDERED_SET; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_SET_TESTER; -import speiger.src.testers.PACKAGE.utils.HELPERS; -import speiger.src.testers.utils.SpecialFeature; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEOrderedSetMoveTester KEY_GENERIC_TYPE extends ABSTRACT_SET_TESTER KEY_GENERIC_TYPE -{ - private ORDERED_SET KEY_GENERIC_TYPE orderedSet; - private LIST KEY_GENERIC_TYPE values; - private KEY_TYPE a; - private KEY_TYPE c; - - @Override - public void setUp() throws Exception { - super.setUp(); - orderedSet = (ORDERED_SET KEY_GENERIC_TYPE) getSet(); - values = HELPERS.copyToList(getSampleElements(getSubjectGenerator().getCollectionSize().getNumElements())); - if (values.size() >= 1) { - a = values.GET_KEY(0); - if (values.size() >= 3) { - c = values.GET_KEY(2); - } - } - } - -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) - @CollectionSize.Require(SEVERAL) -#endignore - public void testaddMoveToFirstMissing() - { - assertEquals(a, orderedSet.FIRST_KEY()); - assertEquals(true, orderedSet.addAndMoveToFirst(e4())); - assertNotEquals(a, orderedSet.FIRST_KEY()); - assertEquals(e4(), orderedSet.FIRST_KEY()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) - @CollectionSize.Require(SEVERAL) -#endignore - public void testaddMoveToFirstPreset() - { - assertEquals(a, orderedSet.FIRST_KEY()); - assertEquals(false, orderedSet.addAndMoveToFirst(c)); - assertNotEquals(a, orderedSet.FIRST_KEY()); - assertEquals(c, orderedSet.FIRST_KEY()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) - @CollectionSize.Require(SEVERAL) -#endignore - public void testaddMoveToLastMissing() - { - assertEquals(c, orderedSet.LAST_KEY()); - assertEquals(true, orderedSet.addAndMoveToLast(e4())); - assertNotEquals(c, orderedSet.LAST_KEY()); - assertEquals(e4(), orderedSet.LAST_KEY()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) - @CollectionSize.Require(SEVERAL) -#endignore - public void testaddMoveToLastPreset() - { - assertEquals(c, orderedSet.LAST_KEY()); - assertEquals(false, orderedSet.addAndMoveToLast(a)); - assertNotEquals(c, orderedSet.LAST_KEY()); - assertEquals(a, orderedSet.LAST_KEY()); - } - -#ignore - @SpecialFeature.Require(SpecialFeature.MODIFIABLE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testMoveToFirstMissing() - { - assertEquals(a, orderedSet.FIRST_KEY()); - assertEquals(false, orderedSet.moveToFirst(e4())); - assertEquals(a, orderedSet.FIRST_KEY()); - } - -#ignore - @SpecialFeature.Require(SpecialFeature.MODIFIABLE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testMoveToFirstPreset() - { - assertEquals(a, orderedSet.FIRST_KEY()); - assertEquals(true, orderedSet.moveToFirst(c)); - assertNotEquals(a, orderedSet.FIRST_KEY()); - assertEquals(c, orderedSet.FIRST_KEY()); - } - -#ignore - @SpecialFeature.Require(SpecialFeature.MODIFIABLE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testMoveToLastMissing() - { - assertEquals(c, orderedSet.LAST_KEY()); - assertEquals(false, orderedSet.moveToLast(e4())); - assertEquals(c, orderedSet.LAST_KEY()); - } - -#ignore - @SpecialFeature.Require(SpecialFeature.MODIFIABLE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testMoveToLastPreset() - { - assertEquals(c, orderedSet.LAST_KEY()); - assertEquals(true, orderedSet.moveToLast(a)); - assertNotEquals(c, orderedSet.LAST_KEY()); - assertEquals(a, orderedSet.LAST_KEY()); - } - -#ignore - @SpecialFeature.Require(SpecialFeature.MODIFIABLE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testMoveCenterToLast() - { - assertEquals(c, orderedSet.LAST_KEY()); - assertTrue(orderedSet.moveToLast(e1())); - assertNotEquals(c, orderedSet.LAST_KEY()); - assertEquals(e1(), orderedSet.LAST_KEY()); - } - -#ignore - @SpecialFeature.Require(SpecialFeature.MODIFIABLE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testMoveCenterToFirst() - { - assertEquals(a, orderedSet.FIRST_KEY()); - assertTrue(orderedSet.moveToFirst(e1())); - assertNotEquals(c, orderedSet.FIRST_KEY()); - assertEquals(e1(), orderedSet.FIRST_KEY()); - } - -#ignore - @SpecialFeature.Require(SpecialFeature.MODIFIABLE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testMoveForthAndBack() - { - assertEquals(c, orderedSet.LAST_KEY()); - assertTrue(orderedSet.moveToLast(e0())); - assertNotEquals(c, orderedSet.LAST_KEY()); - assertEquals(a, orderedSet.LAST_KEY()); - assertNotEquals(a, orderedSet.FIRST_KEY()); - assertTrue(orderedSet.moveToFirst(e0())); - assertEquals(a, orderedSet.FIRST_KEY()); - } - -#ignore - @SpecialFeature.Require(SpecialFeature.MODIFIABLE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testMoveBackAndForth() - { - assertEquals(a, orderedSet.FIRST_KEY()); - assertTrue(orderedSet.moveToFirst(e2())); - assertNotEquals(a, orderedSet.FIRST_KEY()); - assertEquals(c, orderedSet.FIRST_KEY()); - assertNotEquals(c, orderedSet.LAST_KEY()); - assertTrue(orderedSet.moveToLast(e2())); - assertEquals(c, orderedSet.LAST_KEY()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) - @CollectionSize.Require(SEVERAL) -#endignore - public void testAddForthAndBack() - { - assertEquals(c, orderedSet.LAST_KEY()); - assertFalse(orderedSet.addAndMoveToLast(e0())); - assertNotEquals(c, orderedSet.LAST_KEY()); - assertEquals(a, orderedSet.LAST_KEY()); - assertNotEquals(a, orderedSet.FIRST_KEY()); - assertFalse(orderedSet.addAndMoveToFirst(e0())); - assertEquals(a, orderedSet.FIRST_KEY()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) - @CollectionSize.Require(SEVERAL) -#endignore - public void testAddBackAndForth() - { - assertEquals(a, orderedSet.FIRST_KEY()); - assertFalse(orderedSet.addAndMoveToFirst(e2())); - assertNotEquals(a, orderedSet.FIRST_KEY()); - assertEquals(c, orderedSet.FIRST_KEY()); - assertNotEquals(c, orderedSet.LAST_KEY()); - assertFalse(orderedSet.addAndMoveToLast(e2())); - assertEquals(c, orderedSet.LAST_KEY()); - } - -#ignore - @CollectionFeature.Require(absent = SUPPORTS_ADD) -#endignore - public void testaddMoveToFirstUnsupported() - { - try { - orderedSet.addAndMoveToFirst(e4()); - fail("addAndMoveToFirst should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException e) { - } - expectUnchanged(); - } - -#ignore - @CollectionFeature.Require(absent = SUPPORTS_ADD) -#endignore - public void testaddMoveToLastUnsupported() - { - try { - orderedSet.addAndMoveToLast(e4()); - fail("addAndMoveToLast should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException e) { - } - expectUnchanged(); - } - -#ignore - @SpecialFeature.Require(absent = SpecialFeature.MODIFIABLE) -#endignore - public void testmoveToFirstUnsupported() - { - try { - orderedSet.moveToFirst(c); - fail("moveToFirst should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException e) { - } - expectUnchanged(); - } - -#ignore - @SpecialFeature.Require(absent = SpecialFeature.MODIFIABLE) -#endignore - public void testmoveToLastUnsupported() - { - try { - orderedSet.moveToLast(a); - fail("moveToLast should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException e) { - } - expectUnchanged(); - } -} +package speiger.src.testers.PACKAGE.tests.set; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; +import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; +import static org.junit.Assert.assertNotEquals; +#endignore + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.collections.PACKAGE.sets.ORDERED_SET; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_SET_TESTER; +import speiger.src.testers.PACKAGE.utils.HELPERS; +import speiger.src.testers.utils.SpecialFeature; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEOrderedSetMoveTester KEY_GENERIC_TYPE extends ABSTRACT_SET_TESTER KEY_GENERIC_TYPE +{ + private ORDERED_SET KEY_GENERIC_TYPE orderedSet; + private LIST KEY_GENERIC_TYPE values; + private KEY_TYPE a; + private KEY_TYPE c; + + @Override + public void setUp() throws Exception { + super.setUp(); + orderedSet = (ORDERED_SET KEY_GENERIC_TYPE) getSet(); + values = HELPERS.copyToList(getSampleElements(getSubjectGenerator().getCollectionSize().getNumElements())); + if (values.size() >= 1) { + a = values.GET_KEY(0); + if (values.size() >= 3) { + c = values.GET_KEY(2); + } + } + } + +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) + @CollectionSize.Require(SEVERAL) +#endignore + public void testaddMoveToFirstMissing() + { + assertEquals(a, orderedSet.FIRST_KEY()); + assertEquals(true, orderedSet.addAndMoveToFirst(e4())); + assertNotEquals(a, orderedSet.FIRST_KEY()); + assertEquals(e4(), orderedSet.FIRST_KEY()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) + @CollectionSize.Require(SEVERAL) +#endignore + public void testaddMoveToFirstPreset() + { + assertEquals(a, orderedSet.FIRST_KEY()); + assertEquals(false, orderedSet.addAndMoveToFirst(c)); + assertNotEquals(a, orderedSet.FIRST_KEY()); + assertEquals(c, orderedSet.FIRST_KEY()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) + @CollectionSize.Require(SEVERAL) +#endignore + public void testaddMoveToLastMissing() + { + assertEquals(c, orderedSet.LAST_KEY()); + assertEquals(true, orderedSet.addAndMoveToLast(e4())); + assertNotEquals(c, orderedSet.LAST_KEY()); + assertEquals(e4(), orderedSet.LAST_KEY()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) + @CollectionSize.Require(SEVERAL) +#endignore + public void testaddMoveToLastPreset() + { + assertEquals(c, orderedSet.LAST_KEY()); + assertEquals(false, orderedSet.addAndMoveToLast(a)); + assertNotEquals(c, orderedSet.LAST_KEY()); + assertEquals(a, orderedSet.LAST_KEY()); + } + +#ignore + @SpecialFeature.Require(SpecialFeature.MODIFIABLE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testMoveToFirstMissing() + { + assertEquals(a, orderedSet.FIRST_KEY()); + assertEquals(false, orderedSet.moveToFirst(e4())); + assertEquals(a, orderedSet.FIRST_KEY()); + } + +#ignore + @SpecialFeature.Require(SpecialFeature.MODIFIABLE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testMoveToFirstPreset() + { + assertEquals(a, orderedSet.FIRST_KEY()); + assertEquals(true, orderedSet.moveToFirst(c)); + assertNotEquals(a, orderedSet.FIRST_KEY()); + assertEquals(c, orderedSet.FIRST_KEY()); + } + +#ignore + @SpecialFeature.Require(SpecialFeature.MODIFIABLE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testMoveToLastMissing() + { + assertEquals(c, orderedSet.LAST_KEY()); + assertEquals(false, orderedSet.moveToLast(e4())); + assertEquals(c, orderedSet.LAST_KEY()); + } + +#ignore + @SpecialFeature.Require(SpecialFeature.MODIFIABLE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testMoveToLastPreset() + { + assertEquals(c, orderedSet.LAST_KEY()); + assertEquals(true, orderedSet.moveToLast(a)); + assertNotEquals(c, orderedSet.LAST_KEY()); + assertEquals(a, orderedSet.LAST_KEY()); + } + +#ignore + @SpecialFeature.Require(SpecialFeature.MODIFIABLE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testMoveCenterToLast() + { + assertEquals(c, orderedSet.LAST_KEY()); + assertTrue(orderedSet.moveToLast(e1())); + assertNotEquals(c, orderedSet.LAST_KEY()); + assertEquals(e1(), orderedSet.LAST_KEY()); + } + +#ignore + @SpecialFeature.Require(SpecialFeature.MODIFIABLE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testMoveCenterToFirst() + { + assertEquals(a, orderedSet.FIRST_KEY()); + assertTrue(orderedSet.moveToFirst(e1())); + assertNotEquals(c, orderedSet.FIRST_KEY()); + assertEquals(e1(), orderedSet.FIRST_KEY()); + } + +#ignore + @SpecialFeature.Require(SpecialFeature.MODIFIABLE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testMoveForthAndBack() + { + assertEquals(c, orderedSet.LAST_KEY()); + assertTrue(orderedSet.moveToLast(e0())); + assertNotEquals(c, orderedSet.LAST_KEY()); + assertEquals(a, orderedSet.LAST_KEY()); + assertNotEquals(a, orderedSet.FIRST_KEY()); + assertTrue(orderedSet.moveToFirst(e0())); + assertEquals(a, orderedSet.FIRST_KEY()); + } + +#ignore + @SpecialFeature.Require(SpecialFeature.MODIFIABLE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testMoveBackAndForth() + { + assertEquals(a, orderedSet.FIRST_KEY()); + assertTrue(orderedSet.moveToFirst(e2())); + assertNotEquals(a, orderedSet.FIRST_KEY()); + assertEquals(c, orderedSet.FIRST_KEY()); + assertNotEquals(c, orderedSet.LAST_KEY()); + assertTrue(orderedSet.moveToLast(e2())); + assertEquals(c, orderedSet.LAST_KEY()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) + @CollectionSize.Require(SEVERAL) +#endignore + public void testAddForthAndBack() + { + assertEquals(c, orderedSet.LAST_KEY()); + assertFalse(orderedSet.addAndMoveToLast(e0())); + assertNotEquals(c, orderedSet.LAST_KEY()); + assertEquals(a, orderedSet.LAST_KEY()); + assertNotEquals(a, orderedSet.FIRST_KEY()); + assertFalse(orderedSet.addAndMoveToFirst(e0())); + assertEquals(a, orderedSet.FIRST_KEY()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) + @CollectionSize.Require(SEVERAL) +#endignore + public void testAddBackAndForth() + { + assertEquals(a, orderedSet.FIRST_KEY()); + assertFalse(orderedSet.addAndMoveToFirst(e2())); + assertNotEquals(a, orderedSet.FIRST_KEY()); + assertEquals(c, orderedSet.FIRST_KEY()); + assertNotEquals(c, orderedSet.LAST_KEY()); + assertFalse(orderedSet.addAndMoveToLast(e2())); + assertEquals(c, orderedSet.LAST_KEY()); + } + +#ignore + @CollectionFeature.Require(absent = SUPPORTS_ADD) +#endignore + public void testaddMoveToFirstUnsupported() + { + try { + orderedSet.addAndMoveToFirst(e4()); + fail("addAndMoveToFirst should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + } + expectUnchanged(); + } + +#ignore + @CollectionFeature.Require(absent = SUPPORTS_ADD) +#endignore + public void testaddMoveToLastUnsupported() + { + try { + orderedSet.addAndMoveToLast(e4()); + fail("addAndMoveToLast should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + } + expectUnchanged(); + } + +#ignore + @SpecialFeature.Require(absent = SpecialFeature.MODIFIABLE) +#endignore + public void testmoveToFirstUnsupported() + { + try { + orderedSet.moveToFirst(c); + fail("moveToFirst should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + } + expectUnchanged(); + } + +#ignore + @SpecialFeature.Require(absent = SpecialFeature.MODIFIABLE) +#endignore + public void testmoveToLastUnsupported() + { + try { + orderedSet.moveToLast(a); + fail("moveToLast should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + } + expectUnchanged(); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/set/OrderedSetNavigationTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/set/OrderedSetNavigationTester.template index dc7935d..5b38428 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/set/OrderedSetNavigationTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/set/OrderedSetNavigationTester.template @@ -1,248 +1,248 @@ -package speiger.src.testers.PACKAGE.tests.set; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import java.util.NoSuchElementException; - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.collections.PACKAGE.sets.ORDERED_SET; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_SET_TESTER; -import speiger.src.testers.PACKAGE.utils.HELPERS; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPEOrderedSetNavigationTester KEY_GENERIC_TYPE extends ABSTRACT_SET_TESTER KEY_GENERIC_TYPE -{ - private ORDERED_SET KEY_GENERIC_TYPE orderedSet; - private LIST KEY_GENERIC_TYPE values; - private KEY_TYPE a; - private KEY_TYPE c; - - @Override - public void setUp() throws Exception { - super.setUp(); - orderedSet = (ORDERED_SET KEY_GENERIC_TYPE) getSet(); - values = HELPERS.copyToList(getSampleElements(getSubjectGenerator().getCollectionSize().getNumElements())); - if (values.size() >= 1) { - a = values.GET_KEY(0); - if (values.size() >= 3) { - c = values.GET_KEY(2); - } - } - } - -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) - @CollectionSize.Require(ZERO) -#endignore - public void testAddEmptySetToFirst() { - orderedSet.addAndMoveToFirst(e0()); - expectAdded(e0()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) - @CollectionSize.Require(ZERO) -#endignore - public void testAddEmptySetToLast() { - orderedSet.addAndMoveToLast(e0()); - expectAdded(e0()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testyMapPollFirstEmpty() { - int polled = 0; - int expectedPolls = orderedSet.size(); - while(polled < expectedPolls) { - orderedSet.POLL_FIRST_KEY(); - polled++; - } - assertTrue("Map should be empty", orderedSet.isEmpty()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testyMapPollLastEmpty() { - int polled = 0; - int expectedPolls = orderedSet.size(); - while(polled < expectedPolls) { - orderedSet.POLL_LAST_KEY(); - polled++; - } - assertTrue("Map should be empty", orderedSet.isEmpty()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ZERO) -#endignore - public void testEmptySetPollFirst() { - try { - orderedSet.POLL_FIRST_KEY(); - fail("OrderedSet.POLL_FIRST_KEY should throw NoSuchElementException"); - } catch (NoSuchElementException e) { - } - expectUnchanged(); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ZERO) -#endignore - public void testEmptySetPollLast() { - try { - orderedSet.POLL_LAST_KEY(); - fail("OrderedSet.POLL_LAST_KEY should throw NoSuchElementException"); - } catch (NoSuchElementException e) { - } - expectUnchanged(); - } - -#ignore - @CollectionFeature.Require(absent = SUPPORTS_REMOVE) -#endignore - public void testUnsupportedSetPollFirst() { - try { - orderedSet.POLL_FIRST_KEY(); - fail("OrderedSet.POLL_FIRST_KEY should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException e) { - } - expectUnchanged(); - } - -#ignore - @CollectionFeature.Require(absent = SUPPORTS_REMOVE) -#endignore - public void testUnsupportedSetPollLast() { - try { - orderedSet.POLL_LAST_KEY(); - fail("OrderedSet.POLL_LAST_KEY should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException e) { - } - expectUnchanged(); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ONE) -#endignore - public void testSingletonSetPollFirst() { - assertEquals(a, orderedSet.POLL_FIRST_KEY()); - assertTrue(orderedSet.isEmpty()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ONE) -#endignore - public void testSingletonSetPollLast() { - assertEquals(a, orderedSet.POLL_LAST_KEY()); - assertTrue(orderedSet.isEmpty()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testPollFirst() { - assertEquals(a, orderedSet.POLL_FIRST_KEY()); - assertEquals(values.subList(1, values.size()), HELPERS.copyToList(orderedSet)); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testPollLast() { - assertEquals(c, orderedSet.POLL_LAST_KEY()); - assertEquals(values.subList(0, values.size()-1), HELPERS.copyToList(orderedSet)); - } - -#ignore - @CollectionFeature.Require(absent = SUPPORTS_REMOVE) -#endignore - public void testPollFirstUnsupported() { - try { - orderedSet.POLL_FIRST_KEY(); - fail(); - } catch (UnsupportedOperationException e) { - } - } - -#ignore - @CollectionFeature.Require(absent = SUPPORTS_REMOVE) -#endignore - public void testPollLastUnsupported() { - try { - orderedSet.POLL_LAST_KEY(); - fail(); - } catch (UnsupportedOperationException e) { - } - } - -#ignore - @CollectionSize.Require(ZERO) -#endignore - public void testEmptySetFirst() { - try { - orderedSet.FIRST_KEY(); - fail(); - } catch (NoSuchElementException e) { - } - } - -#ignore - @CollectionSize.Require(ZERO) -#endignore - public void testEmptySetLast() { - try { - orderedSet.LAST_KEY(); - fail(); - } catch (NoSuchElementException e) { - } - } - -#ignore - @CollectionSize.Require(ONE) -#endignore - public void testSingletonSetFirst() { - assertEquals(a, orderedSet.FIRST_KEY()); - } - -#ignore - @CollectionSize.Require(ONE) -#endignore - public void testSingletonSetLast() { - assertEquals(a, orderedSet.LAST_KEY()); - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testFirst() { - assertEquals(a, orderedSet.FIRST_KEY()); - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testLast() { - assertEquals(c, orderedSet.LAST_KEY()); - } +package speiger.src.testers.PACKAGE.tests.set; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import java.util.NoSuchElementException; + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.collections.PACKAGE.sets.ORDERED_SET; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_SET_TESTER; +import speiger.src.testers.PACKAGE.utils.HELPERS; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPEOrderedSetNavigationTester KEY_GENERIC_TYPE extends ABSTRACT_SET_TESTER KEY_GENERIC_TYPE +{ + private ORDERED_SET KEY_GENERIC_TYPE orderedSet; + private LIST KEY_GENERIC_TYPE values; + private KEY_TYPE a; + private KEY_TYPE c; + + @Override + public void setUp() throws Exception { + super.setUp(); + orderedSet = (ORDERED_SET KEY_GENERIC_TYPE) getSet(); + values = HELPERS.copyToList(getSampleElements(getSubjectGenerator().getCollectionSize().getNumElements())); + if (values.size() >= 1) { + a = values.GET_KEY(0); + if (values.size() >= 3) { + c = values.GET_KEY(2); + } + } + } + +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) + @CollectionSize.Require(ZERO) +#endignore + public void testAddEmptySetToFirst() { + orderedSet.addAndMoveToFirst(e0()); + expectAdded(e0()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) + @CollectionSize.Require(ZERO) +#endignore + public void testAddEmptySetToLast() { + orderedSet.addAndMoveToLast(e0()); + expectAdded(e0()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testyMapPollFirstEmpty() { + int polled = 0; + int expectedPolls = orderedSet.size(); + while(polled < expectedPolls) { + orderedSet.POLL_FIRST_KEY(); + polled++; + } + assertTrue("Map should be empty", orderedSet.isEmpty()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testyMapPollLastEmpty() { + int polled = 0; + int expectedPolls = orderedSet.size(); + while(polled < expectedPolls) { + orderedSet.POLL_LAST_KEY(); + polled++; + } + assertTrue("Map should be empty", orderedSet.isEmpty()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ZERO) +#endignore + public void testEmptySetPollFirst() { + try { + orderedSet.POLL_FIRST_KEY(); + fail("OrderedSet.POLL_FIRST_KEY should throw NoSuchElementException"); + } catch (NoSuchElementException e) { + } + expectUnchanged(); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ZERO) +#endignore + public void testEmptySetPollLast() { + try { + orderedSet.POLL_LAST_KEY(); + fail("OrderedSet.POLL_LAST_KEY should throw NoSuchElementException"); + } catch (NoSuchElementException e) { + } + expectUnchanged(); + } + +#ignore + @CollectionFeature.Require(absent = SUPPORTS_REMOVE) +#endignore + public void testUnsupportedSetPollFirst() { + try { + orderedSet.POLL_FIRST_KEY(); + fail("OrderedSet.POLL_FIRST_KEY should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + } + expectUnchanged(); + } + +#ignore + @CollectionFeature.Require(absent = SUPPORTS_REMOVE) +#endignore + public void testUnsupportedSetPollLast() { + try { + orderedSet.POLL_LAST_KEY(); + fail("OrderedSet.POLL_LAST_KEY should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + } + expectUnchanged(); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ONE) +#endignore + public void testSingletonSetPollFirst() { + assertEquals(a, orderedSet.POLL_FIRST_KEY()); + assertTrue(orderedSet.isEmpty()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ONE) +#endignore + public void testSingletonSetPollLast() { + assertEquals(a, orderedSet.POLL_LAST_KEY()); + assertTrue(orderedSet.isEmpty()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testPollFirst() { + assertEquals(a, orderedSet.POLL_FIRST_KEY()); + assertEquals(values.subList(1, values.size()), HELPERS.copyToList(orderedSet)); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testPollLast() { + assertEquals(c, orderedSet.POLL_LAST_KEY()); + assertEquals(values.subList(0, values.size()-1), HELPERS.copyToList(orderedSet)); + } + +#ignore + @CollectionFeature.Require(absent = SUPPORTS_REMOVE) +#endignore + public void testPollFirstUnsupported() { + try { + orderedSet.POLL_FIRST_KEY(); + fail(); + } catch (UnsupportedOperationException e) { + } + } + +#ignore + @CollectionFeature.Require(absent = SUPPORTS_REMOVE) +#endignore + public void testPollLastUnsupported() { + try { + orderedSet.POLL_LAST_KEY(); + fail(); + } catch (UnsupportedOperationException e) { + } + } + +#ignore + @CollectionSize.Require(ZERO) +#endignore + public void testEmptySetFirst() { + try { + orderedSet.FIRST_KEY(); + fail(); + } catch (NoSuchElementException e) { + } + } + +#ignore + @CollectionSize.Require(ZERO) +#endignore + public void testEmptySetLast() { + try { + orderedSet.LAST_KEY(); + fail(); + } catch (NoSuchElementException e) { + } + } + +#ignore + @CollectionSize.Require(ONE) +#endignore + public void testSingletonSetFirst() { + assertEquals(a, orderedSet.FIRST_KEY()); + } + +#ignore + @CollectionSize.Require(ONE) +#endignore + public void testSingletonSetLast() { + assertEquals(a, orderedSet.LAST_KEY()); + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testFirst() { + assertEquals(a, orderedSet.FIRST_KEY()); + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testLast() { + assertEquals(c, orderedSet.LAST_KEY()); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/set/SetAddAllTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/set/SetAddAllTester.template index b53bccb..fbef3cd 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/set/SetAddAllTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/set/SetAddAllTester.template @@ -1,46 +1,46 @@ -package speiger.src.testers.PACKAGE.tests.set; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_SET_TESTER; -import speiger.src.testers.PACKAGE.utils.MINIMAL_COLLECTION; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPESetAddAllTester KEY_GENERIC_TYPE extends ABSTRACT_SET_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddAll_supportedSomePresent() { - assertTrue("add(somePresent) should return true", getSet().addAll(MINIMAL_COLLECTION.of(e3(), e0()))); - expectAdded(e3()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) -#endignore - public void testAddAll_withDuplicates() { - MINIMAL_COLLECTION KEY_GENERIC_TYPE elementsToAdd = MINIMAL_COLLECTION.of(e3(), e4(), e3(), e4()); - assertTrue("add(hasDuplicates) should return true", getSet().addAll(elementsToAdd)); - expectAdded(e3(), e4()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAddAll_supportedAllPresent() { - assertFalse("add(allPresent) should return false", getSet().addAll(MINIMAL_COLLECTION.of(e0()))); - expectUnchanged(); - } -} +package speiger.src.testers.PACKAGE.tests.set; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_SET_TESTER; +import speiger.src.testers.PACKAGE.utils.MINIMAL_COLLECTION; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPESetAddAllTester KEY_GENERIC_TYPE extends ABSTRACT_SET_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddAll_supportedSomePresent() { + assertTrue("add(somePresent) should return true", getSet().addAll(MINIMAL_COLLECTION.of(e3(), e0()))); + expectAdded(e3()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) +#endignore + public void testAddAll_withDuplicates() { + MINIMAL_COLLECTION KEY_GENERIC_TYPE elementsToAdd = MINIMAL_COLLECTION.of(e3(), e4(), e3(), e4()); + assertTrue("add(hasDuplicates) should return true", getSet().addAll(elementsToAdd)); + expectAdded(e3(), e4()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAddAll_supportedAllPresent() { + assertFalse("add(allPresent) should return false", getSet().addAll(MINIMAL_COLLECTION.of(e0()))); + expectUnchanged(); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/set/SetAddTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/set/SetAddTester.template index 557ddb3..a580509 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/set/SetAddTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/set/SetAddTester.template @@ -1,36 +1,36 @@ -package speiger.src.testers.PACKAGE.tests.set; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_SET_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPESetAddTester KEY_GENERIC_TYPE extends ABSTRACT_SET_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testAdd_supportedPresent() { - assertFalse("add(present) should return false", getSet().add(e0())); - expectUnchanged(); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_ADD) - @CollectionSize.Require(ZERO) -#endignore - public void testAdd_supportedMissing() { - assertTrue("add(missing) should return true", getSet().add(e0())); - expectAdded(e0()); - } -} +package speiger.src.testers.PACKAGE.tests.set; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_SET_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPESetAddTester KEY_GENERIC_TYPE extends ABSTRACT_SET_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testAdd_supportedPresent() { + assertFalse("add(present) should return false", getSet().add(e0())); + expectUnchanged(); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_ADD) + @CollectionSize.Require(ZERO) +#endignore + public void testAdd_supportedMissing() { + assertTrue("add(missing) should return true", getSet().add(e0())); + expectAdded(e0()); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/set/SetCreationTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/set/SetCreationTester.template index 7ed995d..3724b52 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/set/SetCreationTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/set/SetCreationTester.template @@ -1,45 +1,45 @@ -package speiger.src.testers.PACKAGE.tests.set; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.REJECTS_DUPLICATES_AT_CREATION; -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_SET_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPESetCreationTester KEY_GENERIC_TYPE extends ABSTRACT_SET_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(absent = REJECTS_DUPLICATES_AT_CREATION) - @CollectionSize.Require(absent = { ZERO, ONE }) -#endignore - public void testCreateWithDuplicates_nonNullDuplicatesNotRejected() { - KEY_TYPE[] array = createSamplesArray(); - array[1] = e0(); - collection = primitiveGenerator.create(array); - expectContents(ARRAY_LIST.wrap(array).subList(1, getNumElements())); - } - -#ignore - @CollectionFeature.Require(REJECTS_DUPLICATES_AT_CREATION) - @CollectionSize.Require(absent = { ZERO, ONE }) -#endignore - public void testCreateWithDuplicates_nonNullDuplicatesRejected() { - KEY_TYPE[] array = createSamplesArray(); - array[1] = e0(); - try { - collection = primitiveGenerator.create(array); - fail("Should reject duplicate non-null elements at creation"); - } catch (IllegalArgumentException expected) { - } - } -} +package speiger.src.testers.PACKAGE.tests.set; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.REJECTS_DUPLICATES_AT_CREATION; +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_SET_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPESetCreationTester KEY_GENERIC_TYPE extends ABSTRACT_SET_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(absent = REJECTS_DUPLICATES_AT_CREATION) + @CollectionSize.Require(absent = { ZERO, ONE }) +#endignore + public void testCreateWithDuplicates_nonNullDuplicatesNotRejected() { + KEY_TYPE[] array = createSamplesArray(); + array[1] = e0(); + collection = primitiveGenerator.create(array); + expectContents(ARRAY_LIST.wrap(array).subList(1, getNumElements())); + } + +#ignore + @CollectionFeature.Require(REJECTS_DUPLICATES_AT_CREATION) + @CollectionSize.Require(absent = { ZERO, ONE }) +#endignore + public void testCreateWithDuplicates_nonNullDuplicatesRejected() { + KEY_TYPE[] array = createSamplesArray(); + array[1] = e0(); + try { + collection = primitiveGenerator.create(array); + fail("Should reject duplicate non-null elements at creation"); + } catch (IllegalArgumentException expected) { + } + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/set/SetEqualsTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/set/SetEqualsTester.template index c197118..39e7c6c 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/set/SetEqualsTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/set/SetEqualsTester.template @@ -1,45 +1,45 @@ -package speiger.src.testers.PACKAGE.tests.set; - -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.collections.COLLECTION; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_SET_TESTER; -import speiger.src.testers.PACKAGE.utils.HELPERS; -import speiger.src.testers.PACKAGE.utils.MINIMAL_SET; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPESetEqualsTester KEY_GENERIC_TYPE extends ABSTRACT_SET_TESTER KEY_GENERIC_TYPE -{ - public void testEquals_otherSetWithSameElements() { - assertTrue("A Set should equal any other Set containing the same elements.", getSet().equals(MINIMAL_SET.of(getSampleElements()))); - } - -#ignore - @CollectionSize.Require(absent = CollectionSize.ZERO) -#endignore - public void testEquals_otherSetWithDifferentElements() { - COLLECTION KEY_GENERIC_TYPE elements = getSampleElements(getNumElements() - 1); - elements.add(e3()); - assertFalse("A Set should not equal another Set containing different elements.", getSet().equals(MINIMAL_SET.of(elements))); - } - -#ignore - @CollectionSize.Require(absent = CollectionSize.ZERO) -#endignore - public void testEquals_smallerSet() { - COLLECTION KEY_GENERIC_TYPE fewerElements = getSampleElements(getNumElements() - 1); - assertFalse("Sets of different sizes should not be equal.", getSet().equals(MINIMAL_SET.of(fewerElements))); - } - - public void testEquals_largerSet() { - COLLECTION KEY_GENERIC_TYPE moreElements = getSampleElements(getNumElements() + 1); - assertFalse("Sets of different sizes should not be equal.", getSet().equals(MINIMAL_SET.of(moreElements))); - } - - public void testEquals_list() { - assertFalse("A List should never equal a Set.", getSet().equals(HELPERS.copyToList(getSet()))); - } -} +package speiger.src.testers.PACKAGE.tests.set; + +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.collections.COLLECTION; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_SET_TESTER; +import speiger.src.testers.PACKAGE.utils.HELPERS; +import speiger.src.testers.PACKAGE.utils.MINIMAL_SET; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPESetEqualsTester KEY_GENERIC_TYPE extends ABSTRACT_SET_TESTER KEY_GENERIC_TYPE +{ + public void testEquals_otherSetWithSameElements() { + assertTrue("A Set should equal any other Set containing the same elements.", getSet().equals(MINIMAL_SET.of(getSampleElements()))); + } + +#ignore + @CollectionSize.Require(absent = CollectionSize.ZERO) +#endignore + public void testEquals_otherSetWithDifferentElements() { + COLLECTION KEY_GENERIC_TYPE elements = getSampleElements(getNumElements() - 1); + elements.add(e3()); + assertFalse("A Set should not equal another Set containing different elements.", getSet().equals(MINIMAL_SET.of(elements))); + } + +#ignore + @CollectionSize.Require(absent = CollectionSize.ZERO) +#endignore + public void testEquals_smallerSet() { + COLLECTION KEY_GENERIC_TYPE fewerElements = getSampleElements(getNumElements() - 1); + assertFalse("Sets of different sizes should not be equal.", getSet().equals(MINIMAL_SET.of(fewerElements))); + } + + public void testEquals_largerSet() { + COLLECTION KEY_GENERIC_TYPE moreElements = getSampleElements(getNumElements() + 1); + assertFalse("Sets of different sizes should not be equal.", getSet().equals(MINIMAL_SET.of(moreElements))); + } + + public void testEquals_list() { + assertFalse("A List should never equal a Set.", getSet().equals(HELPERS.copyToList(getSet()))); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/set/SetRemoveTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/set/SetRemoveTester.template index 84bca9a..18d152f 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/set/SetRemoveTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/set/SetRemoveTester.template @@ -1,54 +1,54 @@ -package speiger.src.testers.PACKAGE.tests.set; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; -#endignore - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_SET_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPESetRemoveTester KEY_GENERIC_TYPE extends ABSTRACT_SET_TESTER KEY_GENERIC_TYPE -{ -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(absent = ZERO) -#endignore - public void testRemove_present() { - getSet().remove(e0()); - assertFalse("After remove(present) a set should not contain the removed element.", getSet().contains(e0())); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) -#endignore - public void testRemove_Missing() { - getSet().remove(e3()); - assertFalse("After remove(present) a set should not contain the removed element.", getSet().contains(e3())); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testRemove_middle() { - getSet().remove(e1()); - assertFalse("After remove(present) a set should not contain the removed element.", getSet().contains(e1())); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testRemove_last() { - getSet().remove(e2()); - assertFalse("After remove(present) a set should not contain the removed element.", getSet().contains(e2())); - } -} +package speiger.src.testers.PACKAGE.tests.set; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; +#endignore + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_SET_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPESetRemoveTester KEY_GENERIC_TYPE extends ABSTRACT_SET_TESTER KEY_GENERIC_TYPE +{ +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(absent = ZERO) +#endignore + public void testRemove_present() { + getSet().remove(e0()); + assertFalse("After remove(present) a set should not contain the removed element.", getSet().contains(e0())); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) +#endignore + public void testRemove_Missing() { + getSet().remove(e3()); + assertFalse("After remove(present) a set should not contain the removed element.", getSet().contains(e3())); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testRemove_middle() { + getSet().remove(e1()); + assertFalse("After remove(present) a set should not contain the removed element.", getSet().contains(e1())); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testRemove_last() { + getSet().remove(e2()); + assertFalse("After remove(present) a set should not contain the removed element.", getSet().contains(e2())); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/set/SortedSetIterationTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/set/SortedSetIterationTester.template index aed6e8f..0b48161 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/set/SortedSetIterationTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/set/SortedSetIterationTester.template @@ -1,43 +1,43 @@ -package speiger.src.testers.PACKAGE.tests.set; - -import org.junit.Assert; -import org.junit.Ignore; - -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.sets.SORTED_SET; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_SET_TESTER; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPESortedSetIterationTester KEY_GENERIC_TYPE extends ABSTRACT_SET_TESTER KEY_GENERIC_TYPE -{ - private SORTED_SET KEY_GENERIC_TYPE sortedSet; - - @Override - public void setUp() throws Exception { - super.setUp(); - sortedSet = (SORTED_SET KEY_GENERIC_TYPE) getSet(); - } - -#ignore - @CollectionSize.Require(absent = CollectionSize.ZERO) -#endignore - public void testFirstElement() { - Assert.assertTrue(sortedSet.iterator(e0()) != null); - } - -#ignore - @CollectionSize.Require(CollectionSize.SEVERAL) -#endignore - public void testLastElement() { - Assert.assertTrue(sortedSet.iterator(e2()) != null); - } - -#ignore - @CollectionSize.Require(CollectionSize.SEVERAL) -#endignore - public void testCenterElement() { - Assert.assertTrue(sortedSet.iterator(e1()) != null); - } +package speiger.src.testers.PACKAGE.tests.set; + +import org.junit.Assert; +import org.junit.Ignore; + +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.sets.SORTED_SET; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_SET_TESTER; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPESortedSetIterationTester KEY_GENERIC_TYPE extends ABSTRACT_SET_TESTER KEY_GENERIC_TYPE +{ + private SORTED_SET KEY_GENERIC_TYPE sortedSet; + + @Override + public void setUp() throws Exception { + super.setUp(); + sortedSet = (SORTED_SET KEY_GENERIC_TYPE) getSet(); + } + +#ignore + @CollectionSize.Require(absent = CollectionSize.ZERO) +#endignore + public void testFirstElement() { + Assert.assertTrue(sortedSet.iterator(e0()) != null); + } + +#ignore + @CollectionSize.Require(CollectionSize.SEVERAL) +#endignore + public void testLastElement() { + Assert.assertTrue(sortedSet.iterator(e2()) != null); + } + +#ignore + @CollectionSize.Require(CollectionSize.SEVERAL) +#endignore + public void testCenterElement() { + Assert.assertTrue(sortedSet.iterator(e1()) != null); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/tests/set/SortedSetNaviationTester.template b/src/builder/resources/speiger/assets/testers/templates/tests/set/SortedSetNaviationTester.template index 111e970..e5322bd 100644 --- a/src/builder/resources/speiger/assets/testers/templates/tests/set/SortedSetNaviationTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/tests/set/SortedSetNaviationTester.template @@ -1,178 +1,178 @@ -package speiger.src.testers.PACKAGE.tests.set; - -import org.junit.Ignore; - -#ignore -import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; -import static com.google.common.collect.testing.features.CollectionSize.ONE; -import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; -import static com.google.common.collect.testing.features.CollectionSize.ZERO; -#endignore - -import java.util.NoSuchElementException; - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.collections.PACKAGE.sets.SORTED_SET; -import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_SET_TESTER; -import speiger.src.testers.PACKAGE.utils.HELPERS; - -@Ignore -@SuppressWarnings("javadoc") -public class FILE_KEY_TYPESortedSetNaviationTester KEY_GENERIC_TYPE extends ABSTRACT_SET_TESTER KEY_GENERIC_TYPE -{ - private SORTED_SET KEY_GENERIC_TYPE sortedSet; - private LIST KEY_GENERIC_TYPE values; - private KEY_TYPE a; - private KEY_TYPE c; - - @Override - public void setUp() throws Exception { - super.setUp(); - sortedSet = (SORTED_SET KEY_GENERIC_TYPE) getSet(); - values = HELPERS.copyToList(getSampleElements(getSubjectGenerator().getCollectionSize().getNumElements())); - values.sort(sortedSet.comparator()); - - // some tests assume SEVERAL == 3 - if (values.size() >= 1) { - a = values.GET_KEY(0); - if (values.size() >= 3) { - c = values.GET_KEY(2); - } - } - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ZERO) -#endignore - public void testEmptySetPollFirst() { -#if TYPE_OBJECT - assertEquals(null, sortedSet.POLL_FIRST_KEY()); -#else - assertEquals(CLASS_TYPE.MAX_VALUE, sortedSet.POLL_FIRST_KEY()); -#endif - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ZERO) -#endignore - public void testEmptySetPollLast() { -#if TYPE_OBJECT - assertEquals(null, sortedSet.POLL_LAST_KEY()); -#else - assertEquals(CLASS_TYPE.MIN_VALUE, sortedSet.POLL_LAST_KEY()); -#endif - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ONE) -#endignore - public void testSingletonSetPollFirst() { - assertEquals(a, sortedSet.POLL_FIRST_KEY()); - assertTrue(sortedSet.isEmpty()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(ONE) -#endignore - public void testSingletonSetPollLast() { - assertEquals(a, sortedSet.POLL_LAST_KEY()); - assertTrue(sortedSet.isEmpty()); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testPollFirst() { - assertEquals(a, sortedSet.POLL_FIRST_KEY()); - assertEquals(values.subList(1, values.size()), HELPERS.copyToList(sortedSet)); - } - -#ignore - @CollectionFeature.Require(SUPPORTS_REMOVE) - @CollectionSize.Require(SEVERAL) -#endignore - public void testPollLast() { - assertEquals(c, sortedSet.POLL_LAST_KEY()); - assertEquals(values.subList(0, values.size()-1), HELPERS.copyToList(sortedSet)); - } - -#ignore - @CollectionFeature.Require(absent = SUPPORTS_REMOVE) -#endignore - public void testPollFirstUnsupported() { - try { - sortedSet.POLL_FIRST_KEY(); - fail(); - } catch (UnsupportedOperationException e) { - } - } - -#ignore - @CollectionFeature.Require(absent = SUPPORTS_REMOVE) -#endignore - public void testPollLastUnsupported() { - try { - sortedSet.POLL_LAST_KEY(); - fail(); - } catch (UnsupportedOperationException e) { - } - } - -#ignore - @CollectionSize.Require(ZERO) -#endignore - public void testEmptySetFirst() { - try { - sortedSet.FIRST_KEY(); - fail(); - } catch (NoSuchElementException e) { - } - } - -#ignore - @CollectionSize.Require(ZERO) -#endignore - public void testEmptySetLast() { - try { - sortedSet.LAST_KEY(); - fail(); - } catch (NoSuchElementException e) { - } - } - -#ignore - @CollectionSize.Require(ONE) -#endignore - public void testSingletonSetFirst() { - assertEquals(a, sortedSet.FIRST_KEY()); - } - -#ignore - @CollectionSize.Require(ONE) -#endignore - public void testSingletonSetLast() { - assertEquals(a, sortedSet.LAST_KEY()); - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testFirst() { - assertEquals(a, sortedSet.FIRST_KEY()); - } - -#ignore - @CollectionSize.Require(SEVERAL) -#endignore - public void testLast() { - assertEquals(c, sortedSet.LAST_KEY()); - } -} +package speiger.src.testers.PACKAGE.tests.set; + +import org.junit.Ignore; + +#ignore +import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; +import static com.google.common.collect.testing.features.CollectionSize.ONE; +import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; +import static com.google.common.collect.testing.features.CollectionSize.ZERO; +#endignore + +import java.util.NoSuchElementException; + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.collections.PACKAGE.sets.SORTED_SET; +import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_SET_TESTER; +import speiger.src.testers.PACKAGE.utils.HELPERS; + +@Ignore +@SuppressWarnings("javadoc") +public class FILE_KEY_TYPESortedSetNaviationTester KEY_GENERIC_TYPE extends ABSTRACT_SET_TESTER KEY_GENERIC_TYPE +{ + private SORTED_SET KEY_GENERIC_TYPE sortedSet; + private LIST KEY_GENERIC_TYPE values; + private KEY_TYPE a; + private KEY_TYPE c; + + @Override + public void setUp() throws Exception { + super.setUp(); + sortedSet = (SORTED_SET KEY_GENERIC_TYPE) getSet(); + values = HELPERS.copyToList(getSampleElements(getSubjectGenerator().getCollectionSize().getNumElements())); + values.sort(sortedSet.comparator()); + + // some tests assume SEVERAL == 3 + if (values.size() >= 1) { + a = values.GET_KEY(0); + if (values.size() >= 3) { + c = values.GET_KEY(2); + } + } + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ZERO) +#endignore + public void testEmptySetPollFirst() { +#if TYPE_OBJECT + assertEquals(null, sortedSet.POLL_FIRST_KEY()); +#else + assertEquals(CLASS_TYPE.MAX_VALUE, sortedSet.POLL_FIRST_KEY()); +#endif + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ZERO) +#endignore + public void testEmptySetPollLast() { +#if TYPE_OBJECT + assertEquals(null, sortedSet.POLL_LAST_KEY()); +#else + assertEquals(CLASS_TYPE.MIN_VALUE, sortedSet.POLL_LAST_KEY()); +#endif + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ONE) +#endignore + public void testSingletonSetPollFirst() { + assertEquals(a, sortedSet.POLL_FIRST_KEY()); + assertTrue(sortedSet.isEmpty()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(ONE) +#endignore + public void testSingletonSetPollLast() { + assertEquals(a, sortedSet.POLL_LAST_KEY()); + assertTrue(sortedSet.isEmpty()); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testPollFirst() { + assertEquals(a, sortedSet.POLL_FIRST_KEY()); + assertEquals(values.subList(1, values.size()), HELPERS.copyToList(sortedSet)); + } + +#ignore + @CollectionFeature.Require(SUPPORTS_REMOVE) + @CollectionSize.Require(SEVERAL) +#endignore + public void testPollLast() { + assertEquals(c, sortedSet.POLL_LAST_KEY()); + assertEquals(values.subList(0, values.size()-1), HELPERS.copyToList(sortedSet)); + } + +#ignore + @CollectionFeature.Require(absent = SUPPORTS_REMOVE) +#endignore + public void testPollFirstUnsupported() { + try { + sortedSet.POLL_FIRST_KEY(); + fail(); + } catch (UnsupportedOperationException e) { + } + } + +#ignore + @CollectionFeature.Require(absent = SUPPORTS_REMOVE) +#endignore + public void testPollLastUnsupported() { + try { + sortedSet.POLL_LAST_KEY(); + fail(); + } catch (UnsupportedOperationException e) { + } + } + +#ignore + @CollectionSize.Require(ZERO) +#endignore + public void testEmptySetFirst() { + try { + sortedSet.FIRST_KEY(); + fail(); + } catch (NoSuchElementException e) { + } + } + +#ignore + @CollectionSize.Require(ZERO) +#endignore + public void testEmptySetLast() { + try { + sortedSet.LAST_KEY(); + fail(); + } catch (NoSuchElementException e) { + } + } + +#ignore + @CollectionSize.Require(ONE) +#endignore + public void testSingletonSetFirst() { + assertEquals(a, sortedSet.FIRST_KEY()); + } + +#ignore + @CollectionSize.Require(ONE) +#endignore + public void testSingletonSetLast() { + assertEquals(a, sortedSet.LAST_KEY()); + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testFirst() { + assertEquals(a, sortedSet.FIRST_KEY()); + } + +#ignore + @CollectionSize.Require(SEVERAL) +#endignore + public void testLast() { + assertEquals(c, sortedSet.LAST_KEY()); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/utils/AbstractIteratorTester.template b/src/builder/resources/speiger/assets/testers/templates/utils/AbstractIteratorTester.template index a6a052d..19c00b8 100644 --- a/src/builder/resources/speiger/assets/testers/templates/utils/AbstractIteratorTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/utils/AbstractIteratorTester.template @@ -1,533 +1,533 @@ -package speiger.src.testers.PACKAGE.utils; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.NoSuchElementException; -import java.util.Set; - -import org.junit.Assert; - -import com.google.common.collect.testing.Helpers; -import com.google.common.collect.testing.IteratorFeature; - -import junit.framework.AssertionFailedError; -import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; -import speiger.src.collections.PACKAGE.collections.ITERABLE; -import speiger.src.collections.PACKAGE.collections.ITERATOR; -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; - -@SuppressWarnings("javadoc") -public abstract class ABSTRACT_ITERATOR_TESTER KEY_GENERIC_TYPE -{ - private Stimulus[] stimuli; - private final ITERATOR KEY_GENERIC_TYPE elementsToInsert; - private final Set features; - private final LIST KEY_GENERIC_TYPE expectedElements; - private final int startIndex; - private final KnownOrder knownOrder; - - private abstract static class PermittedMetaException extends RuntimeException { - static final PermittedMetaException UOE_OR_ISE = new PermittedMetaException( - "UnsupportedOperationException or IllegalStateException") { - private static final long serialVersionUID = 1L; - - @Override - boolean isPermitted(RuntimeException exception) { - return exception instanceof UnsupportedOperationException || exception instanceof IllegalStateException; - } - }; - static final PermittedMetaException UOE = new PermittedMetaException("UnsupportedOperationException") { - private static final long serialVersionUID = 1L; - - @Override - boolean isPermitted(RuntimeException exception) { - return exception instanceof UnsupportedOperationException; - } - }; - static final PermittedMetaException ISE = new PermittedMetaException("IllegalStateException") { - private static final long serialVersionUID = 1L; - - @Override - boolean isPermitted(RuntimeException exception) { - return exception instanceof IllegalStateException; - } - }; - static final PermittedMetaException NSEE = new PermittedMetaException("NoSuchElementException") { - private static final long serialVersionUID = 1L; - - @Override - boolean isPermitted(RuntimeException exception) { - return exception instanceof NoSuchElementException; - } - }; - - private PermittedMetaException(String message) { - super(message); - } - - abstract boolean isPermitted(RuntimeException exception); - - void assertPermitted(RuntimeException exception) { - if (!isPermitted(exception)) { - String message = "Exception " + exception.getClass().getSimpleName() + " was thrown; expected " - + getMessage(); - AssertionFailedError assertionFailedError = new AssertionFailedError(String.valueOf(message)); - assertionFailedError.initCause(exception); - throw assertionFailedError; - } - } - - private static final long serialVersionUID = 0; - } - - private static final class UnknownElementException extends RuntimeException { - private UnknownElementException(Collection expected, Object actual) { - super("Returned value '" + actual + "' not found. Remaining elements: " + expected); - } - - private static final long serialVersionUID = 0; - } - - protected final class MultiExceptionListIterator implements LIST_ITERATOR KEY_GENERIC_TYPE { - final ARRAY_LIST KEY_GENERIC_TYPE nextElements = new ARRAY_LISTBRACES(); - final ARRAY_LIST KEY_GENERIC_TYPE previousElements = new ARRAY_LISTBRACES(); - ARRAY_LIST KEY_GENERIC_TYPE stackWithLastReturnedElementAtTop = null; - - MultiExceptionListIterator(LIST KEY_GENERIC_TYPE expectedElements) { - HELPERS.addAll(nextElements, HELPERS.reverse(expectedElements)); - for (int i = 0; i < startIndex; i++) { - previousElements.push(nextElements.pop()); - } - } - - @Override - public void add(KEY_TYPE e) { - if (!features.contains(IteratorFeature.SUPPORTS_ADD)) { - throw PermittedMetaException.UOE; - } - - previousElements.push(e); - stackWithLastReturnedElementAtTop = null; - } - - @Override - public boolean hasNext() { - return !nextElements.isEmpty(); - } - - @Override - public boolean hasPrevious() { - return !previousElements.isEmpty(); - } - - @Override - public KEY_TYPE NEXT() { - return transferElement(nextElements, previousElements); - } - - @Override - public int nextIndex() { - return previousElements.size(); - } - - @Override - public KEY_TYPE PREVIOUS() { - return transferElement(previousElements, nextElements); - } - - @Override - public int previousIndex() { - return nextIndex() - 1; - } - - @Override - public void remove() { -#ignore - throwIfInvalid(IteratorFeature.SUPPORTS_REMOVE); -#endignore - - stackWithLastReturnedElementAtTop.pop(); - stackWithLastReturnedElementAtTop = null; - } - - @Override - public void set(KEY_TYPE e) { -#ignore - throwIfInvalid(IteratorFeature.SUPPORTS_SET); -#endignore - - stackWithLastReturnedElementAtTop.pop(); - stackWithLastReturnedElementAtTop.push(e); - } - - void promoteToNext(KEY_TYPE e) { -#if TYPE_OBJECT - if (nextElements.remove(e)) { -#else - if (nextElements.REMOVE_KEY(e)) { -#endif - nextElements.push(e); - } else { - throw new UnknownElementException(nextElements, e); - } - } - - private KEY_TYPE transferElement(ARRAY_LIST KEY_GENERIC_TYPE source, ARRAY_LIST KEY_GENERIC_TYPE destination) { - if (source.isEmpty()) { - throw PermittedMetaException.NSEE; - } - - destination.push(source.pop()); - stackWithLastReturnedElementAtTop = destination; - return destination.top(); - } - - private void throwIfInvalid(IteratorFeature methodFeature) { - if (!features.contains(methodFeature)) { - if (stackWithLastReturnedElementAtTop == null) { - throw PermittedMetaException.UOE_OR_ISE; - } else { - throw PermittedMetaException.UOE; - } - } else if (stackWithLastReturnedElementAtTop == null) { - throw PermittedMetaException.ISE; - } - } - - private LIST KEY_GENERIC_TYPE getElements() { - LIST KEY_GENERIC_TYPE elements = new ARRAY_LISTBRACES(); - HELPERS.addAll(elements, previousElements); - HELPERS.addAll(elements, HELPERS.reverse(nextElements)); - return elements; - } - } - - public enum KnownOrder { -#ignore - KNOWN_ORDER, UNKNOWN_ORDER -#endignore - } - - ABSTRACT_ITERATOR_TESTER(int steps, ITERABLE KEY_GENERIC_TYPE elementsToInsertIterable, - Iterable features, ITERABLE KEY_GENERIC_TYPE expectedElements, KnownOrder knownOrder, int startIndex) { - stimuli = new Stimulus[steps]; - if (!elementsToInsertIterable.iterator().hasNext()) { - throw new IllegalArgumentException(); - } - elementsToInsert = HELPERS.cycle(elementsToInsertIterable); - this.features = Helpers.copyToSet(features); - this.expectedElements = HELPERS.copyToList(expectedElements); - this.knownOrder = knownOrder; - this.startIndex = startIndex; - } - - protected abstract Iterable> getStimulusValues(); - - protected abstract ITERATOR KEY_GENERIC_TYPE newTargetIterator(); - protected void verify(LIST KEY_GENERIC_TYPE elements) { - } - - /** Executes the test. */ - public final void test() { - try { - recurse(0); - } catch (RuntimeException e) { - throw new RuntimeException(Arrays.toString(stimuli), e); - } - } - - public void testForEachRemaining() { - for (int i = 0; i < expectedElements.size() - 1; i++) { - - LIST KEY_GENERIC_TYPE targetElements = new ARRAY_LISTBRACES(); - ITERATOR KEY_GENERIC_TYPE iterator = newTargetIterator(); - for (int j = 0; j < i; j++) { - targetElements.add(iterator.NEXT()); - } - iterator.forEachRemaining(targetElements::add); - if (knownOrder == KnownOrder.KNOWN_ORDER) { - Assert.assertEquals(expectedElements, targetElements); - } else { - HELPERS.assertEqualIgnoringOrder(expectedElements, targetElements); - } - } - } - - private void recurse(int level) { - if (level == stimuli.length) { - // We've filled the array. - compareResultsForThisListOfStimuli(); - } else { - // Keep recursing to fill the array. - for (Stimulus stimulus : getStimulusValues()) { - stimuli[level] = stimulus; - recurse(level + 1); - } - } - } - - private void compareResultsForThisListOfStimuli() { - int removes = Collections.frequency(Arrays.asList(stimuli), remove); -#ignore - if ((!features.contains(IteratorFeature.SUPPORTS_REMOVE) && removes > 1) || (stimuli.length >= 5 && removes > 2)) { -#endignore - // removes are the most expensive thing to test, since they often - // throw exceptions with stack - // traces, so we test them a bit less aggressively - return; - } - - MultiExceptionListIterator reference = new MultiExceptionListIterator(expectedElements); - ITERATOR KEY_GENERIC_TYPE target = newTargetIterator(); - for (int i = 0; i < stimuli.length; i++) { - String s = Arrays.asList(stimuli)+", Index: "+i; - try { - stimuli[i].executeAndCompare(reference, target, s); - verify(reference.getElements()); - } catch (AssertionFailedError cause) { - AssertionFailedError assertionFailedError = new AssertionFailedError(String.valueOf("failed with stimuli " + subListCopy(stimuli, i + 1))); - assertionFailedError.initCause(cause); - throw assertionFailedError; - } - } - } - - private static List subListCopy(Object[] source, int size) { - final Object[] copy = new Object[size]; - System.arraycopy(source, 0, copy, 0, size); - return Arrays.asList(copy); - } - - private interface IteratorOperation { - KEY_OBJECT_TYPE execute(ITERATOR NO_GENERIC_TYPE iterator); - } - - /** - * Apply this method to both iterators and return normally only if both - * produce the same response. - * - * @see Stimulus#executeAndCompare(ListIterator, Iterator) - */ - private void internalExecuteAndCompare(E reference, E target, IteratorOperation method) { - KEY_OBJECT_TYPE referenceReturnValue = INVALID_KEY_VALUE; - PermittedMetaException referenceException = null; - KEY_OBJECT_TYPE targetReturnValue = INVALID_KEY_VALUE; - RuntimeException targetException = null; - - try { - targetReturnValue = method.execute(target); - } catch (RuntimeException e) { - targetException = e; - } - - try { -#ignore - if (method == NEXT_METHOD && targetException == null && knownOrder == KnownOrder.UNKNOWN_ORDER) { -#endignore -#if TYPE_OBJECT - ((MultiExceptionListIterator) reference).promoteToNext((T)targetReturnValue); -#else - ((MultiExceptionListIterator) reference).promoteToNext(targetReturnValue); -#endif - } - - referenceReturnValue = method.execute(reference); - } catch (PermittedMetaException e) { - referenceException = e; - } catch (UnknownElementException e) { - AssertionFailedError assertionFailedError = new AssertionFailedError(String.valueOf(e.getMessage())); - assertionFailedError.initCause(e); - throw assertionFailedError; - } - - if (referenceException == null) { - if (targetException != null) { - AssertionFailedError assertionFailedError = new AssertionFailedError("Target threw exception when reference did not"); - assertionFailedError.initCause(targetException); - throw assertionFailedError; - } -#if TYPE_FLOAT - Assert.assertEquals(Float.floatToIntBits(referenceReturnValue), Float.floatToIntBits(targetReturnValue)); -#else if TYPE_DOUBLE - Assert.assertEquals(Double.doubleToLongBits(referenceReturnValue), Double.doubleToLongBits(targetReturnValue)); -#else - Assert.assertEquals(referenceReturnValue, targetReturnValue); -#endif - return; - } - - if (targetException == null) { - Assert.fail("Target failed to throw " + referenceException+", Stimuli: "+Arrays.asList(stimuli)); - } - - /* - * Reference iterator threw an exception, so we should expect an - * acceptable exception from the target. - */ - referenceException.assertPermitted(targetException); - } - -#ignore - private static final IteratorOperation REMOVE_METHOD = new IteratorOperation() { -#endignore - @Override - public KEY_OBJECT_TYPE execute(ITERATOR NO_GENERIC_TYPE iterator) { - iterator.remove(); - return INVALID_KEY_VALUE; - } - }; - -#ignore - private static final IteratorOperation NEXT_METHOD = new IteratorOperation() { -#endignore - @Override - public KEY_OBJECT_TYPE execute(ITERATOR NO_GENERIC_TYPE iterator) { - return iterator.NEXT(); - } - }; - -#ignore - private static final IteratorOperation PREVIOUS_METHOD = new IteratorOperation() { -#endignore - @Override - public KEY_OBJECT_TYPE execute(ITERATOR NO_GENERIC_TYPE iterator) { - return ((BI_ITERATOR NO_GENERIC_TYPE) iterator).PREVIOUS(); - } - }; - - private final IteratorOperation newAddMethod() { - final KEY_OBJECT_TYPE toInsert = elementsToInsert.NEXT(); - return new IteratorOperation() { - @Override - public KEY_OBJECT_TYPE execute(ITERATOR NO_GENERIC_TYPE iterator) { - @SuppressWarnings("unchecked") - LIST_ITERATOR KEY_SPECIAL_GENERIC_TYPE rawIterator = (LIST_ITERATOR KEY_SPECIAL_GENERIC_TYPE) iterator; - rawIterator.add(toInsert); - return INVALID_KEY_VALUE; - } - }; - } - - private final IteratorOperation newSetMethod() { - final KEY_OBJECT_TYPE toInsert = elementsToInsert.NEXT(); - return new IteratorOperation() { - @Override - public KEY_OBJECT_TYPE execute(ITERATOR NO_GENERIC_TYPE iterator) { - @SuppressWarnings("unchecked") - LIST_ITERATOR KEY_SPECIAL_GENERIC_TYPE li = (LIST_ITERATOR KEY_SPECIAL_GENERIC_TYPE) iterator; - li.set(toInsert); - return INVALID_KEY_VALUE; - } - }; - } - - abstract static class Stimulus { - private final String toString; - - protected Stimulus(String toString) { - this.toString = toString; - } - - abstract void executeAndCompare(LIST_ITERATOR NO_GENERIC_TYPE reference, E target, String stimuli); - - @Override - public String toString() { - return toString; - } - } - - Stimulus hasNext = new Stimulus("hasNext") { - @Override - void executeAndCompare(LIST_ITERATOR NO_GENERIC_TYPE reference, ITERATOR NO_GENERIC_TYPE target, String stimuli) { - Assert.assertEquals("hasNext wasn't matching. Stimuli: "+stimuli, reference.hasNext(), target.hasNext()); - } - }; - Stimulus next = new Stimulus("next") { - @Override - void executeAndCompare(LIST_ITERATOR NO_GENERIC_TYPE reference, ITERATOR NO_GENERIC_TYPE target, String stimuli) { -#ignore - internalExecuteAndCompare(reference, target, NEXT_METHOD); -#endignore - } - }; - Stimulus remove = new Stimulus("remove") { - @Override - void executeAndCompare(LIST_ITERATOR NO_GENERIC_TYPE reference, ITERATOR NO_GENERIC_TYPE target, String stimuli) { -#ignore - internalExecuteAndCompare(reference, target, REMOVE_METHOD); -#endignore - } - }; - Stimulus skip = new Stimulus("skip") { - @Override - void executeAndCompare(LIST_ITERATOR NO_GENERIC_TYPE reference, ITERATOR NO_GENERIC_TYPE target, String stimuli) { - Assert.assertEquals("skip wasn't matching. Stimuli: "+stimuli, reference.skip(1), target.skip(1)); - } - }; - - @SuppressWarnings("unchecked") - List> iteratorStimuli() { - return Arrays.asList(hasNext, skip, next, remove); - } - - Stimulus hasPrevious = new Stimulus("hasPrevious") { - @Override - void executeAndCompare(LIST_ITERATOR NO_GENERIC_TYPE reference, BI_ITERATOR NO_GENERIC_TYPE target, String stimuli) { - Assert.assertEquals("hasPrevious wasn't matching. Stimuli: "+stimuli, reference.hasPrevious(), target.hasPrevious()); - } - }; - Stimulus previous = new Stimulus("previous") { - @Override - void executeAndCompare(LIST_ITERATOR NO_GENERIC_TYPE reference, BI_ITERATOR NO_GENERIC_TYPE target, String stimuli) { -#ignore - internalExecuteAndCompare(reference, target, PREVIOUS_METHOD); -#endignore - } - }; - Stimulus back = new Stimulus("back") { - @Override - void executeAndCompare(LIST_ITERATOR NO_GENERIC_TYPE reference, BI_ITERATOR NO_GENERIC_TYPE target, String stimuli) { - Assert.assertEquals("back wasn't matching. Stimuli: "+stimuli, reference.back(1), target.back(1)); - } - }; - - - List> biIteratorStimuli() { - return Arrays.asList(hasPrevious, back, previous); - } - - Stimulus nextIndex = new Stimulus("nextIndex") { - @Override - void executeAndCompare(LIST_ITERATOR NO_GENERIC_TYPE reference, LIST_ITERATOR NO_GENERIC_TYPE target, String stimuli) { - Assert.assertEquals("nextIndex wasn't matching. Stimuli: "+stimuli, reference.nextIndex(), target.nextIndex()); - } - }; - Stimulus previousIndex = new Stimulus("previousIndex") { - @Override - void executeAndCompare(LIST_ITERATOR NO_GENERIC_TYPE reference, LIST_ITERATOR NO_GENERIC_TYPE target, String stimuli) { - Assert.assertEquals("previous wasn't matching. Stimuli: "+stimuli, reference.previousIndex(), target.previousIndex()); - } - }; - Stimulus add = new Stimulus("add") { - @Override - void executeAndCompare(LIST_ITERATOR NO_GENERIC_TYPE reference, LIST_ITERATOR NO_GENERIC_TYPE target, String stimuli) { - internalExecuteAndCompare(reference, target, newAddMethod()); - } - }; - Stimulus set = new Stimulus("set") { - @Override - void executeAndCompare(LIST_ITERATOR NO_GENERIC_TYPE reference, LIST_ITERATOR NO_GENERIC_TYPE target, String stimuli) { - internalExecuteAndCompare(reference, target, newSetMethod()); - } - }; - - List> listIteratorStimuli() { - return Arrays.asList(nextIndex, previousIndex, add, set); - } -} +package speiger.src.testers.PACKAGE.utils; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.NoSuchElementException; +import java.util.Set; + +import org.junit.Assert; + +import com.google.common.collect.testing.Helpers; +import com.google.common.collect.testing.IteratorFeature; + +import junit.framework.AssertionFailedError; +import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; +import speiger.src.collections.PACKAGE.collections.ITERABLE; +import speiger.src.collections.PACKAGE.collections.ITERATOR; +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; + +@SuppressWarnings("javadoc") +public abstract class ABSTRACT_ITERATOR_TESTER KEY_GENERIC_TYPE +{ + private Stimulus[] stimuli; + private final ITERATOR KEY_GENERIC_TYPE elementsToInsert; + private final Set features; + private final LIST KEY_GENERIC_TYPE expectedElements; + private final int startIndex; + private final KnownOrder knownOrder; + + private abstract static class PermittedMetaException extends RuntimeException { + static final PermittedMetaException UOE_OR_ISE = new PermittedMetaException( + "UnsupportedOperationException or IllegalStateException") { + private static final long serialVersionUID = 1L; + + @Override + boolean isPermitted(RuntimeException exception) { + return exception instanceof UnsupportedOperationException || exception instanceof IllegalStateException; + } + }; + static final PermittedMetaException UOE = new PermittedMetaException("UnsupportedOperationException") { + private static final long serialVersionUID = 1L; + + @Override + boolean isPermitted(RuntimeException exception) { + return exception instanceof UnsupportedOperationException; + } + }; + static final PermittedMetaException ISE = new PermittedMetaException("IllegalStateException") { + private static final long serialVersionUID = 1L; + + @Override + boolean isPermitted(RuntimeException exception) { + return exception instanceof IllegalStateException; + } + }; + static final PermittedMetaException NSEE = new PermittedMetaException("NoSuchElementException") { + private static final long serialVersionUID = 1L; + + @Override + boolean isPermitted(RuntimeException exception) { + return exception instanceof NoSuchElementException; + } + }; + + private PermittedMetaException(String message) { + super(message); + } + + abstract boolean isPermitted(RuntimeException exception); + + void assertPermitted(RuntimeException exception) { + if (!isPermitted(exception)) { + String message = "Exception " + exception.getClass().getSimpleName() + " was thrown; expected " + + getMessage(); + AssertionFailedError assertionFailedError = new AssertionFailedError(String.valueOf(message)); + assertionFailedError.initCause(exception); + throw assertionFailedError; + } + } + + private static final long serialVersionUID = 0; + } + + private static final class UnknownElementException extends RuntimeException { + private UnknownElementException(Collection expected, Object actual) { + super("Returned value '" + actual + "' not found. Remaining elements: " + expected); + } + + private static final long serialVersionUID = 0; + } + + protected final class MultiExceptionListIterator implements LIST_ITERATOR KEY_GENERIC_TYPE { + final ARRAY_LIST KEY_GENERIC_TYPE nextElements = new ARRAY_LISTBRACES(); + final ARRAY_LIST KEY_GENERIC_TYPE previousElements = new ARRAY_LISTBRACES(); + ARRAY_LIST KEY_GENERIC_TYPE stackWithLastReturnedElementAtTop = null; + + MultiExceptionListIterator(LIST KEY_GENERIC_TYPE expectedElements) { + HELPERS.addAll(nextElements, HELPERS.reverse(expectedElements)); + for (int i = 0; i < startIndex; i++) { + previousElements.push(nextElements.pop()); + } + } + + @Override + public void add(KEY_TYPE e) { + if (!features.contains(IteratorFeature.SUPPORTS_ADD)) { + throw PermittedMetaException.UOE; + } + + previousElements.push(e); + stackWithLastReturnedElementAtTop = null; + } + + @Override + public boolean hasNext() { + return !nextElements.isEmpty(); + } + + @Override + public boolean hasPrevious() { + return !previousElements.isEmpty(); + } + + @Override + public KEY_TYPE NEXT() { + return transferElement(nextElements, previousElements); + } + + @Override + public int nextIndex() { + return previousElements.size(); + } + + @Override + public KEY_TYPE PREVIOUS() { + return transferElement(previousElements, nextElements); + } + + @Override + public int previousIndex() { + return nextIndex() - 1; + } + + @Override + public void remove() { +#ignore + throwIfInvalid(IteratorFeature.SUPPORTS_REMOVE); +#endignore + + stackWithLastReturnedElementAtTop.pop(); + stackWithLastReturnedElementAtTop = null; + } + + @Override + public void set(KEY_TYPE e) { +#ignore + throwIfInvalid(IteratorFeature.SUPPORTS_SET); +#endignore + + stackWithLastReturnedElementAtTop.pop(); + stackWithLastReturnedElementAtTop.push(e); + } + + void promoteToNext(KEY_TYPE e) { +#if TYPE_OBJECT + if (nextElements.remove(e)) { +#else + if (nextElements.REMOVE_KEY(e)) { +#endif + nextElements.push(e); + } else { + throw new UnknownElementException(nextElements, e); + } + } + + private KEY_TYPE transferElement(ARRAY_LIST KEY_GENERIC_TYPE source, ARRAY_LIST KEY_GENERIC_TYPE destination) { + if (source.isEmpty()) { + throw PermittedMetaException.NSEE; + } + + destination.push(source.pop()); + stackWithLastReturnedElementAtTop = destination; + return destination.top(); + } + + private void throwIfInvalid(IteratorFeature methodFeature) { + if (!features.contains(methodFeature)) { + if (stackWithLastReturnedElementAtTop == null) { + throw PermittedMetaException.UOE_OR_ISE; + } else { + throw PermittedMetaException.UOE; + } + } else if (stackWithLastReturnedElementAtTop == null) { + throw PermittedMetaException.ISE; + } + } + + private LIST KEY_GENERIC_TYPE getElements() { + LIST KEY_GENERIC_TYPE elements = new ARRAY_LISTBRACES(); + HELPERS.addAll(elements, previousElements); + HELPERS.addAll(elements, HELPERS.reverse(nextElements)); + return elements; + } + } + + public enum KnownOrder { +#ignore + KNOWN_ORDER, UNKNOWN_ORDER +#endignore + } + + ABSTRACT_ITERATOR_TESTER(int steps, ITERABLE KEY_GENERIC_TYPE elementsToInsertIterable, + Iterable features, ITERABLE KEY_GENERIC_TYPE expectedElements, KnownOrder knownOrder, int startIndex) { + stimuli = new Stimulus[steps]; + if (!elementsToInsertIterable.iterator().hasNext()) { + throw new IllegalArgumentException(); + } + elementsToInsert = HELPERS.cycle(elementsToInsertIterable); + this.features = Helpers.copyToSet(features); + this.expectedElements = HELPERS.copyToList(expectedElements); + this.knownOrder = knownOrder; + this.startIndex = startIndex; + } + + protected abstract Iterable> getStimulusValues(); + + protected abstract ITERATOR KEY_GENERIC_TYPE newTargetIterator(); + protected void verify(LIST KEY_GENERIC_TYPE elements) { + } + + /** Executes the test. */ + public final void test() { + try { + recurse(0); + } catch (RuntimeException e) { + throw new RuntimeException(Arrays.toString(stimuli), e); + } + } + + public void testForEachRemaining() { + for (int i = 0; i < expectedElements.size() - 1; i++) { + + LIST KEY_GENERIC_TYPE targetElements = new ARRAY_LISTBRACES(); + ITERATOR KEY_GENERIC_TYPE iterator = newTargetIterator(); + for (int j = 0; j < i; j++) { + targetElements.add(iterator.NEXT()); + } + iterator.forEachRemaining(targetElements::add); + if (knownOrder == KnownOrder.KNOWN_ORDER) { + Assert.assertEquals(expectedElements, targetElements); + } else { + HELPERS.assertEqualIgnoringOrder(expectedElements, targetElements); + } + } + } + + private void recurse(int level) { + if (level == stimuli.length) { + // We've filled the array. + compareResultsForThisListOfStimuli(); + } else { + // Keep recursing to fill the array. + for (Stimulus stimulus : getStimulusValues()) { + stimuli[level] = stimulus; + recurse(level + 1); + } + } + } + + private void compareResultsForThisListOfStimuli() { + int removes = Collections.frequency(Arrays.asList(stimuli), remove); +#ignore + if ((!features.contains(IteratorFeature.SUPPORTS_REMOVE) && removes > 1) || (stimuli.length >= 5 && removes > 2)) { +#endignore + // removes are the most expensive thing to test, since they often + // throw exceptions with stack + // traces, so we test them a bit less aggressively + return; + } + + MultiExceptionListIterator reference = new MultiExceptionListIterator(expectedElements); + ITERATOR KEY_GENERIC_TYPE target = newTargetIterator(); + for (int i = 0; i < stimuli.length; i++) { + String s = Arrays.asList(stimuli)+", Index: "+i; + try { + stimuli[i].executeAndCompare(reference, target, s); + verify(reference.getElements()); + } catch (AssertionFailedError cause) { + AssertionFailedError assertionFailedError = new AssertionFailedError(String.valueOf("failed with stimuli " + subListCopy(stimuli, i + 1))); + assertionFailedError.initCause(cause); + throw assertionFailedError; + } + } + } + + private static List subListCopy(Object[] source, int size) { + final Object[] copy = new Object[size]; + System.arraycopy(source, 0, copy, 0, size); + return Arrays.asList(copy); + } + + private interface IteratorOperation { + KEY_OBJECT_TYPE execute(ITERATOR NO_GENERIC_TYPE iterator); + } + + /** + * Apply this method to both iterators and return normally only if both + * produce the same response. + * + * @see Stimulus#executeAndCompare(ListIterator, Iterator) + */ + private void internalExecuteAndCompare(E reference, E target, IteratorOperation method) { + KEY_OBJECT_TYPE referenceReturnValue = INVALID_KEY_VALUE; + PermittedMetaException referenceException = null; + KEY_OBJECT_TYPE targetReturnValue = INVALID_KEY_VALUE; + RuntimeException targetException = null; + + try { + targetReturnValue = method.execute(target); + } catch (RuntimeException e) { + targetException = e; + } + + try { +#ignore + if (method == NEXT_METHOD && targetException == null && knownOrder == KnownOrder.UNKNOWN_ORDER) { +#endignore +#if TYPE_OBJECT + ((MultiExceptionListIterator) reference).promoteToNext((T)targetReturnValue); +#else + ((MultiExceptionListIterator) reference).promoteToNext(targetReturnValue); +#endif + } + + referenceReturnValue = method.execute(reference); + } catch (PermittedMetaException e) { + referenceException = e; + } catch (UnknownElementException e) { + AssertionFailedError assertionFailedError = new AssertionFailedError(String.valueOf(e.getMessage())); + assertionFailedError.initCause(e); + throw assertionFailedError; + } + + if (referenceException == null) { + if (targetException != null) { + AssertionFailedError assertionFailedError = new AssertionFailedError("Target threw exception when reference did not"); + assertionFailedError.initCause(targetException); + throw assertionFailedError; + } +#if TYPE_FLOAT + Assert.assertEquals(Float.floatToIntBits(referenceReturnValue), Float.floatToIntBits(targetReturnValue)); +#else if TYPE_DOUBLE + Assert.assertEquals(Double.doubleToLongBits(referenceReturnValue), Double.doubleToLongBits(targetReturnValue)); +#else + Assert.assertEquals(referenceReturnValue, targetReturnValue); +#endif + return; + } + + if (targetException == null) { + Assert.fail("Target failed to throw " + referenceException+", Stimuli: "+Arrays.asList(stimuli)); + } + + /* + * Reference iterator threw an exception, so we should expect an + * acceptable exception from the target. + */ + referenceException.assertPermitted(targetException); + } + +#ignore + private static final IteratorOperation REMOVE_METHOD = new IteratorOperation() { +#endignore + @Override + public KEY_OBJECT_TYPE execute(ITERATOR NO_GENERIC_TYPE iterator) { + iterator.remove(); + return INVALID_KEY_VALUE; + } + }; + +#ignore + private static final IteratorOperation NEXT_METHOD = new IteratorOperation() { +#endignore + @Override + public KEY_OBJECT_TYPE execute(ITERATOR NO_GENERIC_TYPE iterator) { + return iterator.NEXT(); + } + }; + +#ignore + private static final IteratorOperation PREVIOUS_METHOD = new IteratorOperation() { +#endignore + @Override + public KEY_OBJECT_TYPE execute(ITERATOR NO_GENERIC_TYPE iterator) { + return ((BI_ITERATOR NO_GENERIC_TYPE) iterator).PREVIOUS(); + } + }; + + private final IteratorOperation newAddMethod() { + final KEY_OBJECT_TYPE toInsert = elementsToInsert.NEXT(); + return new IteratorOperation() { + @Override + public KEY_OBJECT_TYPE execute(ITERATOR NO_GENERIC_TYPE iterator) { + @SuppressWarnings("unchecked") + LIST_ITERATOR KEY_SPECIAL_GENERIC_TYPE rawIterator = (LIST_ITERATOR KEY_SPECIAL_GENERIC_TYPE) iterator; + rawIterator.add(toInsert); + return INVALID_KEY_VALUE; + } + }; + } + + private final IteratorOperation newSetMethod() { + final KEY_OBJECT_TYPE toInsert = elementsToInsert.NEXT(); + return new IteratorOperation() { + @Override + public KEY_OBJECT_TYPE execute(ITERATOR NO_GENERIC_TYPE iterator) { + @SuppressWarnings("unchecked") + LIST_ITERATOR KEY_SPECIAL_GENERIC_TYPE li = (LIST_ITERATOR KEY_SPECIAL_GENERIC_TYPE) iterator; + li.set(toInsert); + return INVALID_KEY_VALUE; + } + }; + } + + abstract static class Stimulus { + private final String toString; + + protected Stimulus(String toString) { + this.toString = toString; + } + + abstract void executeAndCompare(LIST_ITERATOR NO_GENERIC_TYPE reference, E target, String stimuli); + + @Override + public String toString() { + return toString; + } + } + + Stimulus hasNext = new Stimulus("hasNext") { + @Override + void executeAndCompare(LIST_ITERATOR NO_GENERIC_TYPE reference, ITERATOR NO_GENERIC_TYPE target, String stimuli) { + Assert.assertEquals("hasNext wasn't matching. Stimuli: "+stimuli, reference.hasNext(), target.hasNext()); + } + }; + Stimulus next = new Stimulus("next") { + @Override + void executeAndCompare(LIST_ITERATOR NO_GENERIC_TYPE reference, ITERATOR NO_GENERIC_TYPE target, String stimuli) { +#ignore + internalExecuteAndCompare(reference, target, NEXT_METHOD); +#endignore + } + }; + Stimulus remove = new Stimulus("remove") { + @Override + void executeAndCompare(LIST_ITERATOR NO_GENERIC_TYPE reference, ITERATOR NO_GENERIC_TYPE target, String stimuli) { +#ignore + internalExecuteAndCompare(reference, target, REMOVE_METHOD); +#endignore + } + }; + Stimulus skip = new Stimulus("skip") { + @Override + void executeAndCompare(LIST_ITERATOR NO_GENERIC_TYPE reference, ITERATOR NO_GENERIC_TYPE target, String stimuli) { + Assert.assertEquals("skip wasn't matching. Stimuli: "+stimuli, reference.skip(1), target.skip(1)); + } + }; + + @SuppressWarnings("unchecked") + List> iteratorStimuli() { + return Arrays.asList(hasNext, skip, next, remove); + } + + Stimulus hasPrevious = new Stimulus("hasPrevious") { + @Override + void executeAndCompare(LIST_ITERATOR NO_GENERIC_TYPE reference, BI_ITERATOR NO_GENERIC_TYPE target, String stimuli) { + Assert.assertEquals("hasPrevious wasn't matching. Stimuli: "+stimuli, reference.hasPrevious(), target.hasPrevious()); + } + }; + Stimulus previous = new Stimulus("previous") { + @Override + void executeAndCompare(LIST_ITERATOR NO_GENERIC_TYPE reference, BI_ITERATOR NO_GENERIC_TYPE target, String stimuli) { +#ignore + internalExecuteAndCompare(reference, target, PREVIOUS_METHOD); +#endignore + } + }; + Stimulus back = new Stimulus("back") { + @Override + void executeAndCompare(LIST_ITERATOR NO_GENERIC_TYPE reference, BI_ITERATOR NO_GENERIC_TYPE target, String stimuli) { + Assert.assertEquals("back wasn't matching. Stimuli: "+stimuli, reference.back(1), target.back(1)); + } + }; + + + List> biIteratorStimuli() { + return Arrays.asList(hasPrevious, back, previous); + } + + Stimulus nextIndex = new Stimulus("nextIndex") { + @Override + void executeAndCompare(LIST_ITERATOR NO_GENERIC_TYPE reference, LIST_ITERATOR NO_GENERIC_TYPE target, String stimuli) { + Assert.assertEquals("nextIndex wasn't matching. Stimuli: "+stimuli, reference.nextIndex(), target.nextIndex()); + } + }; + Stimulus previousIndex = new Stimulus("previousIndex") { + @Override + void executeAndCompare(LIST_ITERATOR NO_GENERIC_TYPE reference, LIST_ITERATOR NO_GENERIC_TYPE target, String stimuli) { + Assert.assertEquals("previous wasn't matching. Stimuli: "+stimuli, reference.previousIndex(), target.previousIndex()); + } + }; + Stimulus add = new Stimulus("add") { + @Override + void executeAndCompare(LIST_ITERATOR NO_GENERIC_TYPE reference, LIST_ITERATOR NO_GENERIC_TYPE target, String stimuli) { + internalExecuteAndCompare(reference, target, newAddMethod()); + } + }; + Stimulus set = new Stimulus("set") { + @Override + void executeAndCompare(LIST_ITERATOR NO_GENERIC_TYPE reference, LIST_ITERATOR NO_GENERIC_TYPE target, String stimuli) { + internalExecuteAndCompare(reference, target, newSetMethod()); + } + }; + + List> listIteratorStimuli() { + return Arrays.asList(nextIndex, previousIndex, add, set); + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/utils/BidirectionalteratorTester.template b/src/builder/resources/speiger/assets/testers/templates/utils/BidirectionalteratorTester.template index f92bdcd..6392ae6 100644 --- a/src/builder/resources/speiger/assets/testers/templates/utils/BidirectionalteratorTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/utils/BidirectionalteratorTester.template @@ -1,34 +1,34 @@ -package speiger.src.testers.PACKAGE.utils; - -import java.util.ArrayList; -import java.util.List; - -import com.google.common.collect.testing.Helpers; -import com.google.common.collect.testing.IteratorFeature; - -import speiger.src.collections.PACKAGE.collections.ITERABLE; -import speiger.src.collections.PACKAGE.collections.ITERATOR; -import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; -import speiger.src.collections.PACKAGE.utils.LISTS; - -@SuppressWarnings("javadoc") -public abstract class BIDIRECTIONAL_ITERATOR_TESTER KEY_GENERIC_TYPE extends ABSTRACT_ITERATOR_TESTER KEY_GENERIC_TYPE { - - public BIDIRECTIONAL_ITERATOR_TESTER(int steps, Iterable features, ITERABLE KEY_GENERIC_TYPE expectedElements, KnownOrder knownOrder) { - super(steps, LISTS.singleton(INVALID_KEY_VALUE), features, expectedElements, knownOrder, 0); - } - - @Override - protected Iterable> getStimulusValues() { - List> list = new ArrayList<>(); - Helpers.addAll(list, iteratorStimuli()); - for(Stimulus iter : biIteratorStimuli()) - { - list.add((Stimulus)iter); - } - return list; - } - - @Override - protected abstract BI_ITERATOR KEY_GENERIC_TYPE newTargetIterator(); -} +package speiger.src.testers.PACKAGE.utils; + +import java.util.ArrayList; +import java.util.List; + +import com.google.common.collect.testing.Helpers; +import com.google.common.collect.testing.IteratorFeature; + +import speiger.src.collections.PACKAGE.collections.ITERABLE; +import speiger.src.collections.PACKAGE.collections.ITERATOR; +import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; +import speiger.src.collections.PACKAGE.utils.LISTS; + +@SuppressWarnings("javadoc") +public abstract class BIDIRECTIONAL_ITERATOR_TESTER KEY_GENERIC_TYPE extends ABSTRACT_ITERATOR_TESTER KEY_GENERIC_TYPE { + + public BIDIRECTIONAL_ITERATOR_TESTER(int steps, Iterable features, ITERABLE KEY_GENERIC_TYPE expectedElements, KnownOrder knownOrder) { + super(steps, LISTS.singleton(INVALID_KEY_VALUE), features, expectedElements, knownOrder, 0); + } + + @Override + protected Iterable> getStimulusValues() { + List> list = new ArrayList<>(); + Helpers.addAll(list, iteratorStimuli()); + for(Stimulus iter : biIteratorStimuli()) + { + list.add((Stimulus)iter); + } + return list; + } + + @Override + protected abstract BI_ITERATOR KEY_GENERIC_TYPE newTargetIterator(); +} diff --git a/src/builder/resources/speiger/assets/testers/templates/utils/Helpers.template b/src/builder/resources/speiger/assets/testers/templates/utils/Helpers.template index 8a85ed6..be16cd8 100644 --- a/src/builder/resources/speiger/assets/testers/templates/utils/Helpers.template +++ b/src/builder/resources/speiger/assets/testers/templates/utils/Helpers.template @@ -1,237 +1,237 @@ -package speiger.src.testers.PACKAGE.utils; - -#if TYPE_OBJECT -import java.util.Comparator; -import java.util.Objects; -#endif - -import org.junit.Assert; - -import speiger.src.collections.PACKAGE.collections.COLLECTION; -import speiger.src.collections.PACKAGE.collections.ITERABLE; -import speiger.src.collections.PACKAGE.collections.ITERATOR; -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.functions.COMPARATOR; -#endif -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; -#if !TYPE_BOOLEAN -import speiger.src.collections.PACKAGE.sets.LINKED_HASH_SET; -import speiger.src.collections.PACKAGE.sets.SET; -#endif -import speiger.src.collections.PACKAGE.utils.ITERATORS; - -@SuppressWarnings("javadoc") -public class HELPERS { - public static GENERIC_KEY_BRACES boolean equals(KEY_TYPE key, KEY_TYPE value) { - return key == value; - } - - public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE copyToList(ITERABLE KEY_UNKNOWN_GENERIC_TYPE elements) { - LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); - addAll(list, elements); - return list; - } - - public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE copyToList(KEY_TYPE[] elements) { - return copyToList(ARRAY_LIST.wrap(elements)); - } - -#if !TYPE_BOOLEAN - public static GENERIC_KEY_BRACES SET KEY_GENERIC_TYPE copyToSet(ITERABLE KEY_UNKNOWN_GENERIC_TYPE elements) { - SET KEY_GENERIC_TYPE set = new LINKED_HASH_SETBRACES(); - addAll(set, elements); - return set; - } - - public static GENERIC_KEY_BRACES SET KEY_GENERIC_TYPE copyToSet(KEY_TYPE[] elements) { - return copyToSet(ARRAY_LIST.wrap(elements)); - } - -#endif - public static GENERIC_KEY_BRACES boolean addAll(COLLECTION KEY_GENERIC_TYPE addTo, ITERABLE KEY_UNKNOWN_GENERIC_TYPE elementsToAdd) { - boolean modified = false; - for (ITERATOR KEY_UNKNOWN_GENERIC_TYPE iter = elementsToAdd.iterator(); iter.hasNext();) { - modified |= addTo.add(iter.NEXT()); - } - return modified; - } - - public static GENERIC_KEY_BRACES void assertEqualInOrder(ITERABLE KEY_UNKNOWN_GENERIC_TYPE expected, ITERABLE KEY_UNKNOWN_GENERIC_TYPE actual) { - ITERATOR KEY_UNKNOWN_GENERIC_TYPE expectedIter = expected.iterator(); - ITERATOR KEY_UNKNOWN_GENERIC_TYPE actualIter = actual.iterator(); - while (expectedIter.hasNext() && actualIter.hasNext()) { - if (KEY_EQUALS(expectedIter.NEXT(), actualIter.NEXT())) - continue; - Assert.fail("contents were not equal and in the same order: expected = "+expected+", actual = "+actual); - } - if (expectedIter.hasNext() || actualIter.hasNext()) { - Assert.fail("contents were not equal and in the same order: expected = "+expected+", actual = "+actual); - } - } - - public static GENERIC_KEY_BRACES void assertContentsInOrder(ITERABLE KEY_UNKNOWN_GENERIC_TYPE actual, KEY_TYPE... expected) { - assertEqualInOrder(ARRAY_LIST.wrap(expected), actual); - } - - public static GENERIC_KEY_BRACES void assertEqualIgnoringOrder(ITERABLE KEY_UNKNOWN_GENERIC_TYPE expected, ITERABLE KEY_UNKNOWN_GENERIC_TYPE actual) { - LIST KEY_GENERIC_TYPE exp = copyToList(expected); - LIST KEY_GENERIC_TYPE act = copyToList(actual); - String actString = act.toString(); - for (ITERATOR KEY_UNKNOWN_GENERIC_TYPE iter = exp.iterator(); iter.hasNext();) { - KEY_TYPE value = iter.NEXT(); -#if TYPE_OBJECT - if (!act.remove(value)) { -#else - if (!act.REMOVE_KEY(value)) { -#endif - Assert.fail("did not contain expected element "+value+", expected = "+exp+", actual = "+ actString); - } - } - Assert.assertTrue("unexpected elements: "+act, act.isEmpty()); - } - - public static GENERIC_KEY_BRACES void assertContentsAnyOrder(ITERABLE KEY_UNKNOWN_GENERIC_TYPE actual, KEY_TYPE... expected) { - assertEqualIgnoringOrder(ARRAY_LIST.wrap(expected), actual); - } - - public static GENERIC_KEY_BRACES void assertContains(ITERABLE KEY_UNKNOWN_GENERIC_TYPE actual, KEY_TYPE expected) { - boolean contained = false; - if (actual instanceof COLLECTION) { - contained = ((COLLECTION KEY_GENERIC_TYPE) actual).contains(expected); - } else { - for (ITERATOR KEY_UNKNOWN_GENERIC_TYPE iter = actual.iterator(); iter.hasNext();) { - if (KEY_EQUALS(iter.NEXT(), expected)) { - contained = true; - break; - } - } - } - - if (!contained) { - Assert.fail("Not true that "+actual+" contains "+expected); - } - } - - public static GENERIC_KEY_BRACES void assertContainsAllOf(ITERABLE KEY_UNKNOWN_GENERIC_TYPE actual, KEY_TYPE... expected) { - LIST KEY_GENERIC_TYPE expectedList = new ARRAY_LISTBRACES(); - expectedList.addAll(expected); - - for (ITERATOR KEY_UNKNOWN_GENERIC_TYPE iter = actual.iterator(); iter.hasNext();) { -#if TYPE_OBJECT - expectedList.remove(iter.NEXT()); -#else - expectedList.REMOVE_KEY(iter.NEXT()); -#endif - } - if (!expectedList.isEmpty()) { - Assert.fail("Not true that "+actual+" contains all of "+ARRAY_LIST.wrap(expected)); - } - } - - static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE reverse(LIST KEY_GENERIC_TYPE list) { - return new ITERABLE KEY_GENERIC_TYPE() { - @Override - public ITERATOR KEY_GENERIC_TYPE iterator() { - final LIST_ITERATOR KEY_GENERIC_TYPE listIter = list.listIterator(list.size()); - return new ITERATOR KEY_GENERIC_TYPE() { - @Override - public boolean hasNext() { - return listIter.hasPrevious(); - } - - @Override - public KEY_TYPE NEXT() { - return listIter.PREVIOUS(); - } - - @Override - public void remove() { - listIter.remove(); - } - }; - } - }; - } - - static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE cycle(ITERABLE KEY_GENERIC_TYPE iterable) { - return new ITERATOR KEY_GENERIC_TYPE() { - ITERATOR KEY_GENERIC_TYPE iterator = ITERATORS.empty(); - - @Override - public boolean hasNext() { - return true; - } - - @Override - public KEY_TYPE NEXT() { - if (!iterator.hasNext()) { - iterator = iterable.iterator(); - } - return iterator.NEXT(); - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; - } - - static GENERIC_KEY_BRACES KEY_TYPE get(ITERATOR KEY_GENERIC_TYPE iterator, int position) { - for (int i = 0; i < position; i++) { - iterator.NEXT(); - } - return iterator.NEXT(); - } - - public static GENERIC_KEY_BRACES void testComparator(COMPARATOR KEY_GENERIC_TYPE comparator, KEY_TYPE... valuesInExpectedOrder) { - testComparator(comparator, ARRAY_LIST.wrap(valuesInExpectedOrder)); - } - - public static GENERIC_KEY_BRACES void testComparator(COMPARATOR KEY_GENERIC_TYPE comparator, LIST KEY_GENERIC_TYPE valuesInExpectedOrder) { - for (int i = 0; i < valuesInExpectedOrder.size(); i++) { - KEY_TYPE t = valuesInExpectedOrder.GET_KEY(i); - for (int j = 0; j < i; j++) { - KEY_TYPE lesser = valuesInExpectedOrder.GET_KEY(j); - Assert.assertTrue(comparator+".compare("+lesser+", "+t+")", comparator.compare(lesser, t) < 0); - } - Assert.assertEquals(comparator+".compare("+t+", "+t+")", 0, comparator.compare(t, t)); - for (int j = i+1; j < valuesInExpectedOrder.size(); j++) { - KEY_TYPE greater = valuesInExpectedOrder.GET_KEY(j); - Assert.assertTrue(comparator+".compare("+greater+", "+t+")", comparator.compare(greater, t) > 0); - } - } - } - - public static COMPAREABLE_KEY_BRACES void testCompareToAndEquals(LIST KEY_GENERIC_TYPE valuesInExpectedOrder) { - for (int i = 0; i < valuesInExpectedOrder.size(); i++) { - KEY_TYPE t = valuesInExpectedOrder.GET_KEY(i); - - for (int j = 0; j < i; j++) { - KEY_TYPE lesser = valuesInExpectedOrder.GET_KEY(j); - Assert.assertTrue(lesser+".compareTo("+t+')', COMPARE_TO_KEY(lesser, t) < 0); - Assert.assertFalse(lesser == t); - } - - Assert.assertEquals(t+".compareTo("+t+')', 0, COMPARE_TO_KEY(t, t)); - Assert.assertTrue(equals(t, t)); - - for (int j = i+1; j < valuesInExpectedOrder.size(); j++) { - KEY_TYPE greater = valuesInExpectedOrder.GET_KEY(j); - Assert.assertTrue(greater+".compareTo("+t+')', COMPARE_TO_KEY(greater, t) > 0); - Assert.assertFalse(greater == t); - } - } - } - - public static GENERIC_KEY_BRACES COLLECTION KEY_GENERIC_TYPE misleadingSizeCollection(final int delta) { - return new ARRAY_LIST KEY_GENERIC_TYPE() { - @Override - public int size() { - return Math.max(0, super.size()+delta); - } - }; - } -} +package speiger.src.testers.PACKAGE.utils; + +#if TYPE_OBJECT +import java.util.Comparator; +import java.util.Objects; +#endif + +import org.junit.Assert; + +import speiger.src.collections.PACKAGE.collections.COLLECTION; +import speiger.src.collections.PACKAGE.collections.ITERABLE; +import speiger.src.collections.PACKAGE.collections.ITERATOR; +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.functions.COMPARATOR; +#endif +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; +#if !TYPE_BOOLEAN +import speiger.src.collections.PACKAGE.sets.LINKED_HASH_SET; +import speiger.src.collections.PACKAGE.sets.SET; +#endif +import speiger.src.collections.PACKAGE.utils.ITERATORS; + +@SuppressWarnings("javadoc") +public class HELPERS { + public static GENERIC_KEY_BRACES boolean equals(KEY_TYPE key, KEY_TYPE value) { + return key == value; + } + + public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE copyToList(ITERABLE KEY_UNKNOWN_GENERIC_TYPE elements) { + LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); + addAll(list, elements); + return list; + } + + public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE copyToList(KEY_TYPE[] elements) { + return copyToList(ARRAY_LIST.wrap(elements)); + } + +#if !TYPE_BOOLEAN + public static GENERIC_KEY_BRACES SET KEY_GENERIC_TYPE copyToSet(ITERABLE KEY_UNKNOWN_GENERIC_TYPE elements) { + SET KEY_GENERIC_TYPE set = new LINKED_HASH_SETBRACES(); + addAll(set, elements); + return set; + } + + public static GENERIC_KEY_BRACES SET KEY_GENERIC_TYPE copyToSet(KEY_TYPE[] elements) { + return copyToSet(ARRAY_LIST.wrap(elements)); + } + +#endif + public static GENERIC_KEY_BRACES boolean addAll(COLLECTION KEY_GENERIC_TYPE addTo, ITERABLE KEY_UNKNOWN_GENERIC_TYPE elementsToAdd) { + boolean modified = false; + for (ITERATOR KEY_UNKNOWN_GENERIC_TYPE iter = elementsToAdd.iterator(); iter.hasNext();) { + modified |= addTo.add(iter.NEXT()); + } + return modified; + } + + public static GENERIC_KEY_BRACES void assertEqualInOrder(ITERABLE KEY_UNKNOWN_GENERIC_TYPE expected, ITERABLE KEY_UNKNOWN_GENERIC_TYPE actual) { + ITERATOR KEY_UNKNOWN_GENERIC_TYPE expectedIter = expected.iterator(); + ITERATOR KEY_UNKNOWN_GENERIC_TYPE actualIter = actual.iterator(); + while (expectedIter.hasNext() && actualIter.hasNext()) { + if (KEY_EQUALS(expectedIter.NEXT(), actualIter.NEXT())) + continue; + Assert.fail("contents were not equal and in the same order: expected = "+expected+", actual = "+actual); + } + if (expectedIter.hasNext() || actualIter.hasNext()) { + Assert.fail("contents were not equal and in the same order: expected = "+expected+", actual = "+actual); + } + } + + public static GENERIC_KEY_BRACES void assertContentsInOrder(ITERABLE KEY_UNKNOWN_GENERIC_TYPE actual, KEY_TYPE... expected) { + assertEqualInOrder(ARRAY_LIST.wrap(expected), actual); + } + + public static GENERIC_KEY_BRACES void assertEqualIgnoringOrder(ITERABLE KEY_UNKNOWN_GENERIC_TYPE expected, ITERABLE KEY_UNKNOWN_GENERIC_TYPE actual) { + LIST KEY_GENERIC_TYPE exp = copyToList(expected); + LIST KEY_GENERIC_TYPE act = copyToList(actual); + String actString = act.toString(); + for (ITERATOR KEY_UNKNOWN_GENERIC_TYPE iter = exp.iterator(); iter.hasNext();) { + KEY_TYPE value = iter.NEXT(); +#if TYPE_OBJECT + if (!act.remove(value)) { +#else + if (!act.REMOVE_KEY(value)) { +#endif + Assert.fail("did not contain expected element "+value+", expected = "+exp+", actual = "+ actString); + } + } + Assert.assertTrue("unexpected elements: "+act, act.isEmpty()); + } + + public static GENERIC_KEY_BRACES void assertContentsAnyOrder(ITERABLE KEY_UNKNOWN_GENERIC_TYPE actual, KEY_TYPE... expected) { + assertEqualIgnoringOrder(ARRAY_LIST.wrap(expected), actual); + } + + public static GENERIC_KEY_BRACES void assertContains(ITERABLE KEY_UNKNOWN_GENERIC_TYPE actual, KEY_TYPE expected) { + boolean contained = false; + if (actual instanceof COLLECTION) { + contained = ((COLLECTION KEY_GENERIC_TYPE) actual).contains(expected); + } else { + for (ITERATOR KEY_UNKNOWN_GENERIC_TYPE iter = actual.iterator(); iter.hasNext();) { + if (KEY_EQUALS(iter.NEXT(), expected)) { + contained = true; + break; + } + } + } + + if (!contained) { + Assert.fail("Not true that "+actual+" contains "+expected); + } + } + + public static GENERIC_KEY_BRACES void assertContainsAllOf(ITERABLE KEY_UNKNOWN_GENERIC_TYPE actual, KEY_TYPE... expected) { + LIST KEY_GENERIC_TYPE expectedList = new ARRAY_LISTBRACES(); + expectedList.addAll(expected); + + for (ITERATOR KEY_UNKNOWN_GENERIC_TYPE iter = actual.iterator(); iter.hasNext();) { +#if TYPE_OBJECT + expectedList.remove(iter.NEXT()); +#else + expectedList.REMOVE_KEY(iter.NEXT()); +#endif + } + if (!expectedList.isEmpty()) { + Assert.fail("Not true that "+actual+" contains all of "+ARRAY_LIST.wrap(expected)); + } + } + + static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE reverse(LIST KEY_GENERIC_TYPE list) { + return new ITERABLE KEY_GENERIC_TYPE() { + @Override + public ITERATOR KEY_GENERIC_TYPE iterator() { + final LIST_ITERATOR KEY_GENERIC_TYPE listIter = list.listIterator(list.size()); + return new ITERATOR KEY_GENERIC_TYPE() { + @Override + public boolean hasNext() { + return listIter.hasPrevious(); + } + + @Override + public KEY_TYPE NEXT() { + return listIter.PREVIOUS(); + } + + @Override + public void remove() { + listIter.remove(); + } + }; + } + }; + } + + static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE cycle(ITERABLE KEY_GENERIC_TYPE iterable) { + return new ITERATOR KEY_GENERIC_TYPE() { + ITERATOR KEY_GENERIC_TYPE iterator = ITERATORS.empty(); + + @Override + public boolean hasNext() { + return true; + } + + @Override + public KEY_TYPE NEXT() { + if (!iterator.hasNext()) { + iterator = iterable.iterator(); + } + return iterator.NEXT(); + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + }; + } + + static GENERIC_KEY_BRACES KEY_TYPE get(ITERATOR KEY_GENERIC_TYPE iterator, int position) { + for (int i = 0; i < position; i++) { + iterator.NEXT(); + } + return iterator.NEXT(); + } + + public static GENERIC_KEY_BRACES void testComparator(COMPARATOR KEY_GENERIC_TYPE comparator, KEY_TYPE... valuesInExpectedOrder) { + testComparator(comparator, ARRAY_LIST.wrap(valuesInExpectedOrder)); + } + + public static GENERIC_KEY_BRACES void testComparator(COMPARATOR KEY_GENERIC_TYPE comparator, LIST KEY_GENERIC_TYPE valuesInExpectedOrder) { + for (int i = 0; i < valuesInExpectedOrder.size(); i++) { + KEY_TYPE t = valuesInExpectedOrder.GET_KEY(i); + for (int j = 0; j < i; j++) { + KEY_TYPE lesser = valuesInExpectedOrder.GET_KEY(j); + Assert.assertTrue(comparator+".compare("+lesser+", "+t+")", comparator.compare(lesser, t) < 0); + } + Assert.assertEquals(comparator+".compare("+t+", "+t+")", 0, comparator.compare(t, t)); + for (int j = i+1; j < valuesInExpectedOrder.size(); j++) { + KEY_TYPE greater = valuesInExpectedOrder.GET_KEY(j); + Assert.assertTrue(comparator+".compare("+greater+", "+t+")", comparator.compare(greater, t) > 0); + } + } + } + + public static COMPAREABLE_KEY_BRACES void testCompareToAndEquals(LIST KEY_GENERIC_TYPE valuesInExpectedOrder) { + for (int i = 0; i < valuesInExpectedOrder.size(); i++) { + KEY_TYPE t = valuesInExpectedOrder.GET_KEY(i); + + for (int j = 0; j < i; j++) { + KEY_TYPE lesser = valuesInExpectedOrder.GET_KEY(j); + Assert.assertTrue(lesser+".compareTo("+t+')', COMPARE_TO_KEY(lesser, t) < 0); + Assert.assertFalse(lesser == t); + } + + Assert.assertEquals(t+".compareTo("+t+')', 0, COMPARE_TO_KEY(t, t)); + Assert.assertTrue(equals(t, t)); + + for (int j = i+1; j < valuesInExpectedOrder.size(); j++) { + KEY_TYPE greater = valuesInExpectedOrder.GET_KEY(j); + Assert.assertTrue(greater+".compareTo("+t+')', COMPARE_TO_KEY(greater, t) > 0); + Assert.assertFalse(greater == t); + } + } + } + + public static GENERIC_KEY_BRACES COLLECTION KEY_GENERIC_TYPE misleadingSizeCollection(final int delta) { + return new ARRAY_LIST KEY_GENERIC_TYPE() { + @Override + public int size() { + return Math.max(0, super.size()+delta); + } + }; + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/utils/IteratorTester.template b/src/builder/resources/speiger/assets/testers/templates/utils/IteratorTester.template index 5a3d36d..d94f7b5 100644 --- a/src/builder/resources/speiger/assets/testers/templates/utils/IteratorTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/utils/IteratorTester.template @@ -1,20 +1,20 @@ -package speiger.src.testers.PACKAGE.utils; - -import com.google.common.collect.testing.IteratorFeature; - -import speiger.src.collections.PACKAGE.collections.ITERABLE; -import speiger.src.collections.PACKAGE.collections.ITERATOR; -import speiger.src.collections.PACKAGE.utils.LISTS; - -@SuppressWarnings("javadoc") -public abstract class ITERATOR_TESTER KEY_GENERIC_TYPE extends ABSTRACT_ITERATOR_TESTER KEY_GENERIC_TYPE -{ - public ITERATOR_TESTER(int steps, Iterable features, ITERABLE KEY_GENERIC_TYPE expectedElements, KnownOrder knownOrder) { - super(steps, LISTS.singleton(INVALID_KEY_VALUE), features, expectedElements, knownOrder, 0); - } - - @Override - protected Iterable> getStimulusValues() { - return iteratorStimuli(); - } +package speiger.src.testers.PACKAGE.utils; + +import com.google.common.collect.testing.IteratorFeature; + +import speiger.src.collections.PACKAGE.collections.ITERABLE; +import speiger.src.collections.PACKAGE.collections.ITERATOR; +import speiger.src.collections.PACKAGE.utils.LISTS; + +@SuppressWarnings("javadoc") +public abstract class ITERATOR_TESTER KEY_GENERIC_TYPE extends ABSTRACT_ITERATOR_TESTER KEY_GENERIC_TYPE +{ + public ITERATOR_TESTER(int steps, Iterable features, ITERABLE KEY_GENERIC_TYPE expectedElements, KnownOrder knownOrder) { + super(steps, LISTS.singleton(INVALID_KEY_VALUE), features, expectedElements, knownOrder, 0); + } + + @Override + protected Iterable> getStimulusValues() { + return iteratorStimuli(); + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/testers/templates/utils/ListIteratorTester.template b/src/builder/resources/speiger/assets/testers/templates/utils/ListIteratorTester.template index 1cf2fb7..2ca3543 100644 --- a/src/builder/resources/speiger/assets/testers/templates/utils/ListIteratorTester.template +++ b/src/builder/resources/speiger/assets/testers/templates/utils/ListIteratorTester.template @@ -1,36 +1,36 @@ -package speiger.src.testers.PACKAGE.utils; - -import java.util.ArrayList; -import java.util.List; - -import com.google.common.collect.testing.Helpers; -import com.google.common.collect.testing.IteratorFeature; - -import speiger.src.collections.PACKAGE.collections.ITERABLE; -import speiger.src.collections.PACKAGE.collections.ITERATOR; -import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; - -@SuppressWarnings("javadoc") -public abstract class LIST_ITERATOR_TESTER KEY_GENERIC_TYPE extends ABSTRACT_ITERATOR_TESTER KEY_GENERIC_TYPE { - public LIST_ITERATOR_TESTER(int steps, ITERABLE KEY_GENERIC_TYPE elementsToInsertIterable, Iterable features, ITERABLE KEY_GENERIC_TYPE expectedElements, int startIndex) { - super(steps, elementsToInsertIterable, features, expectedElements, KnownOrder.KNOWN_ORDER, startIndex); - } - - @Override - protected Iterable> getStimulusValues() { - List> list = new ArrayList<>(); - Helpers.addAll(list, iteratorStimuli()); - for(Stimulus iter : biIteratorStimuli()) - { - list.add((Stimulus)iter); - } - for(Stimulus iter : listIteratorStimuli()) - { - list.add((Stimulus)iter); - } - return list; - } - - @Override - protected abstract LIST_ITERATOR KEY_GENERIC_TYPE newTargetIterator(); -} +package speiger.src.testers.PACKAGE.utils; + +import java.util.ArrayList; +import java.util.List; + +import com.google.common.collect.testing.Helpers; +import com.google.common.collect.testing.IteratorFeature; + +import speiger.src.collections.PACKAGE.collections.ITERABLE; +import speiger.src.collections.PACKAGE.collections.ITERATOR; +import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; + +@SuppressWarnings("javadoc") +public abstract class LIST_ITERATOR_TESTER KEY_GENERIC_TYPE extends ABSTRACT_ITERATOR_TESTER KEY_GENERIC_TYPE { + public LIST_ITERATOR_TESTER(int steps, ITERABLE KEY_GENERIC_TYPE elementsToInsertIterable, Iterable features, ITERABLE KEY_GENERIC_TYPE expectedElements, int startIndex) { + super(steps, elementsToInsertIterable, features, expectedElements, KnownOrder.KNOWN_ORDER, startIndex); + } + + @Override + protected Iterable> getStimulusValues() { + List> list = new ArrayList<>(); + Helpers.addAll(list, iteratorStimuli()); + for(Stimulus iter : biIteratorStimuli()) + { + list.add((Stimulus)iter); + } + for(Stimulus iter : listIteratorStimuli()) + { + list.add((Stimulus)iter); + } + return list; + } + + @Override + protected abstract LIST_ITERATOR KEY_GENERIC_TYPE newTargetIterator(); +} diff --git a/src/builder/resources/speiger/assets/testers/templates/utils/MinimalCollection.template b/src/builder/resources/speiger/assets/testers/templates/utils/MinimalCollection.template index 77a554a..107424f 100644 --- a/src/builder/resources/speiger/assets/testers/templates/utils/MinimalCollection.template +++ b/src/builder/resources/speiger/assets/testers/templates/utils/MinimalCollection.template @@ -1,95 +1,95 @@ -package speiger.src.testers.PACKAGE.utils; - -import java.util.Collection; -#if TYPE_OBJECT -import java.util.function.Consumer; -#endif - -import speiger.src.collections.PACKAGE.collections.ABSTRACT_COLLECTION; -import speiger.src.collections.PACKAGE.collections.COLLECTION; -import speiger.src.collections.PACKAGE.collections.ITERATOR; -#if !TYPE_OBJECT -import speiger.src.collections.PACKAGE.functions.CONSUMER; -#else -import speiger.src.collections.objects.utils.ObjectArrays; -#endif -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; - -@SuppressWarnings("javadoc") -public class MINIMAL_COLLECTION KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION KEY_GENERIC_TYPE { - - private final KEY_TYPE[] contents; - - protected MINIMAL_COLLECTION(KEY_TYPE[] contents) { - this.contents = contents; - } - - public static GENERIC_KEY_BRACES MINIMAL_COLLECTION KEY_GENERIC_TYPE of(KEY_TYPE... contents) { - return new MINIMAL_COLLECTIONBRACES(contents); - } - - @Override - public boolean add(KEY_TYPE o) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean removeAll(Collection c) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean retainAll(Collection c) { - throw new UnsupportedOperationException(); - } - - @Override - public ITERATOR KEY_GENERIC_TYPE iterator() { - return ARRAY_LIST.wrap(contents).iterator(); - } - -#if !TYPE_OBJECT - @Override - public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) { - if(a.length < contents.length) a = new KEY_TYPE[contents.length]; - System.arraycopy(contents, 0, a, 0, contents.length); - if (a.length > contents.length) a[contents.length] = EMPTY_KEY_VALUE; - return a; - } - -#else - @Override - public E[] toArray(E[] a) { - if(a == null) a = (E[])new Object[contents.length]; - else if(a.length < contents.length) a = (E[])ObjectArrays.newArray(a.getClass().getComponentType(), contents.length); - System.arraycopy(contents, 0, a, 0, contents.length); - if (a.length > contents.length) a[contents.length] = null; - return a; - } - -#endif - @Override - public int size() { - return contents.length; - } -} +package speiger.src.testers.PACKAGE.utils; + +import java.util.Collection; +#if TYPE_OBJECT +import java.util.function.Consumer; +#endif + +import speiger.src.collections.PACKAGE.collections.ABSTRACT_COLLECTION; +import speiger.src.collections.PACKAGE.collections.COLLECTION; +import speiger.src.collections.PACKAGE.collections.ITERATOR; +#if !TYPE_OBJECT +import speiger.src.collections.PACKAGE.functions.CONSUMER; +#else +import speiger.src.collections.objects.utils.ObjectArrays; +#endif +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; + +@SuppressWarnings("javadoc") +public class MINIMAL_COLLECTION KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION KEY_GENERIC_TYPE { + + private final KEY_TYPE[] contents; + + protected MINIMAL_COLLECTION(KEY_TYPE[] contents) { + this.contents = contents; + } + + public static GENERIC_KEY_BRACES MINIMAL_COLLECTION KEY_GENERIC_TYPE of(KEY_TYPE... contents) { + return new MINIMAL_COLLECTIONBRACES(contents); + } + + @Override + public boolean add(KEY_TYPE o) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean removeAll(Collection c) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean retainAll(Collection c) { + throw new UnsupportedOperationException(); + } + + @Override + public ITERATOR KEY_GENERIC_TYPE iterator() { + return ARRAY_LIST.wrap(contents).iterator(); + } + +#if !TYPE_OBJECT + @Override + public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) { + if(a.length < contents.length) a = new KEY_TYPE[contents.length]; + System.arraycopy(contents, 0, a, 0, contents.length); + if (a.length > contents.length) a[contents.length] = EMPTY_KEY_VALUE; + return a; + } + +#else + @Override + public E[] toArray(E[] a) { + if(a == null) a = (E[])new Object[contents.length]; + else if(a.length < contents.length) a = (E[])ObjectArrays.newArray(a.getClass().getComponentType(), contents.length); + System.arraycopy(contents, 0, a, 0, contents.length); + if (a.length > contents.length) a[contents.length] = null; + return a; + } + +#endif + @Override + public int size() { + return contents.length; + } +} diff --git a/src/builder/resources/speiger/assets/testers/templates/utils/MinimalSet.template b/src/builder/resources/speiger/assets/testers/templates/utils/MinimalSet.template index 8213df4..56f86c3 100644 --- a/src/builder/resources/speiger/assets/testers/templates/utils/MinimalSet.template +++ b/src/builder/resources/speiger/assets/testers/templates/utils/MinimalSet.template @@ -1,84 +1,84 @@ -package speiger.src.testers.PACKAGE.utils; - -#if TYPE_OBJECT -import java.util.Objects; -#endif - -import speiger.src.collections.PACKAGE.collections.ITERABLE; -import speiger.src.collections.PACKAGE.collections.ITERATOR; -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.lists.LIST; -import speiger.src.collections.PACKAGE.sets.SET; - -@SuppressWarnings("javadoc") -public class MINIMAL_SET KEY_GENERIC_TYPE extends MINIMAL_COLLECTION KEY_GENERIC_TYPE implements SET KEY_GENERIC_TYPE { - public static GENERIC_KEY_BRACES MINIMAL_SET KEY_GENERIC_TYPE of(KEY_TYPE...array) { - return MINIMAL_SET.of(ARRAY_LIST.wrap(array)); - } - - public static GENERIC_KEY_BRACES MINIMAL_SET KEY_GENERIC_TYPE of(ITERABLE KEY_GENERIC_TYPE iterable) - { - LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); - for(ITERATOR KEY_GENERIC_TYPE iter = iterable.iterator();iter.hasNext();) - { - KEY_TYPE key = iter.NEXT(); - if(list.contains(key)) continue; - list.add(key); - } - return new MINIMAL_SETBRACES(list.TO_ARRAY(NEW_KEY_ARRAY(list.size()))); - } - - protected MINIMAL_SET(KEY_TYPE[] contents) { - super(contents); - } - - @Override - public SET KEY_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); } - -#if TYPE_OBJECT - @Override - public T addOrGet(T o) { throw new UnsupportedOperationException(); } - -#endif - @Override - public boolean equals(Object object) { - if (object instanceof SET) { - SET KEY_GENERIC_TYPE that = (SET KEY_GENERIC_TYPE) object; - return (size() == that.size()) && this.containsAll(that); - } - return false; - } - - @Override - public int hashCode() { - int hashCodeSum = 0; - for (ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { - hashCodeSum += KEY_TO_HASH(iter.NEXT()); - } - return hashCodeSum; - } - -#if TYPE_OBJECT - @Override - public boolean remove(Object o) { - for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { - if(KEY_EQUALS(iter.NEXT(), o)) { - iter.remove(); - return true; - } - } - return false; - } -#else - @Override - public boolean remove(KEY_TYPE o) { - for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { - if(KEY_EQUALS(iter.NEXT(), o)) { - iter.remove(); - return true; - } - } - return false; - } -#endif -} +package speiger.src.testers.PACKAGE.utils; + +#if TYPE_OBJECT +import java.util.Objects; +#endif + +import speiger.src.collections.PACKAGE.collections.ITERABLE; +import speiger.src.collections.PACKAGE.collections.ITERATOR; +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.lists.LIST; +import speiger.src.collections.PACKAGE.sets.SET; + +@SuppressWarnings("javadoc") +public class MINIMAL_SET KEY_GENERIC_TYPE extends MINIMAL_COLLECTION KEY_GENERIC_TYPE implements SET KEY_GENERIC_TYPE { + public static GENERIC_KEY_BRACES MINIMAL_SET KEY_GENERIC_TYPE of(KEY_TYPE...array) { + return MINIMAL_SET.of(ARRAY_LIST.wrap(array)); + } + + public static GENERIC_KEY_BRACES MINIMAL_SET KEY_GENERIC_TYPE of(ITERABLE KEY_GENERIC_TYPE iterable) + { + LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); + for(ITERATOR KEY_GENERIC_TYPE iter = iterable.iterator();iter.hasNext();) + { + KEY_TYPE key = iter.NEXT(); + if(list.contains(key)) continue; + list.add(key); + } + return new MINIMAL_SETBRACES(list.TO_ARRAY(NEW_KEY_ARRAY(list.size()))); + } + + protected MINIMAL_SET(KEY_TYPE[] contents) { + super(contents); + } + + @Override + public SET KEY_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); } + +#if TYPE_OBJECT + @Override + public T addOrGet(T o) { throw new UnsupportedOperationException(); } + +#endif + @Override + public boolean equals(Object object) { + if (object instanceof SET) { + SET KEY_GENERIC_TYPE that = (SET KEY_GENERIC_TYPE) object; + return (size() == that.size()) && this.containsAll(that); + } + return false; + } + + @Override + public int hashCode() { + int hashCodeSum = 0; + for (ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { + hashCodeSum += KEY_TO_HASH(iter.NEXT()); + } + return hashCodeSum; + } + +#if TYPE_OBJECT + @Override + public boolean remove(Object o) { + for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { + if(KEY_EQUALS(iter.NEXT(), o)) { + iter.remove(); + return true; + } + } + return false; + } +#else + @Override + public boolean remove(KEY_TYPE o) { + for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { + if(KEY_EQUALS(iter.NEXT(), o)) { + iter.remove(); + return true; + } + } + return false; + } +#endif +} diff --git a/src/builder/resources/speiger/assets/testers/templates/utils/Samples.template b/src/builder/resources/speiger/assets/testers/templates/utils/Samples.template index c557db4..731fe8a 100644 --- a/src/builder/resources/speiger/assets/testers/templates/utils/Samples.template +++ b/src/builder/resources/speiger/assets/testers/templates/utils/Samples.template @@ -1,73 +1,73 @@ -package speiger.src.testers.PACKAGE.utils; - -import com.google.common.collect.testing.SampleElements; - -import speiger.src.collections.PACKAGE.collections.ITERABLE; -import speiger.src.collections.PACKAGE.collections.ITERATOR; -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.lists.LIST; - -@SuppressWarnings("javadoc") -public class SAMPLE_ELEMENTS KEY_GENERIC_TYPE implements ITERABLE KEY_GENERIC_TYPE -{ - private final KEY_TYPE e0; - private final KEY_TYPE e1; - private final KEY_TYPE e2; - private final KEY_TYPE e3; - private final KEY_TYPE e4; - - public SAMPLE_ELEMENTS(SampleElements samples) - { - this(samples.e0(), samples.e1(), samples.e2(), samples.e3(), samples.e4()); - } - - public SAMPLE_ELEMENTS(KEY_TYPE e0, KEY_TYPE e1, KEY_TYPE e2, KEY_TYPE e3, KEY_TYPE e4) - { - this.e0 = e0; - this.e1 = e1; - this.e2 = e2; - this.e3 = e3; - this.e4 = e4; - } - - public SampleElements toSamples() - { - return new SampleElements<>(e0(), e1(), e2(), e3(), e4()); - } - - @Override - public ITERATOR KEY_GENERIC_TYPE iterator() - { - return asList().iterator(); - } - - public LIST KEY_GENERIC_TYPE asList() - { - return ARRAY_LIST.wrap(e0(), e1(), e2(), e3(), e4()); - } - - public KEY_TYPE e0() - { - return e0; - } - - public KEY_TYPE e1() - { - return e1; - } - - public KEY_TYPE e2() - { - return e2; - } - - public KEY_TYPE e3() - { - return e3; - } - - public KEY_TYPE e4() - { - return e4; - } -} +package speiger.src.testers.PACKAGE.utils; + +import com.google.common.collect.testing.SampleElements; + +import speiger.src.collections.PACKAGE.collections.ITERABLE; +import speiger.src.collections.PACKAGE.collections.ITERATOR; +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.lists.LIST; + +@SuppressWarnings("javadoc") +public class SAMPLE_ELEMENTS KEY_GENERIC_TYPE implements ITERABLE KEY_GENERIC_TYPE +{ + private final KEY_TYPE e0; + private final KEY_TYPE e1; + private final KEY_TYPE e2; + private final KEY_TYPE e3; + private final KEY_TYPE e4; + + public SAMPLE_ELEMENTS(SampleElements samples) + { + this(samples.e0(), samples.e1(), samples.e2(), samples.e3(), samples.e4()); + } + + public SAMPLE_ELEMENTS(KEY_TYPE e0, KEY_TYPE e1, KEY_TYPE e2, KEY_TYPE e3, KEY_TYPE e4) + { + this.e0 = e0; + this.e1 = e1; + this.e2 = e2; + this.e3 = e3; + this.e4 = e4; + } + + public SampleElements toSamples() + { + return new SampleElements<>(e0(), e1(), e2(), e3(), e4()); + } + + @Override + public ITERATOR KEY_GENERIC_TYPE iterator() + { + return asList().iterator(); + } + + public LIST KEY_GENERIC_TYPE asList() + { + return ARRAY_LIST.wrap(e0(), e1(), e2(), e3(), e4()); + } + + public KEY_TYPE e0() + { + return e0; + } + + public KEY_TYPE e1() + { + return e1; + } + + public KEY_TYPE e2() + { + return e2; + } + + public KEY_TYPE e3() + { + return e3; + } + + public KEY_TYPE e4() + { + return e4; + } +} diff --git a/src/builder/resources/speiger/assets/tests/templates/collections/ListTests.template b/src/builder/resources/speiger/assets/tests/templates/collections/ListTests.template index 850982e..3ed1002 100644 --- a/src/builder/resources/speiger/assets/tests/templates/collections/ListTests.template +++ b/src/builder/resources/speiger/assets/tests/templates/collections/ListTests.template @@ -1,358 +1,358 @@ -package speiger.src.tests.PACKAGE.collections; - -import java.util.Arrays; -import java.util.Collection; -import java.util.function.Function; -#if TYPE_BOOLEAN -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; -#endif - -import com.google.common.collect.testing.features.CollectionSize; -#if !TYPE_BOOLEAN -import com.google.common.collect.testing.features.CollectionFeature; -#endif -import com.google.common.collect.testing.features.ListFeature; -import com.google.common.collect.testing.features.Feature; - -#if TYPE_BOOLEAN -import com.google.common.collect.testing.testers.CollectionAddAllTester; -import com.google.common.collect.testing.testers.CollectionAddTester; -import com.google.common.collect.testing.testers.CollectionContainsAllTester; -import com.google.common.collect.testing.testers.CollectionContainsTester; -import com.google.common.collect.testing.testers.CollectionIteratorTester; -import com.google.common.collect.testing.testers.CollectionRemoveAllTester; -import com.google.common.collect.testing.testers.CollectionRemoveTester; -import com.google.common.collect.testing.testers.CollectionRetainAllTester; -import com.google.common.collect.testing.testers.ListAddAllAtIndexTester; -import com.google.common.collect.testing.testers.ListAddAtIndexTester; -import com.google.common.collect.testing.testers.ListEqualsTester; -import com.google.common.collect.testing.testers.ListIndexOfTester; -import com.google.common.collect.testing.testers.ListLastIndexOfTester; -import com.google.common.collect.testing.testers.ListRetainAllTester; -import com.google.common.collect.testing.testers.ListSubListTester; -#else -import com.google.common.collect.testing.testers.ListSubListTester; -#endif - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; -import speiger.src.collections.PACKAGE.lists.IMMUTABLE_LIST; -import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; -import speiger.src.collections.PACKAGE.lists.LINKED_LIST; -import speiger.src.collections.PACKAGE.lists.COPY_ON_WRITE_LIST; -import speiger.src.collections.PACKAGE.lists.LIST; - -#if !TYPE_BOOLEAN -import speiger.src.collections.PACKAGE.utils.LISTS; -#endif -import speiger.src.testers.PACKAGE.builder.LIST_TEST_BUILDER; -import speiger.src.testers.PACKAGE.impl.COLLECTION_CONSTRUCTOR_TESTS; -import speiger.src.testers.PACKAGE.impl.SIMPLE_TEST_GENERATOR; -#if TYPE_OBJECT -import speiger.src.testers.PACKAGE.generators.TEST_LIST_GENERATOR; -#endif -import speiger.src.testers.utils.SpecialFeature; -import speiger.src.testers.utils.TestUtils; -#if TYPE_BOOLEAN -import speiger.src.testers.booleans.tests.collection.BooleanCollectionAddAllArrayTester; -import speiger.src.testers.booleans.tests.collection.BooleanCollectionAddAllTester; -import speiger.src.testers.booleans.tests.collection.BooleanCollectionAddTester; -import speiger.src.testers.booleans.tests.collection.BooleanCollectionContainsAllTester; -import speiger.src.testers.booleans.tests.collection.BooleanCollectionContainsTester; -import speiger.src.testers.booleans.tests.collection.BooleanCollectionIteratorTester; -import speiger.src.testers.booleans.tests.collection.BooleanCollectionRemoveAllTester; -import speiger.src.testers.booleans.tests.collection.BooleanCollectionRetainAllTester; -import speiger.src.testers.booleans.tests.list.BooleanListAddAllArrayAtIndexTester; -import speiger.src.testers.booleans.tests.list.BooleanListAddAllAtIndexTester; -import speiger.src.testers.booleans.tests.list.BooleanListAddAtIndexTester; -import speiger.src.testers.booleans.tests.list.BooleanListEqualsTester; -import speiger.src.testers.booleans.tests.list.BooleanListExtractElementsTester; -import speiger.src.testers.booleans.tests.list.BooleanListIndexOfTester; -import speiger.src.testers.booleans.tests.list.BooleanListLastIndexOfTester; -import speiger.src.testers.booleans.tests.list.BooleanListRemoveElementsTester; -import speiger.src.testers.booleans.tests.list.BooleanListRetainAllTester; -import speiger.src.testers.booleans.tests.list.BooleanListSubListTester; -#else -import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListSubListTester; -#endif - - -@SuppressWarnings("javadoc") -public class LIST_TESTS extends TestCase -{ - public static Test suite() { - TestSuite suite = new TestSuite("LISTS"); - suite(suite); - constructorSuite(suite); - System.out.println("Generated ["+suite.countTestCases()+"] Tests"); - return suite; - } - - public static void constructorSuite(TestSuite suite) { - TestSuite constructors = new TestSuite("Constructors"); - constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.ArrayList.class)); - constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.LinkedList.class)); - constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.CopyOnWriteArrayList.class)); - constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.ImmutableList.class)); - suite.addTest(constructors); - } - -#if TYPE_OBJECT - public static void suite(TestSuite suite) { - suite.addTest(listSuite("ARRAY_LIST", T -> new ARRAY_LISTBRACES(T), getFeatures(), -1)); - suite.addTest(listSuite("LINKED_LIST", T -> new LINKED_LISTBRACES(T), getFeatures(), -1)); - suite.addTest(copyOnWritelistSuite("COPY_ON_WRITE_LIST", T -> new COPY_ON_WRITE_LISTBRACES(T), getCopyOnWriteFeatures(), -1)); - suite.addTest(listSuite("IMMUTABLE_LIST", T -> new IMMUTABLE_LISTBRACES(T), getImmutableFeatures(), -1)); - suite.addTest(listSuite("Synchronized ARRAY_LIST", T -> new ARRAY_LISTBRACES(T).synchronize(), getFeatures(), -1)); - suite.addTest(listSuite("Unmodifiable ARRAY_LIST", T -> new ARRAY_LISTBRACES(T).unmodifiable(), getImmutableFeatures(), -1)); - suite.addTest(emptylistSuite("Empty LIST", T -> LISTS.empty(), getImmutableWrapperFeatures(), 0)); - suite.addTest(listSuite("Singleton LIST", T -> LISTS.singleton(T[0]), getImmutableWrapperFeatures(), 1)); - } - - private static Test listSuite(String name, Function factory, Collection> features, int size) { - return LIST_TEST_BUILDER.using((TEST_LIST_GENERATOR KEY_STRING_GENERIC_TYPE)new SIMPLE_TEST_GENERATOR.Lists KEY_STRING_GENERIC_TYPE(factory).setElements(createStrings())).setPrefixes(createPrefixes()).setSuffixes(createSuffixes()).named(name).withFeatures(getSizes(size)).withFeatures(features).createTestSuite(); - } - - private static Test copyOnWritelistSuite(String name, Function factory, Collection> features, int size) { - return LIST_TEST_BUILDER.using((TEST_LIST_GENERATOR KEY_STRING_GENERIC_TYPE)new SIMPLE_TEST_GENERATOR.Lists KEY_STRING_GENERIC_TYPE(factory).setElements(createStrings())).setPrefixes(createPrefixes()).setSuffixes(createSuffixes()).named(name).withFeatures(getSizes(size)).withFeatures(features).createTestSuite(); - } - - private static Test emptylistSuite(String name, Function factory, Collection> features, int size) { - return LIST_TEST_BUILDER.using((TEST_LIST_GENERATOR KEY_STRING_GENERIC_TYPE)new SIMPLE_TEST_GENERATOR.Lists KEY_STRING_GENERIC_TYPE(factory).setElements(createStrings())).setPrefixes(createPrefixes()).setSuffixes(createSuffixes()).named(name).withFeatures(getSizes(size)).suppressing(TestUtils.getSurpession(ListSubListTester.class)).suppressing(TestUtils.getSurpession(FILE_KEY_TYPEListSubListTester.class)).withFeatures(features).createTestSuite(); - } - - private static String[] createStrings() { - return new String[]{"a", "b", "c", "d", "e"}; - } - - private static String[] createPrefixes() { - return new String[]{"^", "_", "`"}; - } - - private static String[] createSuffixes() { - return new String[]{"f", "g", "h"}; - } - -#else if !TYPE_BOOLEAN - public static void suite(TestSuite suite) { - suite.addTest(listSuite("ARRAY_LIST", ARRAY_LIST::new, getFeatures(), -1)); - suite.addTest(listSuite("LINKED_LIST", LINKED_LIST::new, getFeatures(), -1)); - suite.addTest(copyOnWritelistSuite("COPY_ON_WRITE_LIST", COPY_ON_WRITE_LIST::new, getCopyOnWriteFeatures(), -1)); - suite.addTest(listSuite("IMMUTABLE_LIST", IMMUTABLE_LIST::new, getImmutableFeatures(), -1)); - suite.addTest(listSuite("Synchronized ARRAY_LIST", T -> new ARRAY_LISTBRACES(T).synchronize(), getFeatures(), -1)); - suite.addTest(listSuite("Unmodifiable ARRAY_LIST", T -> new ARRAY_LISTBRACES(T).unmodifiable(), getImmutableFeatures(), -1)); - suite.addTest(emptylistSuite("Empty LIST", T -> LISTS.empty(), getImmutableWrapperFeatures(), 0)); - suite.addTest(listSuite("Singleton LIST", T -> LISTS.singleton(T[0]), getImmutableWrapperFeatures(), 1)); - } - - private static Test listSuite(String name, Function factory, Collection> features, int size) { - return LIST_TEST_BUILDER.using(new SIMPLE_TEST_GENERATOR.ListsBRACES(factory)).named(name).withFeatures(getSizes(size)).withFeatures(features).createTestSuite(); - } - - private static Test copyOnWritelistSuite(String name, Function factory, Collection> features, int size) { - return LIST_TEST_BUILDER.using(new SIMPLE_TEST_GENERATOR.Lists KEY_STRING_GENERIC_TYPE(factory)).named(name).withFeatures(getSizes(size)).withFeatures(features).createTestSuite(); - } - - private static Test emptylistSuite(String name, Function factory, Collection> features, int size) { - return LIST_TEST_BUILDER.using(new SIMPLE_TEST_GENERATOR.ListsBRACES(factory)).named(name).withFeatures(getSizes(size)).suppressing(TestUtils.getSurpession(ListSubListTester.class)).suppressing(TestUtils.getSurpession(FILE_KEY_TYPEListSubListTester.class)).withFeatures(features).createTestSuite(); - } - -#else - public static void suite(TestSuite suite) { - listSuite(suite, "ARRAY_LIST", ARRAY_LIST::new, getFeatures(), false, -1); - listSuite(suite, "LINKED_LIST", LINKED_LIST::new, getFeatures(), false, -1); - copyOnWritelistSuite(suite, "COPY_ON_WRITE_LIST", COPY_ON_WRITE_LIST::new, getCopyOnWriteFeatures(), false, -1); - listSuite(suite, "IMMUTABLE_LIST", IMMUTABLE_LIST::new, getImmutableFeatures(), true, -1); - listSuite(suite, "Synchronized ARRAY_LIST", T -> new ARRAY_LISTBRACES(T).synchronize(), getFeatures(), false, -1); - listSuite(suite, "Unmodifiable ARRAY_LIST", T -> new ARRAY_LISTBRACES(T).unmodifiable(), getImmutableFeatures(), true, -1); - } - - private static void copyOnWritelistSuite(TestSuite suite, String name, Function factory, Collection> features, boolean immutable, int size) { - TestSuite data = new TestSuite(name); - Collection sizes = getSizes(size); -#ignore - if(sizes.contains(CollectionSize.ZERO) || sizes.contains(CollectionSize.ANY)) { -#endignore - data.addTest(LIST_TEST_BUILDER.using(new SIMPLE_TEST_GENERATOR.ListsBRACES(factory)) -#ignore - .named(name+" [collection size: zero]").withFeatures(CollectionSize.ZERO).withFeatures(features).suppressing(getSurpression(CollectionSize.ZERO, immutable)).createTestSuite()); -#endignore - } -#ignore - if(sizes.contains(CollectionSize.ONE) || sizes.contains(CollectionSize.ANY)) { -#endignore - data.addTest(LIST_TEST_BUILDER.using(new SIMPLE_TEST_GENERATOR.ListsBRACES(factory)) -#ignore - .named(name+" [collection size: one]").withFeatures(CollectionSize.ONE).withFeatures(features).suppressing(getSurpression(CollectionSize.ONE, immutable)).createTestSuite()); -#endignore - } -#ignore - if(sizes.contains(CollectionSize.SEVERAL) || sizes.contains(CollectionSize.ANY)) { -#endignore - data.addTest(LIST_TEST_BUILDER.using(new SIMPLE_TEST_GENERATOR.ListsBRACES(factory)) -#ignore - .named(name+" [collection size: several]").withFeatures(CollectionSize.SEVERAL).withFeatures(features).suppressing(getSurpression(CollectionSize.SEVERAL, immutable)).createTestSuite()); -#endignore - } - suite.addTest(data); - } - - private static void listSuite(TestSuite suite, String name, Function factory, Collection> features, boolean immutable, int size) { - TestSuite data = new TestSuite(name); - Collection sizes = getSizes(size); -#ignore - if(sizes.contains(CollectionSize.ZERO) || sizes.contains(CollectionSize.ANY)) { -#endignore - data.addTest(LIST_TEST_BUILDER.using(new SIMPLE_TEST_GENERATOR.ListsBRACES(factory)) -#ignore - .named(name+" [collection size: zero]").withFeatures(CollectionSize.ZERO).withFeatures(features).suppressing(getSurpression(CollectionSize.ZERO, immutable)).createTestSuite()); -#endignore - } -#ignore - if(sizes.contains(CollectionSize.ONE) || sizes.contains(CollectionSize.ANY)) { -#endignore - data.addTest(LIST_TEST_BUILDER.using(new SIMPLE_TEST_GENERATOR.ListsBRACES(factory)) -#ignore - .named(name+" [collection size: one]").withFeatures(CollectionSize.ONE).withFeatures(features).suppressing(getSurpression(CollectionSize.ONE, immutable)).createTestSuite()); -#endignore - } -#ignore - if(sizes.contains(CollectionSize.SEVERAL) || sizes.contains(CollectionSize.ANY)) { -#endignore - data.addTest(LIST_TEST_BUILDER.using(new SIMPLE_TEST_GENERATOR.ListsBRACES(factory)).named(name) -#ignore - .named(name+" [collection size: several]").withFeatures(CollectionSize.SEVERAL).withFeatures(features).suppressing(getSurpression(CollectionSize.SEVERAL, immutable)).createTestSuite()); -#endignore - } - suite.addTest(data); - } - - private static List getSurpression(CollectionSize size, boolean immutable) { - List list = new ArrayList<>(); - if(size == CollectionSize.ONE) { - TestUtils.getSurpession(list, CollectionRetainAllTester.class, "testRetainAll_disjointPreviouslyNonEmpty"); - if(immutable) { - TestUtils.getSurpession(list, CollectionAddAllTester.class, "testAddAll_unsupportedNonePresent"); - TestUtils.getSurpession(list, BooleanCollectionAddAllTester.class, "testAddAll_unsupportedNonePresent"); - TestUtils.getSurpession(list, BooleanCollectionAddAllArrayTester.class, "testAddAllArray_unsupportedNonePresent"); - } - } - else { - TestUtils.getSurpession(list, CollectionContainsAllTester.class, "testContainsAll_disjoint", "testContainsAll_partialOverlap"); - TestUtils.getSurpession(list, CollectionContainsTester.class, "testContains_no"); - TestUtils.getSurpession(list, CollectionIteratorTester.class, "testIterator_removeAffectsBackingCollection"); - TestUtils.getSurpession(list, CollectionRemoveAllTester.class, "testRemoveAll_nonePresent"); - TestUtils.getSurpession(list, CollectionRemoveTester.class, "testRemove_present", "testRemove_notPresent"); - TestUtils.getSurpession(list, CollectionRetainAllTester.class, "testRetainAll_disjointPreviouslyNonEmpty", "testRetainAll_containsDuplicatesSizeSeveral", "testRetainAll_partialOverlap"); - TestUtils.getSurpession(list, BooleanCollectionContainsAllTester.class, "testContainsAll_disjoint", "testContainsAll_partialOverlap"); - TestUtils.getSurpession(list, BooleanCollectionContainsTester.class, "testContains_no"); - TestUtils.getSurpession(list, BooleanCollectionIteratorTester.class, "testIterator_removeAffectsBackingCollection"); - TestUtils.getSurpession(list, BooleanCollectionRemoveAllTester.class, "testRemoveAll_nonePresentFetchRemoved", "testRemoveAll_someFetchRemovedElements", "testRemoveAll_nonePresent"); - TestUtils.getSurpession(list, BooleanCollectionRetainAllTester.class, "testRetainAllExtra_containsDuplicatesSizeSeveral", "testRetainAllExtra_partialOverlap", "testRetainAll_containsDuplicatesSizeSeveral", "testRetainAll_partialOverlap"); - TestUtils.getSurpession(list, ListAddAllAtIndexTester.class, "testAddAllAtIndex_negative", "testAddAllAtIndex_tooLarge"); - TestUtils.getSurpession(list, ListAddAtIndexTester.class, "testAddAtIndex_tooLarge", "testAddAtIndex_negative"); - TestUtils.getSurpession(list, ListEqualsTester.class, "testEquals_otherListWithDifferentElements"); - TestUtils.getSurpession(list, ListIndexOfTester.class, "testFind_no"); - TestUtils.getSurpession(list, ListLastIndexOfTester.class, "testLastIndexOf_duplicate", "testFind_no", "testFind_yes"); - TestUtils.getSurpession(list, ListRetainAllTester.class, "testRetainAll_duplicatesRemoved", "testRetainAll_countIgnored"); - TestUtils.getSurpession(list, ListSubListTester.class, "testSubList_lastIndexOf", "testSubList_contains", "testSubList_indexOf"); - TestUtils.getSurpession(list, BooleanListAddAllAtIndexTester.class, "testAddAllAtIndex_negative", "testAddAllAtIndex_tooLarge"); - TestUtils.getSurpession(list, BooleanListAddAllArrayAtIndexTester.class, "testAddAllArrayAtIndex_tooLarge", "testAddAllArrayAtIndex_negative"); - TestUtils.getSurpession(list, BooleanListAddAtIndexTester.class, "testAddAtIndex_tooLarge", "testAddAtIndex_negative"); - TestUtils.getSurpession(list, BooleanListEqualsTester.class, "testEquals_otherListWithDifferentElements"); - TestUtils.getSurpession(list, BooleanListExtractElementsTester.class, "testRemoveElements"); - TestUtils.getSurpession(list, BooleanListIndexOfTester.class, "testFind_no"); - TestUtils.getSurpession(list, BooleanListLastIndexOfTester.class, "testLastIndexOf_duplicate", "testFind_no", "testFind_yes"); - TestUtils.getSurpession(list, BooleanListRemoveElementsTester.class, "testRemoveElements"); - TestUtils.getSurpession(list, BooleanListRetainAllTester.class, "testRetainAll_duplicatesRemoved", "testRetainAll_countIgnored"); - TestUtils.getSurpession(list, BooleanListSubListTester.class, "testSubList_lastIndexOf", "testSubList_contains", "testSubList_indexOf"); - if(immutable) { - TestUtils.getSurpession(list, CollectionAddAllTester.class, "testAddAll_unsupportedNonePresent"); - TestUtils.getSurpession(list, CollectionAddTester.class, "testAdd_unsupportedNotPresent"); - TestUtils.getSurpession(list, CollectionRemoveTester.class, "testRemove_unsupportedNotPresent"); - TestUtils.getSurpession(list, BooleanCollectionAddAllTester.class, "testAddAll_unsupportedNonePresent"); - TestUtils.getSurpession(list, BooleanCollectionAddAllArrayTester.class, "testAddAllArray_unsupportedNonePresent"); - TestUtils.getSurpession(list, BooleanCollectionAddTester.class, "testAdd_unsupportedNotPresent"); - TestUtils.getSurpession(list, ListAddAllAtIndexTester.class, "testAddAllAtIndex_unsupportedSomePresent"); - TestUtils.getSurpession(list, ListAddAtIndexTester.class, "testAddAtIndex_unsupportedNotPresent"); - TestUtils.getSurpession(list, BooleanListAddAllAtIndexTester.class, "testAddAllAtIndex_unsupportedSomePresent"); - TestUtils.getSurpession(list, BooleanListAddAllArrayAtIndexTester.class, "testAddAllArrayAtIndex_unsupportedSomePresent"); - TestUtils.getSurpession(list, BooleanListAddAtIndexTester.class, "testAddAtIndex_unsupportedNotPresent"); - } - } - return list; - } - -#endif -#ignore - private static Collection getSizes(int size) { - switch(size) { - case 0: return Arrays.asList(CollectionSize.ZERO); - case 1: return Arrays.asList(CollectionSize.ONE); - case 2: return Arrays.asList(CollectionSize.ZERO, CollectionSize.ONE); - case 3: return Arrays.asList(CollectionSize.SEVERAL); - case 4: return Arrays.asList(CollectionSize.ZERO, CollectionSize.SEVERAL); - case 5: return Arrays.asList(CollectionSize.ONE, CollectionSize.SEVERAL); - default: return Arrays.asList(CollectionSize.ANY); - } - } - -#endignore - - private static Collection> getCopyOnWriteFeatures() { - -#if TYPE_OBJECT -#ignore - return Arrays.asList(ListFeature.SUPPORTS_SET, ListFeature.SUPPORTS_ADD_WITH_INDEX, ListFeature.SUPPORTS_REMOVE_WITH_INDEX, SpecialFeature.COPYING, CollectionFeature.ALLOWS_NULL_VALUES); -#endignore -#else -#ignore - return Arrays.asList(ListFeature.SUPPORTS_SET, ListFeature.SUPPORTS_ADD_WITH_INDEX, ListFeature.SUPPORTS_REMOVE_WITH_INDEX, SpecialFeature.COPYING); -#endignore -#endif - } - - private static Collection> getImmutableFeatures() { - -#if TYPE_OBJECT -#ignore - return Arrays.asList(SpecialFeature.COPYING, CollectionFeature.ALLOWS_NULL_VALUES); -#endignore -#else -#ignore - return Arrays.asList(SpecialFeature.COPYING); -#endignore -#endif - } - -#if !TYPE_BOOLEAN - private static Collection> getImmutableWrapperFeatures() { - -#if TYPE_OBJECT -#ignore - return Arrays.asList(SpecialFeature.COPYING, CollectionFeature.ALLOWS_NULL_VALUES, CollectionFeature.SUBSET_VIEW); -#endignore -#else -#ignore - return Arrays.asList(SpecialFeature.COPYING, CollectionFeature.SUBSET_VIEW); -#endignore -#endif - } - -#endif - private static Collection> getFeatures() { - -#if TYPE_OBJECT -#ignore - return Arrays.asList(ListFeature.GENERAL_PURPOSE, CollectionFeature.ALLOWS_NULL_VALUES, SpecialFeature.COPYING, SpecialFeature.ITERATOR_MODIFIABLE); -#endignore -#else -#ignore - return Arrays.asList(ListFeature.GENERAL_PURPOSE, SpecialFeature.COPYING, SpecialFeature.ITERATOR_MODIFIABLE); -#endignore -#endif - } +package speiger.src.tests.PACKAGE.collections; + +import java.util.Arrays; +import java.util.Collection; +import java.util.function.Function; +#if TYPE_BOOLEAN +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +#endif + +import com.google.common.collect.testing.features.CollectionSize; +#if !TYPE_BOOLEAN +import com.google.common.collect.testing.features.CollectionFeature; +#endif +import com.google.common.collect.testing.features.ListFeature; +import com.google.common.collect.testing.features.Feature; + +#if TYPE_BOOLEAN +import com.google.common.collect.testing.testers.CollectionAddAllTester; +import com.google.common.collect.testing.testers.CollectionAddTester; +import com.google.common.collect.testing.testers.CollectionContainsAllTester; +import com.google.common.collect.testing.testers.CollectionContainsTester; +import com.google.common.collect.testing.testers.CollectionIteratorTester; +import com.google.common.collect.testing.testers.CollectionRemoveAllTester; +import com.google.common.collect.testing.testers.CollectionRemoveTester; +import com.google.common.collect.testing.testers.CollectionRetainAllTester; +import com.google.common.collect.testing.testers.ListAddAllAtIndexTester; +import com.google.common.collect.testing.testers.ListAddAtIndexTester; +import com.google.common.collect.testing.testers.ListEqualsTester; +import com.google.common.collect.testing.testers.ListIndexOfTester; +import com.google.common.collect.testing.testers.ListLastIndexOfTester; +import com.google.common.collect.testing.testers.ListRetainAllTester; +import com.google.common.collect.testing.testers.ListSubListTester; +#else +import com.google.common.collect.testing.testers.ListSubListTester; +#endif + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; +import speiger.src.collections.PACKAGE.lists.IMMUTABLE_LIST; +import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; +import speiger.src.collections.PACKAGE.lists.LINKED_LIST; +import speiger.src.collections.PACKAGE.lists.COPY_ON_WRITE_LIST; +import speiger.src.collections.PACKAGE.lists.LIST; + +#if !TYPE_BOOLEAN +import speiger.src.collections.PACKAGE.utils.LISTS; +#endif +import speiger.src.testers.PACKAGE.builder.LIST_TEST_BUILDER; +import speiger.src.testers.PACKAGE.impl.COLLECTION_CONSTRUCTOR_TESTS; +import speiger.src.testers.PACKAGE.impl.SIMPLE_TEST_GENERATOR; +#if TYPE_OBJECT +import speiger.src.testers.PACKAGE.generators.TEST_LIST_GENERATOR; +#endif +import speiger.src.testers.utils.SpecialFeature; +import speiger.src.testers.utils.TestUtils; +#if TYPE_BOOLEAN +import speiger.src.testers.booleans.tests.collection.BooleanCollectionAddAllArrayTester; +import speiger.src.testers.booleans.tests.collection.BooleanCollectionAddAllTester; +import speiger.src.testers.booleans.tests.collection.BooleanCollectionAddTester; +import speiger.src.testers.booleans.tests.collection.BooleanCollectionContainsAllTester; +import speiger.src.testers.booleans.tests.collection.BooleanCollectionContainsTester; +import speiger.src.testers.booleans.tests.collection.BooleanCollectionIteratorTester; +import speiger.src.testers.booleans.tests.collection.BooleanCollectionRemoveAllTester; +import speiger.src.testers.booleans.tests.collection.BooleanCollectionRetainAllTester; +import speiger.src.testers.booleans.tests.list.BooleanListAddAllArrayAtIndexTester; +import speiger.src.testers.booleans.tests.list.BooleanListAddAllAtIndexTester; +import speiger.src.testers.booleans.tests.list.BooleanListAddAtIndexTester; +import speiger.src.testers.booleans.tests.list.BooleanListEqualsTester; +import speiger.src.testers.booleans.tests.list.BooleanListExtractElementsTester; +import speiger.src.testers.booleans.tests.list.BooleanListIndexOfTester; +import speiger.src.testers.booleans.tests.list.BooleanListLastIndexOfTester; +import speiger.src.testers.booleans.tests.list.BooleanListRemoveElementsTester; +import speiger.src.testers.booleans.tests.list.BooleanListRetainAllTester; +import speiger.src.testers.booleans.tests.list.BooleanListSubListTester; +#else +import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListSubListTester; +#endif + + +@SuppressWarnings("javadoc") +public class LIST_TESTS extends TestCase +{ + public static Test suite() { + TestSuite suite = new TestSuite("LISTS"); + suite(suite); + constructorSuite(suite); + System.out.println("Generated ["+suite.countTestCases()+"] Tests"); + return suite; + } + + public static void constructorSuite(TestSuite suite) { + TestSuite constructors = new TestSuite("Constructors"); + constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.ArrayList.class)); + constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.LinkedList.class)); + constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.CopyOnWriteArrayList.class)); + constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.ImmutableList.class)); + suite.addTest(constructors); + } + +#if TYPE_OBJECT + public static void suite(TestSuite suite) { + suite.addTest(listSuite("ARRAY_LIST", T -> new ARRAY_LISTBRACES(T), getFeatures(), -1)); + suite.addTest(listSuite("LINKED_LIST", T -> new LINKED_LISTBRACES(T), getFeatures(), -1)); + suite.addTest(copyOnWritelistSuite("COPY_ON_WRITE_LIST", T -> new COPY_ON_WRITE_LISTBRACES(T), getCopyOnWriteFeatures(), -1)); + suite.addTest(listSuite("IMMUTABLE_LIST", T -> new IMMUTABLE_LISTBRACES(T), getImmutableFeatures(), -1)); + suite.addTest(listSuite("Synchronized ARRAY_LIST", T -> new ARRAY_LISTBRACES(T).synchronize(), getFeatures(), -1)); + suite.addTest(listSuite("Unmodifiable ARRAY_LIST", T -> new ARRAY_LISTBRACES(T).unmodifiable(), getImmutableFeatures(), -1)); + suite.addTest(emptylistSuite("Empty LIST", T -> LISTS.empty(), getImmutableWrapperFeatures(), 0)); + suite.addTest(listSuite("Singleton LIST", T -> LISTS.singleton(T[0]), getImmutableWrapperFeatures(), 1)); + } + + private static Test listSuite(String name, Function factory, Collection> features, int size) { + return LIST_TEST_BUILDER.using((TEST_LIST_GENERATOR KEY_STRING_GENERIC_TYPE)new SIMPLE_TEST_GENERATOR.Lists KEY_STRING_GENERIC_TYPE(factory).setElements(createStrings())).setPrefixes(createPrefixes()).setSuffixes(createSuffixes()).named(name).withFeatures(getSizes(size)).withFeatures(features).createTestSuite(); + } + + private static Test copyOnWritelistSuite(String name, Function factory, Collection> features, int size) { + return LIST_TEST_BUILDER.using((TEST_LIST_GENERATOR KEY_STRING_GENERIC_TYPE)new SIMPLE_TEST_GENERATOR.Lists KEY_STRING_GENERIC_TYPE(factory).setElements(createStrings())).setPrefixes(createPrefixes()).setSuffixes(createSuffixes()).named(name).withFeatures(getSizes(size)).withFeatures(features).createTestSuite(); + } + + private static Test emptylistSuite(String name, Function factory, Collection> features, int size) { + return LIST_TEST_BUILDER.using((TEST_LIST_GENERATOR KEY_STRING_GENERIC_TYPE)new SIMPLE_TEST_GENERATOR.Lists KEY_STRING_GENERIC_TYPE(factory).setElements(createStrings())).setPrefixes(createPrefixes()).setSuffixes(createSuffixes()).named(name).withFeatures(getSizes(size)).suppressing(TestUtils.getSurpession(ListSubListTester.class)).suppressing(TestUtils.getSurpession(FILE_KEY_TYPEListSubListTester.class)).withFeatures(features).createTestSuite(); + } + + private static String[] createStrings() { + return new String[]{"a", "b", "c", "d", "e"}; + } + + private static String[] createPrefixes() { + return new String[]{"^", "_", "`"}; + } + + private static String[] createSuffixes() { + return new String[]{"f", "g", "h"}; + } + +#else if !TYPE_BOOLEAN + public static void suite(TestSuite suite) { + suite.addTest(listSuite("ARRAY_LIST", ARRAY_LIST::new, getFeatures(), -1)); + suite.addTest(listSuite("LINKED_LIST", LINKED_LIST::new, getFeatures(), -1)); + suite.addTest(copyOnWritelistSuite("COPY_ON_WRITE_LIST", COPY_ON_WRITE_LIST::new, getCopyOnWriteFeatures(), -1)); + suite.addTest(listSuite("IMMUTABLE_LIST", IMMUTABLE_LIST::new, getImmutableFeatures(), -1)); + suite.addTest(listSuite("Synchronized ARRAY_LIST", T -> new ARRAY_LISTBRACES(T).synchronize(), getFeatures(), -1)); + suite.addTest(listSuite("Unmodifiable ARRAY_LIST", T -> new ARRAY_LISTBRACES(T).unmodifiable(), getImmutableFeatures(), -1)); + suite.addTest(emptylistSuite("Empty LIST", T -> LISTS.empty(), getImmutableWrapperFeatures(), 0)); + suite.addTest(listSuite("Singleton LIST", T -> LISTS.singleton(T[0]), getImmutableWrapperFeatures(), 1)); + } + + private static Test listSuite(String name, Function factory, Collection> features, int size) { + return LIST_TEST_BUILDER.using(new SIMPLE_TEST_GENERATOR.ListsBRACES(factory)).named(name).withFeatures(getSizes(size)).withFeatures(features).createTestSuite(); + } + + private static Test copyOnWritelistSuite(String name, Function factory, Collection> features, int size) { + return LIST_TEST_BUILDER.using(new SIMPLE_TEST_GENERATOR.Lists KEY_STRING_GENERIC_TYPE(factory)).named(name).withFeatures(getSizes(size)).withFeatures(features).createTestSuite(); + } + + private static Test emptylistSuite(String name, Function factory, Collection> features, int size) { + return LIST_TEST_BUILDER.using(new SIMPLE_TEST_GENERATOR.ListsBRACES(factory)).named(name).withFeatures(getSizes(size)).suppressing(TestUtils.getSurpession(ListSubListTester.class)).suppressing(TestUtils.getSurpession(FILE_KEY_TYPEListSubListTester.class)).withFeatures(features).createTestSuite(); + } + +#else + public static void suite(TestSuite suite) { + listSuite(suite, "ARRAY_LIST", ARRAY_LIST::new, getFeatures(), false, -1); + listSuite(suite, "LINKED_LIST", LINKED_LIST::new, getFeatures(), false, -1); + copyOnWritelistSuite(suite, "COPY_ON_WRITE_LIST", COPY_ON_WRITE_LIST::new, getCopyOnWriteFeatures(), false, -1); + listSuite(suite, "IMMUTABLE_LIST", IMMUTABLE_LIST::new, getImmutableFeatures(), true, -1); + listSuite(suite, "Synchronized ARRAY_LIST", T -> new ARRAY_LISTBRACES(T).synchronize(), getFeatures(), false, -1); + listSuite(suite, "Unmodifiable ARRAY_LIST", T -> new ARRAY_LISTBRACES(T).unmodifiable(), getImmutableFeatures(), true, -1); + } + + private static void copyOnWritelistSuite(TestSuite suite, String name, Function factory, Collection> features, boolean immutable, int size) { + TestSuite data = new TestSuite(name); + Collection sizes = getSizes(size); +#ignore + if(sizes.contains(CollectionSize.ZERO) || sizes.contains(CollectionSize.ANY)) { +#endignore + data.addTest(LIST_TEST_BUILDER.using(new SIMPLE_TEST_GENERATOR.ListsBRACES(factory)) +#ignore + .named(name+" [collection size: zero]").withFeatures(CollectionSize.ZERO).withFeatures(features).suppressing(getSurpression(CollectionSize.ZERO, immutable)).createTestSuite()); +#endignore + } +#ignore + if(sizes.contains(CollectionSize.ONE) || sizes.contains(CollectionSize.ANY)) { +#endignore + data.addTest(LIST_TEST_BUILDER.using(new SIMPLE_TEST_GENERATOR.ListsBRACES(factory)) +#ignore + .named(name+" [collection size: one]").withFeatures(CollectionSize.ONE).withFeatures(features).suppressing(getSurpression(CollectionSize.ONE, immutable)).createTestSuite()); +#endignore + } +#ignore + if(sizes.contains(CollectionSize.SEVERAL) || sizes.contains(CollectionSize.ANY)) { +#endignore + data.addTest(LIST_TEST_BUILDER.using(new SIMPLE_TEST_GENERATOR.ListsBRACES(factory)) +#ignore + .named(name+" [collection size: several]").withFeatures(CollectionSize.SEVERAL).withFeatures(features).suppressing(getSurpression(CollectionSize.SEVERAL, immutable)).createTestSuite()); +#endignore + } + suite.addTest(data); + } + + private static void listSuite(TestSuite suite, String name, Function factory, Collection> features, boolean immutable, int size) { + TestSuite data = new TestSuite(name); + Collection sizes = getSizes(size); +#ignore + if(sizes.contains(CollectionSize.ZERO) || sizes.contains(CollectionSize.ANY)) { +#endignore + data.addTest(LIST_TEST_BUILDER.using(new SIMPLE_TEST_GENERATOR.ListsBRACES(factory)) +#ignore + .named(name+" [collection size: zero]").withFeatures(CollectionSize.ZERO).withFeatures(features).suppressing(getSurpression(CollectionSize.ZERO, immutable)).createTestSuite()); +#endignore + } +#ignore + if(sizes.contains(CollectionSize.ONE) || sizes.contains(CollectionSize.ANY)) { +#endignore + data.addTest(LIST_TEST_BUILDER.using(new SIMPLE_TEST_GENERATOR.ListsBRACES(factory)) +#ignore + .named(name+" [collection size: one]").withFeatures(CollectionSize.ONE).withFeatures(features).suppressing(getSurpression(CollectionSize.ONE, immutable)).createTestSuite()); +#endignore + } +#ignore + if(sizes.contains(CollectionSize.SEVERAL) || sizes.contains(CollectionSize.ANY)) { +#endignore + data.addTest(LIST_TEST_BUILDER.using(new SIMPLE_TEST_GENERATOR.ListsBRACES(factory)).named(name) +#ignore + .named(name+" [collection size: several]").withFeatures(CollectionSize.SEVERAL).withFeatures(features).suppressing(getSurpression(CollectionSize.SEVERAL, immutable)).createTestSuite()); +#endignore + } + suite.addTest(data); + } + + private static List getSurpression(CollectionSize size, boolean immutable) { + List list = new ArrayList<>(); + if(size == CollectionSize.ONE) { + TestUtils.getSurpession(list, CollectionRetainAllTester.class, "testRetainAll_disjointPreviouslyNonEmpty"); + if(immutable) { + TestUtils.getSurpession(list, CollectionAddAllTester.class, "testAddAll_unsupportedNonePresent"); + TestUtils.getSurpession(list, BooleanCollectionAddAllTester.class, "testAddAll_unsupportedNonePresent"); + TestUtils.getSurpession(list, BooleanCollectionAddAllArrayTester.class, "testAddAllArray_unsupportedNonePresent"); + } + } + else { + TestUtils.getSurpession(list, CollectionContainsAllTester.class, "testContainsAll_disjoint", "testContainsAll_partialOverlap"); + TestUtils.getSurpession(list, CollectionContainsTester.class, "testContains_no"); + TestUtils.getSurpession(list, CollectionIteratorTester.class, "testIterator_removeAffectsBackingCollection"); + TestUtils.getSurpession(list, CollectionRemoveAllTester.class, "testRemoveAll_nonePresent"); + TestUtils.getSurpession(list, CollectionRemoveTester.class, "testRemove_present", "testRemove_notPresent"); + TestUtils.getSurpession(list, CollectionRetainAllTester.class, "testRetainAll_disjointPreviouslyNonEmpty", "testRetainAll_containsDuplicatesSizeSeveral", "testRetainAll_partialOverlap"); + TestUtils.getSurpession(list, BooleanCollectionContainsAllTester.class, "testContainsAll_disjoint", "testContainsAll_partialOverlap"); + TestUtils.getSurpession(list, BooleanCollectionContainsTester.class, "testContains_no"); + TestUtils.getSurpession(list, BooleanCollectionIteratorTester.class, "testIterator_removeAffectsBackingCollection"); + TestUtils.getSurpession(list, BooleanCollectionRemoveAllTester.class, "testRemoveAll_nonePresentFetchRemoved", "testRemoveAll_someFetchRemovedElements", "testRemoveAll_nonePresent"); + TestUtils.getSurpession(list, BooleanCollectionRetainAllTester.class, "testRetainAllExtra_containsDuplicatesSizeSeveral", "testRetainAllExtra_partialOverlap", "testRetainAll_containsDuplicatesSizeSeveral", "testRetainAll_partialOverlap"); + TestUtils.getSurpession(list, ListAddAllAtIndexTester.class, "testAddAllAtIndex_negative", "testAddAllAtIndex_tooLarge"); + TestUtils.getSurpession(list, ListAddAtIndexTester.class, "testAddAtIndex_tooLarge", "testAddAtIndex_negative"); + TestUtils.getSurpession(list, ListEqualsTester.class, "testEquals_otherListWithDifferentElements"); + TestUtils.getSurpession(list, ListIndexOfTester.class, "testFind_no"); + TestUtils.getSurpession(list, ListLastIndexOfTester.class, "testLastIndexOf_duplicate", "testFind_no", "testFind_yes"); + TestUtils.getSurpession(list, ListRetainAllTester.class, "testRetainAll_duplicatesRemoved", "testRetainAll_countIgnored"); + TestUtils.getSurpession(list, ListSubListTester.class, "testSubList_lastIndexOf", "testSubList_contains", "testSubList_indexOf"); + TestUtils.getSurpession(list, BooleanListAddAllAtIndexTester.class, "testAddAllAtIndex_negative", "testAddAllAtIndex_tooLarge"); + TestUtils.getSurpession(list, BooleanListAddAllArrayAtIndexTester.class, "testAddAllArrayAtIndex_tooLarge", "testAddAllArrayAtIndex_negative"); + TestUtils.getSurpession(list, BooleanListAddAtIndexTester.class, "testAddAtIndex_tooLarge", "testAddAtIndex_negative"); + TestUtils.getSurpession(list, BooleanListEqualsTester.class, "testEquals_otherListWithDifferentElements"); + TestUtils.getSurpession(list, BooleanListExtractElementsTester.class, "testRemoveElements"); + TestUtils.getSurpession(list, BooleanListIndexOfTester.class, "testFind_no"); + TestUtils.getSurpession(list, BooleanListLastIndexOfTester.class, "testLastIndexOf_duplicate", "testFind_no", "testFind_yes"); + TestUtils.getSurpession(list, BooleanListRemoveElementsTester.class, "testRemoveElements"); + TestUtils.getSurpession(list, BooleanListRetainAllTester.class, "testRetainAll_duplicatesRemoved", "testRetainAll_countIgnored"); + TestUtils.getSurpession(list, BooleanListSubListTester.class, "testSubList_lastIndexOf", "testSubList_contains", "testSubList_indexOf"); + if(immutable) { + TestUtils.getSurpession(list, CollectionAddAllTester.class, "testAddAll_unsupportedNonePresent"); + TestUtils.getSurpession(list, CollectionAddTester.class, "testAdd_unsupportedNotPresent"); + TestUtils.getSurpession(list, CollectionRemoveTester.class, "testRemove_unsupportedNotPresent"); + TestUtils.getSurpession(list, BooleanCollectionAddAllTester.class, "testAddAll_unsupportedNonePresent"); + TestUtils.getSurpession(list, BooleanCollectionAddAllArrayTester.class, "testAddAllArray_unsupportedNonePresent"); + TestUtils.getSurpession(list, BooleanCollectionAddTester.class, "testAdd_unsupportedNotPresent"); + TestUtils.getSurpession(list, ListAddAllAtIndexTester.class, "testAddAllAtIndex_unsupportedSomePresent"); + TestUtils.getSurpession(list, ListAddAtIndexTester.class, "testAddAtIndex_unsupportedNotPresent"); + TestUtils.getSurpession(list, BooleanListAddAllAtIndexTester.class, "testAddAllAtIndex_unsupportedSomePresent"); + TestUtils.getSurpession(list, BooleanListAddAllArrayAtIndexTester.class, "testAddAllArrayAtIndex_unsupportedSomePresent"); + TestUtils.getSurpession(list, BooleanListAddAtIndexTester.class, "testAddAtIndex_unsupportedNotPresent"); + } + } + return list; + } + +#endif +#ignore + private static Collection getSizes(int size) { + switch(size) { + case 0: return Arrays.asList(CollectionSize.ZERO); + case 1: return Arrays.asList(CollectionSize.ONE); + case 2: return Arrays.asList(CollectionSize.ZERO, CollectionSize.ONE); + case 3: return Arrays.asList(CollectionSize.SEVERAL); + case 4: return Arrays.asList(CollectionSize.ZERO, CollectionSize.SEVERAL); + case 5: return Arrays.asList(CollectionSize.ONE, CollectionSize.SEVERAL); + default: return Arrays.asList(CollectionSize.ANY); + } + } + +#endignore + + private static Collection> getCopyOnWriteFeatures() { + +#if TYPE_OBJECT +#ignore + return Arrays.asList(ListFeature.SUPPORTS_SET, ListFeature.SUPPORTS_ADD_WITH_INDEX, ListFeature.SUPPORTS_REMOVE_WITH_INDEX, SpecialFeature.COPYING, CollectionFeature.ALLOWS_NULL_VALUES); +#endignore +#else +#ignore + return Arrays.asList(ListFeature.SUPPORTS_SET, ListFeature.SUPPORTS_ADD_WITH_INDEX, ListFeature.SUPPORTS_REMOVE_WITH_INDEX, SpecialFeature.COPYING); +#endignore +#endif + } + + private static Collection> getImmutableFeatures() { + +#if TYPE_OBJECT +#ignore + return Arrays.asList(SpecialFeature.COPYING, CollectionFeature.ALLOWS_NULL_VALUES); +#endignore +#else +#ignore + return Arrays.asList(SpecialFeature.COPYING); +#endignore +#endif + } + +#if !TYPE_BOOLEAN + private static Collection> getImmutableWrapperFeatures() { + +#if TYPE_OBJECT +#ignore + return Arrays.asList(SpecialFeature.COPYING, CollectionFeature.ALLOWS_NULL_VALUES, CollectionFeature.SUBSET_VIEW); +#endignore +#else +#ignore + return Arrays.asList(SpecialFeature.COPYING, CollectionFeature.SUBSET_VIEW); +#endignore +#endif + } + +#endif + private static Collection> getFeatures() { + +#if TYPE_OBJECT +#ignore + return Arrays.asList(ListFeature.GENERAL_PURPOSE, CollectionFeature.ALLOWS_NULL_VALUES, SpecialFeature.COPYING, SpecialFeature.ITERATOR_MODIFIABLE); +#endignore +#else +#ignore + return Arrays.asList(ListFeature.GENERAL_PURPOSE, SpecialFeature.COPYING, SpecialFeature.ITERATOR_MODIFIABLE); +#endignore +#endif + } } \ No newline at end of file diff --git a/src/builder/resources/speiger/assets/tests/templates/collections/QueueTests.template b/src/builder/resources/speiger/assets/tests/templates/collections/QueueTests.template index f9d0f4f..4497d77 100644 --- a/src/builder/resources/speiger/assets/tests/templates/collections/QueueTests.template +++ b/src/builder/resources/speiger/assets/tests/templates/collections/QueueTests.template @@ -1,89 +1,89 @@ -package speiger.src.tests.PACKAGE.collections; - -import java.util.Arrays; -import java.util.Collection; -#if TYPE_OBJECT -import java.util.Comparator; -#endif -import java.util.function.Function; - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.Feature; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; -import speiger.src.collections.PACKAGE.lists.LINKED_LIST; -import speiger.src.collections.PACKAGE.queues.ARRAY_FIFO_QUEUE; -import speiger.src.collections.PACKAGE.queues.ARRAY_PRIORITY_QUEUE; -import speiger.src.collections.PACKAGE.queues.HEAP_PRIORITY_QUEUE; -import speiger.src.collections.PACKAGE.queues.PRIORITY_QUEUE; -import speiger.src.testers.PACKAGE.builder.DEQUEUE_TEST_BUILDER; -import speiger.src.testers.PACKAGE.builder.QUEUE_TEST_BUILDER; -import speiger.src.testers.PACKAGE.impl.SIMPLE_QUEUE_TEST_GENERATOR; -import speiger.src.testers.utils.SpecialFeature; - -@SuppressWarnings("javadoc") -public class QUEUE_TESTS extends TestCase -{ - public static Test suite() { - TestSuite suite = new TestSuite("PRIORITY_QUEUES"); - suite(suite); - System.out.println("Generated ["+suite.countTestCases()+"] Tests"); - return suite; - } - - public static void suite(TestSuite suite) { - suite.addTest(dequeueSuite("ARRAY_FIFO_QUEUE", T -> new ARRAY_FIFO_QUEUEBRACES(T), getFeatures(), -1)); - suite.addTest(queueSuite("HEAP_PRIORITY_QUEUE", T -> new HEAP_PRIORITY_QUEUEBRACES(T), getFeatures(), -1)); -#if TYPE_OBJECT - suite.addTest(queueSuite("HEAP_PRIORITY_QUEUEComparator", T -> new HEAP_PRIORITY_QUEUEBRACES(T, Comparator.naturalOrder()), getFeatures(), -1)); - suite.addTest(queueSuite("ARRAY_PRIORITY_QUEUEComparator", T -> new ARRAY_PRIORITY_QUEUEBRACES(T, Comparator.naturalOrder()), getFeatures(), -1)); -#else - suite.addTest(queueSuite("HEAP_PRIORITY_QUEUEComparator", T -> new HEAP_PRIORITY_QUEUEBRACES(T, CLASS_TYPE::compare), getFeatures(), -1)); - suite.addTest(queueSuite("ARRAY_PRIORITY_QUEUEComparator", T -> new ARRAY_PRIORITY_QUEUEBRACES(T, CLASS_TYPE::compare), getFeatures(), -1)); -#endif - suite.addTest(queueSuite("ARRAY_PRIORITY_QUEUE", T -> new ARRAY_PRIORITY_QUEUEBRACES(T), getFeatures(), -1)); - suite.addTest(dequeueSuite("LINKED_LIST", T -> new LINKED_LISTBRACES(T), getFeatures(), -1)); - } - -#if TYPE_OBJECT - private static Test queueSuite(String name, Function> factory, Collection> features, int size) { - return QUEUE_TEST_BUILDER.using(new SIMPLE_QUEUE_TEST_GENERATOR(factory).setElements(createStrings())).named(name).withFeatures(features).withFeatures(getSizes(size)).createTestSuite(); - } - - private static Test dequeueSuite(String name, Function> factory, Collection> features, int size) { - return DEQUEUE_TEST_BUILDER.using(new SIMPLE_QUEUE_TEST_GENERATOR(factory).setElements(createStrings())).named(name).withFeatures(features).withFeatures(getSizes(size)).createTestSuite(); - } - - private static String[] createStrings() { - return new String[]{"a", "b", "c", "d", "e"}; - } - -#else - private static Test queueSuite(String name, Function factory, Collection> features, int size) { - return QUEUE_TEST_BUILDER.using(new SIMPLE_QUEUE_TEST_GENERATORBRACES(factory)).named(name).withFeatures(features).withFeatures(getSizes(size)).createTestSuite(); - } - - private static Test dequeueSuite(String name, Function factory, Collection> features, int size) { - return DEQUEUE_TEST_BUILDER.using(new SIMPLE_QUEUE_TEST_GENERATORBRACES(factory)).named(name).withFeatures(features).withFeatures(getSizes(size)).createTestSuite(); - } - -#endif - private static Collection getSizes(int size) { - switch(size) { - case 0: return Arrays.asList(CollectionSize.ZERO); - case 1: return Arrays.asList(CollectionSize.ONE); - case 2: return Arrays.asList(CollectionSize.ZERO, CollectionSize.ONE); - case 3: return Arrays.asList(CollectionSize.SEVERAL); - case 4: return Arrays.asList(CollectionSize.ZERO, CollectionSize.SEVERAL); - case 5: return Arrays.asList(CollectionSize.ONE, CollectionSize.SEVERAL); - default: return Arrays.asList(CollectionSize.ANY); - } - } - - private static Collection> getFeatures() { - return Arrays.asList(CollectionFeature.GENERAL_PURPOSE, SpecialFeature.COPYING, CollectionFeature.KNOWN_ORDER); - } -} +package speiger.src.tests.PACKAGE.collections; + +import java.util.Arrays; +import java.util.Collection; +#if TYPE_OBJECT +import java.util.Comparator; +#endif +import java.util.function.Function; + +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.Feature; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; +import speiger.src.collections.PACKAGE.lists.LINKED_LIST; +import speiger.src.collections.PACKAGE.queues.ARRAY_FIFO_QUEUE; +import speiger.src.collections.PACKAGE.queues.ARRAY_PRIORITY_QUEUE; +import speiger.src.collections.PACKAGE.queues.HEAP_PRIORITY_QUEUE; +import speiger.src.collections.PACKAGE.queues.PRIORITY_QUEUE; +import speiger.src.testers.PACKAGE.builder.DEQUEUE_TEST_BUILDER; +import speiger.src.testers.PACKAGE.builder.QUEUE_TEST_BUILDER; +import speiger.src.testers.PACKAGE.impl.SIMPLE_QUEUE_TEST_GENERATOR; +import speiger.src.testers.utils.SpecialFeature; + +@SuppressWarnings("javadoc") +public class QUEUE_TESTS extends TestCase +{ + public static Test suite() { + TestSuite suite = new TestSuite("PRIORITY_QUEUES"); + suite(suite); + System.out.println("Generated ["+suite.countTestCases()+"] Tests"); + return suite; + } + + public static void suite(TestSuite suite) { + suite.addTest(dequeueSuite("ARRAY_FIFO_QUEUE", T -> new ARRAY_FIFO_QUEUEBRACES(T), getFeatures(), -1)); + suite.addTest(queueSuite("HEAP_PRIORITY_QUEUE", T -> new HEAP_PRIORITY_QUEUEBRACES(T), getFeatures(), -1)); +#if TYPE_OBJECT + suite.addTest(queueSuite("HEAP_PRIORITY_QUEUEComparator", T -> new HEAP_PRIORITY_QUEUEBRACES(T, Comparator.naturalOrder()), getFeatures(), -1)); + suite.addTest(queueSuite("ARRAY_PRIORITY_QUEUEComparator", T -> new ARRAY_PRIORITY_QUEUEBRACES(T, Comparator.naturalOrder()), getFeatures(), -1)); +#else + suite.addTest(queueSuite("HEAP_PRIORITY_QUEUEComparator", T -> new HEAP_PRIORITY_QUEUEBRACES(T, CLASS_TYPE::compare), getFeatures(), -1)); + suite.addTest(queueSuite("ARRAY_PRIORITY_QUEUEComparator", T -> new ARRAY_PRIORITY_QUEUEBRACES(T, CLASS_TYPE::compare), getFeatures(), -1)); +#endif + suite.addTest(queueSuite("ARRAY_PRIORITY_QUEUE", T -> new ARRAY_PRIORITY_QUEUEBRACES(T), getFeatures(), -1)); + suite.addTest(dequeueSuite("LINKED_LIST", T -> new LINKED_LISTBRACES(T), getFeatures(), -1)); + } + +#if TYPE_OBJECT + private static Test queueSuite(String name, Function> factory, Collection> features, int size) { + return QUEUE_TEST_BUILDER.using(new SIMPLE_QUEUE_TEST_GENERATOR(factory).setElements(createStrings())).named(name).withFeatures(features).withFeatures(getSizes(size)).createTestSuite(); + } + + private static Test dequeueSuite(String name, Function> factory, Collection> features, int size) { + return DEQUEUE_TEST_BUILDER.using(new SIMPLE_QUEUE_TEST_GENERATOR(factory).setElements(createStrings())).named(name).withFeatures(features).withFeatures(getSizes(size)).createTestSuite(); + } + + private static String[] createStrings() { + return new String[]{"a", "b", "c", "d", "e"}; + } + +#else + private static Test queueSuite(String name, Function factory, Collection> features, int size) { + return QUEUE_TEST_BUILDER.using(new SIMPLE_QUEUE_TEST_GENERATORBRACES(factory)).named(name).withFeatures(features).withFeatures(getSizes(size)).createTestSuite(); + } + + private static Test dequeueSuite(String name, Function factory, Collection> features, int size) { + return DEQUEUE_TEST_BUILDER.using(new SIMPLE_QUEUE_TEST_GENERATORBRACES(factory)).named(name).withFeatures(features).withFeatures(getSizes(size)).createTestSuite(); + } + +#endif + private static Collection getSizes(int size) { + switch(size) { + case 0: return Arrays.asList(CollectionSize.ZERO); + case 1: return Arrays.asList(CollectionSize.ONE); + case 2: return Arrays.asList(CollectionSize.ZERO, CollectionSize.ONE); + case 3: return Arrays.asList(CollectionSize.SEVERAL); + case 4: return Arrays.asList(CollectionSize.ZERO, CollectionSize.SEVERAL); + case 5: return Arrays.asList(CollectionSize.ONE, CollectionSize.SEVERAL); + default: return Arrays.asList(CollectionSize.ANY); + } + } + + private static Collection> getFeatures() { + return Arrays.asList(CollectionFeature.GENERAL_PURPOSE, SpecialFeature.COPYING, CollectionFeature.KNOWN_ORDER); + } +} diff --git a/src/builder/resources/speiger/assets/tests/templates/collections/SetTests.template b/src/builder/resources/speiger/assets/tests/templates/collections/SetTests.template index c58cc82..1a953c3 100644 --- a/src/builder/resources/speiger/assets/tests/templates/collections/SetTests.template +++ b/src/builder/resources/speiger/assets/tests/templates/collections/SetTests.template @@ -1,196 +1,196 @@ -package speiger.src.tests.PACKAGE.collections; - -import java.util.Arrays; -import java.util.Collection; -import java.util.function.Function; -#if TYPE_OBJECT -import java.util.Comparator; -import java.util.Objects; -#endif - -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.SetFeature; -import com.google.common.collect.testing.features.Feature; -#if TYPE_OBJECT -import com.google.common.collect.testing.features.CollectionFeature; -#endif -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; -import speiger.src.collections.PACKAGE.sets.IMMUTABLE_HASH_SET; -import speiger.src.collections.PACKAGE.sets.AVL_TREE_SET; -import speiger.src.collections.PACKAGE.sets.ARRAY_SET; -import speiger.src.collections.PACKAGE.sets.LINKED_CUSTOM_HASH_SET; -import speiger.src.collections.PACKAGE.sets.LINKED_HASH_SET; -import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET; -import speiger.src.collections.PACKAGE.sets.CUSTOM_HASH_SET; -import speiger.src.collections.PACKAGE.sets.HASH_SET; -import speiger.src.collections.PACKAGE.sets.ORDERED_SET; -import speiger.src.collections.PACKAGE.sets.RB_TREE_SET; -import speiger.src.collections.PACKAGE.sets.SET; -import speiger.src.collections.PACKAGE.utils.SETS; -import speiger.src.collections.PACKAGE.utils.STRATEGY; -import speiger.src.testers.PACKAGE.builder.NAVIGABLE_SET_TEST_BUILDER; -import speiger.src.testers.PACKAGE.builder.ORDERED_SET_TEST_BUILDER; -import speiger.src.testers.PACKAGE.builder.SET_TEST_BUILDER; -#if TYPE_OBJECT -import speiger.src.testers.PACKAGE.generators.TEST_NAVIGABLE_SET_GENERATOR; -import speiger.src.testers.PACKAGE.generators.TEST_ORDERED_SET_GENERATOR; -import speiger.src.testers.PACKAGE.generators.TEST_SET_GENERATOR; -#endif -import speiger.src.testers.PACKAGE.impl.COLLECTION_CONSTRUCTOR_TESTS; -import speiger.src.testers.PACKAGE.impl.SIMPLE_TEST_GENERATOR; -#if TYPE_CHAR || TYPE_FLOAT || TYPE_DOUBLE || TYPE_OBJECT -import speiger.src.testers.PACKAGE.tests.collection.FILE_KEY_TYPECollectionIteratorTester; -#endif -import speiger.src.testers.utils.SpecialFeature; -#if TYPE_CHAR || TYPE_FLOAT || TYPE_DOUBLE || TYPE_OBJECT -import speiger.src.testers.utils.TestUtils; -#endif - -@SuppressWarnings("javadoc") -public class SET_TESTS extends TestCase -{ - public static Test suite() { - TestSuite suite = new TestSuite("SETS"); - suite(suite); - constructorSuite(suite); - System.out.println("Generated ["+suite.countTestCases()+"] Tests"); - return suite; - } - - public static void constructorSuite(TestSuite suite) { - TestSuite constructors = new TestSuite("Constructors"); - constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.HashSet.class)); - constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.LinkedHashSet.class)); - constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.CustomHashSet.class)); - constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.LinkedCustomHashSet.class)); - constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.ImmutableHashSet.class)); - constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.ArraySet.class)); - constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.RBTreeSet.class)); - constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.AVLTreeSet.class)); - constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.RBTreeSetComparator.class)); - constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.AVLTreeSetComparator.class)); - suite.addTest(constructors); - } - - public static void suite(TestSuite suite) { - suite.addTest(setSuite("HASH_SET", HASH_SET::new, getFeatures(), -1, true)); - suite.addTest(orderedSetSuite("LINKED_HASH_SET", LINKED_HASH_SET::new, getFeatures(), -1)); - suite.addTest(setSuite("CUSTOM_HASH_SET", T -> new CUSTOM_HASH_SETBRACES(T, HashStrategy.INSTANCE), getFeatures(), -1, true)); - suite.addTest(orderedSetSuite("LINKED_CUSTOM_HASH_SET", T -> new LINKED_CUSTOM_HASH_SETBRACES(T, HashStrategy.INSTANCE), getFeatures(), -1)); - suite.addTest(orderedSetSuite("IMMUTABLE_HASH_SET", IMMUTABLE_HASH_SET::new, getImmutableFeatures(), -1)); - suite.addTest(orderedSetSuite("ARRAY_SET", ARRAY_SET::new, getFeatures(), -1)); -#if TYPE_OBJECT - suite.addTest(navigableSetSuite("RB_TREE_SET", RB_TREE_SET::new, getFeatures(), false, -1)); - suite.addTest(navigableSetSuite("AVL_TREE_SET", AVL_TREE_SET::new, getFeatures(), false, -1)); - suite.addTest(navigableSetSuite("RB_TREE_SET_Null", T -> new RB_TREE_SET<>(T, Comparator.nullsFirst(Comparator.naturalOrder())), getFeatures(), true, -1)); - suite.addTest(navigableSetSuite("AVL_TREE_SET_Null", T -> new AVL_TREE_SET<>(T, Comparator.nullsFirst(Comparator.naturalOrder())), getFeatures(), true, -1)); - suite.addTest(navigableSetSuite("Synchronized RB_TREE_SET", T -> new RB_TREE_SET<>(T).synchronize(), getFeatures(), false, -1)); - suite.addTest(navigableSetSuite("Unmodifiable RB_TREE_SET", T -> new RB_TREE_SET<>(T).unmodifiable(), getImmutableFeatures(), false, -1)); -#else - suite.addTest(navigableSetSuite("RB_TREE_SET", RB_TREE_SET::new, getFeatures(), -1)); - suite.addTest(navigableSetSuite("AVL_TREE_SET", AVL_TREE_SET::new, getFeatures(), -1)); - suite.addTest(navigableSetSuite("Synchronized RB_TREE_SET", T -> new RB_TREE_SET(T).synchronize(), getFeatures(), -1)); - suite.addTest(navigableSetSuite("Unmodifiable RB_TREE_SET", T -> new RB_TREE_SET(T).unmodifiable(), getImmutableFeatures(), -1)); -#endif - suite.addTest(setSuite("Empty SET", T -> SETS.empty(), getImmutableFeatures(), 0, false)); - suite.addTest(setSuite("Singleton SET", T -> SETS.singleton(T[0]), getImmutableFeatures(), 1, false)); - suite.addTest(orderedSetSuite("Synchronized LINKED_HASH_SET", T -> new LINKED_HASH_SETBRACES(T).synchronize(), getFeatures(), -1)); - suite.addTest(orderedSetSuite("Unmodifiable LINKED_HASH_SET", T -> new LINKED_HASH_SETBRACES(T).unmodifiable(), getImmutableFeatures(), -1)); - } - -#if TYPE_OBJECT - public static Test setSuite(String name, Function> factory, Collection> features, int size, boolean sorted) { - SET_TEST_BUILDER builder = (SET_TEST_BUILDER)SET_TEST_BUILDER.using((TEST_SET_GENERATOR)new SIMPLE_TEST_GENERATOR.SetsBRACES(factory).setElements(createSortedStrings())).named(name) -#ignore - .withFeatures(getSizes(size)).withFeatures(CollectionFeature.ALLOWS_NULL_VALUES).withFeatures(features); -#endignore - if(sorted) builder.suppressing(TestUtils.getSurpession(FILE_KEY_TYPECollectionIteratorTester.class, "testIterator_unknownOrderRemoveSupported")); - return builder.createTestSuite(); - } - - public static Test orderedSetSuite(String name, Function> factory, Collection> features, int size) { - return ORDERED_SET_TEST_BUILDER.using((TEST_ORDERED_SET_GENERATOR)new SIMPLE_TEST_GENERATOR.OrderedSetsBRACES(factory).setElements(createSortedStrings())).named(name) -#ignore - .withFeatures(getSizes(size)).withFeatures(CollectionFeature.ALLOWS_NULL_VALUES).withFeatures(features).createTestSuite(); -#endignore - } - - public static Test navigableSetSuite(String name, Function> factory, Collection> features, boolean nullValues, int size) { - NAVIGABLE_SET_TEST_BUILDER builder = (NAVIGABLE_SET_TEST_BUILDER)NAVIGABLE_SET_TEST_BUILDER.using((TEST_NAVIGABLE_SET_GENERATOR)new SIMPLE_TEST_GENERATOR.NavigableSetsBRACES(factory).setElements(createSortedStrings())).named(name) -#ignore - .withFeatures(getSizes(size)).withFeatures(features); - if(nullValues) builder.withFeatures(CollectionFeature.ALLOWS_NULL_VALUES); -#endignore - return builder.createTestSuite(); - } - - private static class HashStrategy implements STRATEGY { - static final HashStrategy INSTANCE = new HashStrategy(); - @Override - public int hashCode(String o) { return KEY_TO_HASH(o); } - @Override - public boolean equals(String key, String value) { return KEY_EQUALS(key, value); } - } - - private static String[] createSortedStrings() { - return new String[]{"a", "b", "c", "d", "e", "!! a", "!! b", "~~ a", "~~ b"}; - } -#else - public static Test setSuite(String name, Function factory, Collection> features, int size, boolean sorted) { - SET_TEST_BUILDER builder = (SET_TEST_BUILDER)SET_TEST_BUILDER.using(new SIMPLE_TEST_GENERATOR.SetsBRACES(factory)).named(name) -#ignore - .withFeatures(getSizes(size)).withFeatures(features); -#endignore -#if TYPE_CHAR || TYPE_FLOAT || TYPE_DOUBLE - if(sorted) builder.suppressing(TestUtils.getSurpession(FILE_KEY_TYPECollectionIteratorTester.class, "testIterator_unknownOrderRemoveSupported")); -#endif - return builder.createTestSuite(); - } - - public static Test orderedSetSuite(String name, Function factory, Collection> features, int size) { - return ORDERED_SET_TEST_BUILDER.using(new SIMPLE_TEST_GENERATOR.OrderedSetsBRACES(factory)).named(name) -#ignore - .withFeatures(getSizes(size)).withFeatures(features).createTestSuite(); -#endignore - } - - public static Test navigableSetSuite(String name, Function factory, Collection> features, int size) { - return NAVIGABLE_SET_TEST_BUILDER.using(new SIMPLE_TEST_GENERATOR.NavigableSetsBRACES(factory)).named(name) -#ignore - .withFeatures(getSizes(size)).withFeatures(features).createTestSuite(); -#endignore - } - - private static class HashStrategy implements STRATEGY KEY_GENERIC_TYPE { - static final HashStrategy INSTANCE = new HashStrategy(); - @Override - public int hashCode(KEY_TYPE o) { return KEY_TO_HASH(o); } - @Override - public boolean equals(KEY_TYPE key, KEY_TYPE value) { return KEY_EQUALS(key, value); } - } -#endif - -#ignore - private static Collection getSizes(int size) { - switch(size) { - case 0: return Arrays.asList(CollectionSize.ZERO); - case 1: return Arrays.asList(CollectionSize.ONE); - case 2: return Arrays.asList(CollectionSize.ZERO, CollectionSize.ONE); - case 3: return Arrays.asList(CollectionSize.SEVERAL); - case 4: return Arrays.asList(CollectionSize.ZERO, CollectionSize.SEVERAL); - case 5: return Arrays.asList(CollectionSize.ONE, CollectionSize.SEVERAL); - default: return Arrays.asList(CollectionSize.ANY); - } - } - - private static Collection> getImmutableFeatures() { - return Arrays.asList(SpecialFeature.COPYING); - } - - private static Collection> getFeatures() { - return Arrays.asList(SetFeature.GENERAL_PURPOSE, SpecialFeature.COPYING, SpecialFeature.MODIFIABLE); - } -#endignore -} +package speiger.src.tests.PACKAGE.collections; + +import java.util.Arrays; +import java.util.Collection; +import java.util.function.Function; +#if TYPE_OBJECT +import java.util.Comparator; +import java.util.Objects; +#endif + +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.SetFeature; +import com.google.common.collect.testing.features.Feature; +#if TYPE_OBJECT +import com.google.common.collect.testing.features.CollectionFeature; +#endif +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; +import speiger.src.collections.PACKAGE.sets.IMMUTABLE_HASH_SET; +import speiger.src.collections.PACKAGE.sets.AVL_TREE_SET; +import speiger.src.collections.PACKAGE.sets.ARRAY_SET; +import speiger.src.collections.PACKAGE.sets.LINKED_CUSTOM_HASH_SET; +import speiger.src.collections.PACKAGE.sets.LINKED_HASH_SET; +import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET; +import speiger.src.collections.PACKAGE.sets.CUSTOM_HASH_SET; +import speiger.src.collections.PACKAGE.sets.HASH_SET; +import speiger.src.collections.PACKAGE.sets.ORDERED_SET; +import speiger.src.collections.PACKAGE.sets.RB_TREE_SET; +import speiger.src.collections.PACKAGE.sets.SET; +import speiger.src.collections.PACKAGE.utils.SETS; +import speiger.src.collections.PACKAGE.utils.STRATEGY; +import speiger.src.testers.PACKAGE.builder.NAVIGABLE_SET_TEST_BUILDER; +import speiger.src.testers.PACKAGE.builder.ORDERED_SET_TEST_BUILDER; +import speiger.src.testers.PACKAGE.builder.SET_TEST_BUILDER; +#if TYPE_OBJECT +import speiger.src.testers.PACKAGE.generators.TEST_NAVIGABLE_SET_GENERATOR; +import speiger.src.testers.PACKAGE.generators.TEST_ORDERED_SET_GENERATOR; +import speiger.src.testers.PACKAGE.generators.TEST_SET_GENERATOR; +#endif +import speiger.src.testers.PACKAGE.impl.COLLECTION_CONSTRUCTOR_TESTS; +import speiger.src.testers.PACKAGE.impl.SIMPLE_TEST_GENERATOR; +#if TYPE_CHAR || TYPE_FLOAT || TYPE_DOUBLE || TYPE_OBJECT +import speiger.src.testers.PACKAGE.tests.collection.FILE_KEY_TYPECollectionIteratorTester; +#endif +import speiger.src.testers.utils.SpecialFeature; +#if TYPE_CHAR || TYPE_FLOAT || TYPE_DOUBLE || TYPE_OBJECT +import speiger.src.testers.utils.TestUtils; +#endif + +@SuppressWarnings("javadoc") +public class SET_TESTS extends TestCase +{ + public static Test suite() { + TestSuite suite = new TestSuite("SETS"); + suite(suite); + constructorSuite(suite); + System.out.println("Generated ["+suite.countTestCases()+"] Tests"); + return suite; + } + + public static void constructorSuite(TestSuite suite) { + TestSuite constructors = new TestSuite("Constructors"); + constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.HashSet.class)); + constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.LinkedHashSet.class)); + constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.CustomHashSet.class)); + constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.LinkedCustomHashSet.class)); + constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.ImmutableHashSet.class)); + constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.ArraySet.class)); + constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.RBTreeSet.class)); + constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.AVLTreeSet.class)); + constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.RBTreeSetComparator.class)); + constructors.addTest(new TestSuite(COLLECTION_CONSTRUCTOR_TESTS.AVLTreeSetComparator.class)); + suite.addTest(constructors); + } + + public static void suite(TestSuite suite) { + suite.addTest(setSuite("HASH_SET", HASH_SET::new, getFeatures(), -1, true)); + suite.addTest(orderedSetSuite("LINKED_HASH_SET", LINKED_HASH_SET::new, getFeatures(), -1)); + suite.addTest(setSuite("CUSTOM_HASH_SET", T -> new CUSTOM_HASH_SETBRACES(T, HashStrategy.INSTANCE), getFeatures(), -1, true)); + suite.addTest(orderedSetSuite("LINKED_CUSTOM_HASH_SET", T -> new LINKED_CUSTOM_HASH_SETBRACES(T, HashStrategy.INSTANCE), getFeatures(), -1)); + suite.addTest(orderedSetSuite("IMMUTABLE_HASH_SET", IMMUTABLE_HASH_SET::new, getImmutableFeatures(), -1)); + suite.addTest(orderedSetSuite("ARRAY_SET", ARRAY_SET::new, getFeatures(), -1)); +#if TYPE_OBJECT + suite.addTest(navigableSetSuite("RB_TREE_SET", RB_TREE_SET::new, getFeatures(), false, -1)); + suite.addTest(navigableSetSuite("AVL_TREE_SET", AVL_TREE_SET::new, getFeatures(), false, -1)); + suite.addTest(navigableSetSuite("RB_TREE_SET_Null", T -> new RB_TREE_SET<>(T, Comparator.nullsFirst(Comparator.naturalOrder())), getFeatures(), true, -1)); + suite.addTest(navigableSetSuite("AVL_TREE_SET_Null", T -> new AVL_TREE_SET<>(T, Comparator.nullsFirst(Comparator.naturalOrder())), getFeatures(), true, -1)); + suite.addTest(navigableSetSuite("Synchronized RB_TREE_SET", T -> new RB_TREE_SET<>(T).synchronize(), getFeatures(), false, -1)); + suite.addTest(navigableSetSuite("Unmodifiable RB_TREE_SET", T -> new RB_TREE_SET<>(T).unmodifiable(), getImmutableFeatures(), false, -1)); +#else + suite.addTest(navigableSetSuite("RB_TREE_SET", RB_TREE_SET::new, getFeatures(), -1)); + suite.addTest(navigableSetSuite("AVL_TREE_SET", AVL_TREE_SET::new, getFeatures(), -1)); + suite.addTest(navigableSetSuite("Synchronized RB_TREE_SET", T -> new RB_TREE_SET(T).synchronize(), getFeatures(), -1)); + suite.addTest(navigableSetSuite("Unmodifiable RB_TREE_SET", T -> new RB_TREE_SET(T).unmodifiable(), getImmutableFeatures(), -1)); +#endif + suite.addTest(setSuite("Empty SET", T -> SETS.empty(), getImmutableFeatures(), 0, false)); + suite.addTest(setSuite("Singleton SET", T -> SETS.singleton(T[0]), getImmutableFeatures(), 1, false)); + suite.addTest(orderedSetSuite("Synchronized LINKED_HASH_SET", T -> new LINKED_HASH_SETBRACES(T).synchronize(), getFeatures(), -1)); + suite.addTest(orderedSetSuite("Unmodifiable LINKED_HASH_SET", T -> new LINKED_HASH_SETBRACES(T).unmodifiable(), getImmutableFeatures(), -1)); + } + +#if TYPE_OBJECT + public static Test setSuite(String name, Function> factory, Collection> features, int size, boolean sorted) { + SET_TEST_BUILDER builder = (SET_TEST_BUILDER)SET_TEST_BUILDER.using((TEST_SET_GENERATOR)new SIMPLE_TEST_GENERATOR.SetsBRACES(factory).setElements(createSortedStrings())).named(name) +#ignore + .withFeatures(getSizes(size)).withFeatures(CollectionFeature.ALLOWS_NULL_VALUES).withFeatures(features); +#endignore + if(sorted) builder.suppressing(TestUtils.getSurpession(FILE_KEY_TYPECollectionIteratorTester.class, "testIterator_unknownOrderRemoveSupported")); + return builder.createTestSuite(); + } + + public static Test orderedSetSuite(String name, Function> factory, Collection> features, int size) { + return ORDERED_SET_TEST_BUILDER.using((TEST_ORDERED_SET_GENERATOR)new SIMPLE_TEST_GENERATOR.OrderedSetsBRACES(factory).setElements(createSortedStrings())).named(name) +#ignore + .withFeatures(getSizes(size)).withFeatures(CollectionFeature.ALLOWS_NULL_VALUES).withFeatures(features).createTestSuite(); +#endignore + } + + public static Test navigableSetSuite(String name, Function> factory, Collection> features, boolean nullValues, int size) { + NAVIGABLE_SET_TEST_BUILDER builder = (NAVIGABLE_SET_TEST_BUILDER)NAVIGABLE_SET_TEST_BUILDER.using((TEST_NAVIGABLE_SET_GENERATOR)new SIMPLE_TEST_GENERATOR.NavigableSetsBRACES(factory).setElements(createSortedStrings())).named(name) +#ignore + .withFeatures(getSizes(size)).withFeatures(features); + if(nullValues) builder.withFeatures(CollectionFeature.ALLOWS_NULL_VALUES); +#endignore + return builder.createTestSuite(); + } + + private static class HashStrategy implements STRATEGY { + static final HashStrategy INSTANCE = new HashStrategy(); + @Override + public int hashCode(String o) { return KEY_TO_HASH(o); } + @Override + public boolean equals(String key, String value) { return KEY_EQUALS(key, value); } + } + + private static String[] createSortedStrings() { + return new String[]{"a", "b", "c", "d", "e", "!! a", "!! b", "~~ a", "~~ b"}; + } +#else + public static Test setSuite(String name, Function factory, Collection> features, int size, boolean sorted) { + SET_TEST_BUILDER builder = (SET_TEST_BUILDER)SET_TEST_BUILDER.using(new SIMPLE_TEST_GENERATOR.SetsBRACES(factory)).named(name) +#ignore + .withFeatures(getSizes(size)).withFeatures(features); +#endignore +#if TYPE_CHAR || TYPE_FLOAT || TYPE_DOUBLE + if(sorted) builder.suppressing(TestUtils.getSurpession(FILE_KEY_TYPECollectionIteratorTester.class, "testIterator_unknownOrderRemoveSupported")); +#endif + return builder.createTestSuite(); + } + + public static Test orderedSetSuite(String name, Function factory, Collection> features, int size) { + return ORDERED_SET_TEST_BUILDER.using(new SIMPLE_TEST_GENERATOR.OrderedSetsBRACES(factory)).named(name) +#ignore + .withFeatures(getSizes(size)).withFeatures(features).createTestSuite(); +#endignore + } + + public static Test navigableSetSuite(String name, Function factory, Collection> features, int size) { + return NAVIGABLE_SET_TEST_BUILDER.using(new SIMPLE_TEST_GENERATOR.NavigableSetsBRACES(factory)).named(name) +#ignore + .withFeatures(getSizes(size)).withFeatures(features).createTestSuite(); +#endignore + } + + private static class HashStrategy implements STRATEGY KEY_GENERIC_TYPE { + static final HashStrategy INSTANCE = new HashStrategy(); + @Override + public int hashCode(KEY_TYPE o) { return KEY_TO_HASH(o); } + @Override + public boolean equals(KEY_TYPE key, KEY_TYPE value) { return KEY_EQUALS(key, value); } + } +#endif + +#ignore + private static Collection getSizes(int size) { + switch(size) { + case 0: return Arrays.asList(CollectionSize.ZERO); + case 1: return Arrays.asList(CollectionSize.ONE); + case 2: return Arrays.asList(CollectionSize.ZERO, CollectionSize.ONE); + case 3: return Arrays.asList(CollectionSize.SEVERAL); + case 4: return Arrays.asList(CollectionSize.ZERO, CollectionSize.SEVERAL); + case 5: return Arrays.asList(CollectionSize.ONE, CollectionSize.SEVERAL); + default: return Arrays.asList(CollectionSize.ANY); + } + } + + private static Collection> getImmutableFeatures() { + return Arrays.asList(SpecialFeature.COPYING); + } + + private static Collection> getFeatures() { + return Arrays.asList(SetFeature.GENERAL_PURPOSE, SpecialFeature.COPYING, SpecialFeature.MODIFIABLE); + } +#endignore +} diff --git a/src/builder/resources/speiger/assets/tests/templates/maps/MapTests.template b/src/builder/resources/speiger/assets/tests/templates/maps/MapTests.template index 0a6f725..1a5639d 100644 --- a/src/builder/resources/speiger/assets/tests/templates/maps/MapTests.template +++ b/src/builder/resources/speiger/assets/tests/templates/maps/MapTests.template @@ -1,395 +1,395 @@ -package speiger.src.tests.PACKAGE.maps; - -#if VALUE_BOOLEAN -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; -#endif -import java.util.Arrays; -import java.util.Collection; -#if TYPE_OBJECT -import java.util.Objects; -#endif -import java.util.function.BiFunction; - -#if TYPE_OBJECT -import com.google.common.collect.testing.AnEnum; -#endif -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; -import com.google.common.collect.testing.features.Feature; -#if VALUE_BOOLEAN -import com.google.common.collect.testing.testers.CollectionAddAllTester; -import com.google.common.collect.testing.testers.CollectionAddTester; -import com.google.common.collect.testing.testers.CollectionContainsAllTester; -import com.google.common.collect.testing.testers.CollectionContainsTester; -import com.google.common.collect.testing.testers.CollectionRetainAllTester; -#endif - - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; -import speiger.src.collections.PACKAGE.maps.impl.concurrent.CONCURRENT_HASH_MAP; -import speiger.src.collections.PACKAGE.maps.impl.hash.LINKED_HASH_MAP; -import speiger.src.collections.PACKAGE.maps.impl.immutable.IMMUTABLE_HASH_MAP; -import speiger.src.collections.PACKAGE.maps.impl.customHash.CUSTOM_HASH_MAP; -import speiger.src.collections.PACKAGE.maps.impl.customHash.LINKED_CUSTOM_HASH_MAP; -import speiger.src.collections.PACKAGE.maps.impl.hash.HASH_MAP; -import speiger.src.collections.PACKAGE.maps.impl.misc.ARRAY_MAP; -#if TYPE_OBJECT -import speiger.src.collections.PACKAGE.maps.impl.misc.ENUM_MAP; -import speiger.src.collections.PACKAGE.maps.impl.misc.LINKED_ENUM_MAP; -#endif -import speiger.src.collections.PACKAGE.maps.impl.tree.AVL_TREE_MAP; -import speiger.src.collections.PACKAGE.maps.impl.tree.RB_TREE_MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP; -import speiger.src.collections.PACKAGE.maps.interfaces.SORTED_MAP; -import speiger.src.collections.PACKAGE.utils.STRATEGY; -import speiger.src.collections.PACKAGE.utils.maps.MAPS; -import speiger.src.testers.PACKAGE.builder.maps.MAP_TEST_BUILDER; -import speiger.src.testers.PACKAGE.builder.maps.ORDERED_MAP_TEST_BUILDER; -import speiger.src.testers.PACKAGE.builder.maps.NAVIGABLE_MAP_TEST_BUILDER; -import speiger.src.testers.PACKAGE.impl.maps.SIMPLE_MAP_TEST_GENERATOR; -import speiger.src.testers.PACKAGE.impl.maps.MAP_CONSTRUCTOR_TESTS; -import speiger.src.testers.PACKAGE.impl.maps.SIMPLE_TEST_MAP; -import speiger.src.testers.objects.tests.collection.ObjectCollectionIteratorTester; -#if !SAME_TYPE && !TYPE_OBJECT -import speiger.src.testers.PACKAGE.tests.collection.FILE_KEY_TYPECollectionIteratorTester; -#endif -#if !VALUE_OBJECT -import speiger.src.testers.VALUE_PACKAGE.tests.collection.FILE_VALUE_TYPECollectionIteratorTester; -#endif -import speiger.src.testers.PACKAGE.tests.misc.PAIRTester; -#if VALUE_BOOLEAN -import speiger.src.testers.booleans.tests.collection.BooleanCollectionAddAllArrayTester; -import speiger.src.testers.booleans.tests.collection.BooleanCollectionAddAllTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapContainsValueTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeIfAbsentTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeIfPresentTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapSupplyIfAbsentTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapMergeTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutIfAbsentTester; -import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapRemoveEntryTester; -#endif -import speiger.src.testers.utils.SpecialFeature; -import speiger.src.testers.utils.TestUtils; - -@SuppressWarnings("javadoc") -public class MAP_TESTS extends TestCase -{ - public static Test suite() { - TestSuite suite = new TestSuite("MAPS"); - suite(suite); - constructorSuite(suite); - pairSuite(suite); - System.out.println("Generated ["+suite.countTestCases()+"] Tests"); - return suite; - } - - public static void pairSuite(TestSuite suite) { - TestSuite pairs = new TestSuite("Constructors"); - pairs.addTest(new TestSuite(PAIRTester.Mutable.class)); - pairs.addTest(new TestSuite(PAIRTester.Immutable.class)); - suite.addTest(pairs); - } - - public static void constructorSuite(TestSuite suite) { - TestSuite constructors = new TestSuite("Constructors"); - constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.HashMap.class)); - constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.LinkedHashMap.class)); -#if TYPE_OBJECT - constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.EnumMap.class)); - constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.LinkedEnumMap.class)); -#endif - constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.CustomHashMap.class)); - constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.LinkedCustomHashMap.class)); - constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.ImmutableHashMap.class)); - constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.ConcurrentHashMap.class)); - constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.ArrayMap.class)); - constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.RBTreeMap.class)); - constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.AVLTreeMap.class)); - constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.RBTreeMapComparator.class)); - constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.AVLTreeMapComparator.class)); - - constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.HashMapBuilder.class)); - constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.LinkedHashMapBuilder.class)); - constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.CustomHashMapBuilder.class)); - constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.LinkedCustomHashMapBuilder.class)); - constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.ImmutableHashMapBuilder.class)); - constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.ConcurrentHashMapBuilder.class)); - constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.ArrayMapBuilder.class)); - constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.RBTreeMapBuilder.class)); - constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.AVLTreeMapBuilder.class)); - constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.RBTreeMapComparatorBuilder.class)); - constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.AVLTreeMapComparatorBuilder.class)); - suite.addTest(constructors); - } - - public static void suite(TestSuite suite) { - suite.addTest(mapSuite("HASH_MAP", HASH_MAP::new, getFeatures(), -1, true)); - suite.addTest(orderedMapSuite("LINKED_HASH_MAP", LINKED_HASH_MAP::new, getFeatures(), -1)); - suite.addTest(orderedMapSuite("IMMUTABLE_HASH_MAP", IMMUTABLE_HASH_MAP::new, getImmutableFeatures(), -1)); -#if TYPE_OBJECT - suite.addTest(enumMapSuite("ENUM_MAP", ENUM_MAP::new, getFeatures(), 5)); - suite.addTest(enumOrderedMapSuite("LINKED_ENUM_MAP", (K, V) -> K.length <= 0 ? new LINKED_ENUM_MAP<>(AnEnum.class) : new LINKED_ENUM_MAP<>(K, V), getFeatures(), 5)); -#endif - suite.addTest(mapSuite("CUSTOM_HASH_MAP", (K, V) -> new CUSTOM_HASH_MAPKV_BRACES(K, V, HashStrategy.INSTANCE), getFeatures(), -1, true)); - suite.addTest(orderedMapSuite("LINKED_CUSTOM_HASH_MAP", (K, V) -> new LINKED_CUSTOM_HASH_MAPKV_BRACES(K, V, HashStrategy.INSTANCE), getFeatures(), -1)); - suite.addTest(orderedMapSuite("ARRAY_MAP", ARRAY_MAP::new, getFeatures(), -1)); - suite.addTest(concurrentMapSuite("CONCURRENT_HASH_MAP", CONCURRENT_HASH_MAP::new, getFeatures(), 2)); - suite.addTest(concurrentMapSuite("CONCURRENT_HASH_MAP", CONCURRENT_HASH_MAP::new, getFeatures(), 3)); - suite.addTest(navigableMapSuite("RB_TREE_MAP", RB_TREE_MAP::new, getFeatures(), -1)); - suite.addTest(navigableMapSuite("AVL_TREE_MAP", AVL_TREE_MAP::new, getFeatures(), -1)); - suite.addTest(navigableMapSuite("SynchronizedRB_TREE_MAP", (K, V) -> new RB_TREE_MAPKV_BRACES(K, V).synchronize(), getLimitedFeatures(), -1)); - suite.addTest(navigableMapSuite("UnmodifiableRB_TREE_MAP", (K, V) -> new RB_TREE_MAPKV_BRACES(K, V).unmodifiable(), getLimitedImmutableFeatures(), -1)); - suite.addTest(orderedMapSuite("SynchronizedORDERED_MAP", (K, V) -> new LINKED_HASH_MAPKV_BRACES(K, V).synchronize(), getFeatures(), -1)); - suite.addTest(orderedMapSuite("UnmodifiableORDERED_MAP", (K, V) -> new LINKED_HASH_MAPKV_BRACES(K, V).unmodifiable(), getImmutableFeatures(), -1)); - suite.addTest(mapSuite("EmptyMAP", (K, V) -> MAPS.empty(), getEmptyFeatures(), 0, false)); - suite.addTest(mapSuite("SingletonMAP", (K, V) -> MAPS.singleton(K[0], V[0]), getEmptyFeatures(), 1, false)); - suite.addTest(mapSuite("AbstractMap", SIMPLE_TEST_MAP::new, getTestFeatures(), -1, false)); - } - -#if TYPE_OBJECT -#if VALUE_OBJECT - private static Test enumMapSuite(String name, BiFunction> factory, Collection> features, int size) { - SIMPLE_MAP_TEST_GENERATOR.Maps generator = new SIMPLE_MAP_TEST_GENERATOR.Maps(factory); - MAP_TEST_BUILDER builder = MAP_TEST_BUILDER.using(generator); -#else - private static Test enumMapSuite(String name, BiFunction> factory, Collection> features, int size) { - SIMPLE_MAP_TEST_GENERATOR.Maps generator = new SIMPLE_MAP_TEST_GENERATOR.Maps(factory); - MAP_TEST_BUILDER builder = MAP_TEST_BUILDER.using(generator); -#endif - builder.shouldBlockKeys(true); - generator.setKeys(AnEnum.values()); -#if VALUE_OBJECT - generator.setValues(createValues()); -#ignore - builder.withFeatures(MapFeature.ALLOWS_NULL_VALUES); -#endignore -#if SAME_TYPE - builder.withFeatures(MapFeature.ALLOWS_NULL_ENTRY_QUERIES); -#endif -#endif - builder.withFeatures(getSizes(size)).withFeatures(features); -#if VALUE_BOOLEAN - builder.suppressing(getSuppression()); -#endif - return builder.named(name).createTestSuite(); -} - -#if VALUE_OBJECT - private static Test enumOrderedMapSuite(String name, BiFunction> factory, Collection> features, int size) { - SIMPLE_MAP_TEST_GENERATOR.OrderedMaps generator = new SIMPLE_MAP_TEST_GENERATOR.OrderedMaps(factory); - ORDERED_MAP_TEST_BUILDER builder = ORDERED_MAP_TEST_BUILDER.using(generator); -#else - private static Test enumOrderedMapSuite(String name, BiFunction> factory, Collection> features, int size) { - SIMPLE_MAP_TEST_GENERATOR.OrderedMaps generator = new SIMPLE_MAP_TEST_GENERATOR.OrderedMaps(factory); - ORDERED_MAP_TEST_BUILDER builder = ORDERED_MAP_TEST_BUILDER.using(generator); -#endif - generator.setKeys(AnEnum.values()); -#if VALUE_OBJECT - generator.setValues(createValues()); -#ignore - builder.withFeatures(MapFeature.ALLOWS_NULL_VALUES); -#endignore -#if SAME_TYPE - builder.withFeatures(MapFeature.ALLOWS_NULL_ENTRY_QUERIES); -#endif -#endif - builder.withFeatures(getSizes(size)).withFeatures(features); -#if VALUE_BOOLEAN - builder.suppressing(getSuppression()); -#endif - return builder.named(name).createTestSuite(); - } - -#endif - - private static Test mapSuite(String name, BiFunction factory, Collection> features, int size, boolean sorted) { - SIMPLE_MAP_TEST_GENERATOR.Maps KEY_VALUE_STRING_GENERIC_TYPE generator = new SIMPLE_MAP_TEST_GENERATOR.Maps KEY_VALUE_STRING_GENERIC_TYPE(factory); - MAP_TEST_BUILDER KEY_VALUE_STRING_GENERIC_TYPE builder = MAP_TEST_BUILDER.using(generator); - builder.shouldBlockKeys(sorted); -#if TYPE_OBJECT - generator.setKeys(createKeys()); -#ignore - builder.withFeatures(MapFeature.ALLOWS_NULL_KEYS); -#endignore -#endif -#if VALUE_OBJECT - generator.setValues(createValues()); -#ignore - builder.withFeatures(MapFeature.ALLOWS_NULL_VALUES); -#endignore -#if SAME_TYPE - builder.withFeatures(MapFeature.ALLOWS_NULL_ENTRY_QUERIES); -#endif -#endif - builder.withFeatures(getSizes(size)).withFeatures(features); -#if VALUE_BOOLEAN - builder.suppressing(getSuppression()); -#endif - return builder.named(name).createTestSuite(); - } - - private static Test concurrentMapSuite(String name, BiFunction factory, Collection> features, int size) { - SIMPLE_MAP_TEST_GENERATOR.Maps KEY_VALUE_STRING_GENERIC_TYPE generator = new SIMPLE_MAP_TEST_GENERATOR.Maps KEY_VALUE_STRING_GENERIC_TYPE(factory); - MAP_TEST_BUILDER KEY_VALUE_STRING_GENERIC_TYPE builder = MAP_TEST_BUILDER.using(generator); -#if TYPE_OBJECT - generator.setKeys(createKeys()); -#ignore - builder.withFeatures(MapFeature.ALLOWS_NULL_KEYS); -#endignore -#endif -#if VALUE_OBJECT - generator.setValues(createValues()); -#ignore - builder.withFeatures(MapFeature.ALLOWS_NULL_VALUES); -#endignore -#if SAME_TYPE - builder.withFeatures(MapFeature.ALLOWS_NULL_ENTRY_QUERIES); -#endif -#endif - builder.withFeatures(getSizes(size)).withFeatures(features); - if(size == 3) { - builder.suppressing(TestUtils.getSurpession(ObjectCollectionIteratorTester.class, "testIterator_unknownOrderRemoveSupported")); - builder.suppressing(TestUtils.getSurpession(FILE_KEY_TYPECollectionIteratorTester.class, "testIterator_unknownOrderRemoveSupported")); - builder.suppressing(TestUtils.getSurpession(FILE_VALUE_TYPECollectionIteratorTester.class, "testIterator_unknownOrderRemoveSupported")); - } -#if VALUE_BOOLEAN - builder.suppressing(getSuppression()); -#endif - return builder.named(name).createTestSuite(); - } - - private static Test orderedMapSuite(String name, BiFunction factory, Collection> features, int size) { - SIMPLE_MAP_TEST_GENERATOR.OrderedMaps KEY_VALUE_STRING_GENERIC_TYPE generator = new SIMPLE_MAP_TEST_GENERATOR.OrderedMaps KEY_VALUE_STRING_GENERIC_TYPE(factory); - ORDERED_MAP_TEST_BUILDER KEY_VALUE_STRING_GENERIC_TYPE builder = ORDERED_MAP_TEST_BUILDER.using(generator); -#if TYPE_OBJECT - generator.setKeys(createKeys()); -#ignore - builder.withFeatures(MapFeature.ALLOWS_NULL_KEYS); -#endignore -#endif -#if VALUE_OBJECT - generator.setValues(createValues()); -#ignore - builder.withFeatures(MapFeature.ALLOWS_NULL_VALUES); -#endignore -#if SAME_TYPE - builder.withFeatures(MapFeature.ALLOWS_NULL_ENTRY_QUERIES); -#endif -#endif - builder.withFeatures(getSizes(size)).withFeatures(features); -#if VALUE_BOOLEAN - builder.suppressing(getSuppression()); -#endif - return builder.named(name).createTestSuite(); - } - - private static Test navigableMapSuite(String name, BiFunction factory, Collection> features, int size) { - SIMPLE_MAP_TEST_GENERATOR.SortedMaps KEY_VALUE_STRING_GENERIC_TYPE generator = new SIMPLE_MAP_TEST_GENERATOR.SortedMaps KEY_VALUE_STRING_GENERIC_TYPE(factory); - NAVIGABLE_MAP_TEST_BUILDER KEY_VALUE_STRING_GENERIC_TYPE builder = NAVIGABLE_MAP_TEST_BUILDER.using(generator); -#if TYPE_OBJECT - generator.setKeys(createKeys()); -#endif -#if VALUE_OBJECT - generator.setValues(createValues()); -#ignore - builder.withFeatures(MapFeature.ALLOWS_NULL_VALUES); -#endignore -#if SAME_TYPE - builder.withFeatures(MapFeature.ALLOWS_NULL_ENTRY_QUERIES); -#endif -#endif - builder.withFeatures(getSizes(size)).withFeatures(features); -#if VALUE_BOOLEAN - builder.suppressing(getSuppression()); -#endif - return builder.named(name).createTestSuite(); - } - - private static class HashStrategy implements STRATEGY KEY_STRING_GENERIC_TYPE { - static final HashStrategy INSTANCE = new HashStrategy(); - @Override - public int hashCode(KEY_STRING_TYPE o) { return KEY_TO_HASH(o); } - @Override - public boolean equals(KEY_STRING_TYPE key, KEY_STRING_TYPE value) { return KEY_EQUALS(key, value); } - } - -#ignore - private static Collection getSizes(int size) { - switch(size) { - case 0: return Arrays.asList(CollectionSize.ZERO); - case 1: return Arrays.asList(CollectionSize.ONE); - case 2: return Arrays.asList(CollectionSize.ZERO, CollectionSize.ONE); - case 3: return Arrays.asList(CollectionSize.SEVERAL); - case 4: return Arrays.asList(CollectionSize.ZERO, CollectionSize.SEVERAL); - case 5: return Arrays.asList(CollectionSize.ONE, CollectionSize.SEVERAL); - default: return Arrays.asList(CollectionSize.ANY); - } - } - - private static Collection> getFeatures() { - return Arrays.asList(MapFeature.GENERAL_PURPOSE, CollectionFeature.SUPPORTS_ITERATOR_REMOVE, SpecialFeature.COPYING, SpecialFeature.MODIFIABLE); - } - - private static Collection> getTestFeatures() { - return Arrays.asList(MapFeature.GENERAL_PURPOSE, CollectionFeature.SUPPORTS_ITERATOR_REMOVE, SpecialFeature.MODIFIABLE); - } - - private static Collection> getEmptyFeatures() { - return Arrays.asList(SpecialFeature.CHILDREN_COPY); - } - - private static Collection> getImmutableFeatures() { - return Arrays.asList(SpecialFeature.COPYING); - } - - private static Collection> getLimitedFeatures() { - return Arrays.asList(MapFeature.GENERAL_PURPOSE, CollectionFeature.SUPPORTS_ITERATOR_REMOVE, SpecialFeature.SUBMAP, SpecialFeature.DESCENDING, SpecialFeature.COPYING, SpecialFeature.MODIFIABLE); - } - - private static Collection> getLimitedImmutableFeatures() { - return Arrays.asList(SpecialFeature.SUBMAP, SpecialFeature.DESCENDING, SpecialFeature.COPYING); - } -#endignore -#if TYPE_OBJECT - private static String[] createKeys() { - return new String[]{"one", "two", "three", "four", "five", "!! a", "!! b", "~~ a", "~~ b"}; - } - -#endif -#if VALUE_OBJECT - private static String[] createValues() { - return new String[]{"January", "February", "March", "April", "May", "below view", "below view", "above view", "above view"}; - } - -#endif -#if VALUE_BOOLEAN - public static List getSuppression() { - List list = new ArrayList<>(); - TestUtils.getSurpession(list, FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeTester.class, "testCompute_absentToPresent", "testCompute_presentToPresent"); - TestUtils.getSurpession(list, FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeIfAbsentTester.class, "testComputeIfAbsent_supportedAbsent"); - TestUtils.getSurpession(list, FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeIfPresentTester.class, "testCompute_presentToPresent", "testComputeIfPresent_supportedPresent"); - TestUtils.getSurpession(list, FILE_KEY_TYPE2FILE_VALUE_TYPEMapSupplyIfAbsentTester.class, "testSupplyIfAbsent_supportedAbsent"); - TestUtils.getSurpession(list, FILE_KEY_TYPE2FILE_VALUE_TYPEMapMergeTester.class, "testAbsent"); - TestUtils.getSurpession(list, FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutIfAbsentTester.class, "testPutIfAbsent_supportedAbsent"); - TestUtils.getSurpession(list, FILE_KEY_TYPE2FILE_VALUE_TYPEMapRemoveEntryTester.class, "testRemove_supportedPresentLastWrongValue", "testRemoveObject_supportedPresentLastWrongValue"); - - TestUtils.getSurpession(list, CollectionAddTester.class, "testAdd_unsupportedNotPresent"); - TestUtils.getSurpession(list, CollectionAddAllTester.class, "testAddAll_unsupportedNonePresent"); - TestUtils.getSurpession(list, FILE_KEY_TYPE2FILE_VALUE_TYPEMapContainsValueTester.class, "testContains_no"); - TestUtils.getSurpession(list, CollectionContainsTester.class, "testContains_no"); - TestUtils.getSurpession(list, CollectionRetainAllTester.class, "testRetainAll_disjointPreviouslyNonEmpty"); - TestUtils.getSurpession(list, BooleanCollectionAddAllTester.class, "testAddAll_unsupportedNonePresent"); - TestUtils.getSurpession(list, BooleanCollectionAddAllArrayTester.class, "testAddAllArray_unsupportedNonePresent"); - TestUtils.getSurpession(list, CollectionContainsAllTester.class, "testContainsAll_disjoint", "testContainsAll_partialOverlap"); - return list; - } - -#endif -} +package speiger.src.tests.PACKAGE.maps; + +#if VALUE_BOOLEAN +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +#endif +import java.util.Arrays; +import java.util.Collection; +#if TYPE_OBJECT +import java.util.Objects; +#endif +import java.util.function.BiFunction; + +#if TYPE_OBJECT +import com.google.common.collect.testing.AnEnum; +#endif +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; +import com.google.common.collect.testing.features.Feature; +#if VALUE_BOOLEAN +import com.google.common.collect.testing.testers.CollectionAddAllTester; +import com.google.common.collect.testing.testers.CollectionAddTester; +import com.google.common.collect.testing.testers.CollectionContainsAllTester; +import com.google.common.collect.testing.testers.CollectionContainsTester; +import com.google.common.collect.testing.testers.CollectionRetainAllTester; +#endif + + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; +import speiger.src.collections.PACKAGE.maps.impl.concurrent.CONCURRENT_HASH_MAP; +import speiger.src.collections.PACKAGE.maps.impl.hash.LINKED_HASH_MAP; +import speiger.src.collections.PACKAGE.maps.impl.immutable.IMMUTABLE_HASH_MAP; +import speiger.src.collections.PACKAGE.maps.impl.customHash.CUSTOM_HASH_MAP; +import speiger.src.collections.PACKAGE.maps.impl.customHash.LINKED_CUSTOM_HASH_MAP; +import speiger.src.collections.PACKAGE.maps.impl.hash.HASH_MAP; +import speiger.src.collections.PACKAGE.maps.impl.misc.ARRAY_MAP; +#if TYPE_OBJECT +import speiger.src.collections.PACKAGE.maps.impl.misc.ENUM_MAP; +import speiger.src.collections.PACKAGE.maps.impl.misc.LINKED_ENUM_MAP; +#endif +import speiger.src.collections.PACKAGE.maps.impl.tree.AVL_TREE_MAP; +import speiger.src.collections.PACKAGE.maps.impl.tree.RB_TREE_MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP; +import speiger.src.collections.PACKAGE.maps.interfaces.SORTED_MAP; +import speiger.src.collections.PACKAGE.utils.STRATEGY; +import speiger.src.collections.PACKAGE.utils.maps.MAPS; +import speiger.src.testers.PACKAGE.builder.maps.MAP_TEST_BUILDER; +import speiger.src.testers.PACKAGE.builder.maps.ORDERED_MAP_TEST_BUILDER; +import speiger.src.testers.PACKAGE.builder.maps.NAVIGABLE_MAP_TEST_BUILDER; +import speiger.src.testers.PACKAGE.impl.maps.SIMPLE_MAP_TEST_GENERATOR; +import speiger.src.testers.PACKAGE.impl.maps.MAP_CONSTRUCTOR_TESTS; +import speiger.src.testers.PACKAGE.impl.maps.SIMPLE_TEST_MAP; +import speiger.src.testers.objects.tests.collection.ObjectCollectionIteratorTester; +#if !SAME_TYPE && !TYPE_OBJECT +import speiger.src.testers.PACKAGE.tests.collection.FILE_KEY_TYPECollectionIteratorTester; +#endif +#if !VALUE_OBJECT +import speiger.src.testers.VALUE_PACKAGE.tests.collection.FILE_VALUE_TYPECollectionIteratorTester; +#endif +import speiger.src.testers.PACKAGE.tests.misc.PAIRTester; +#if VALUE_BOOLEAN +import speiger.src.testers.booleans.tests.collection.BooleanCollectionAddAllArrayTester; +import speiger.src.testers.booleans.tests.collection.BooleanCollectionAddAllTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapContainsValueTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeIfAbsentTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeIfPresentTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapSupplyIfAbsentTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapMergeTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutIfAbsentTester; +import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEMapRemoveEntryTester; +#endif +import speiger.src.testers.utils.SpecialFeature; +import speiger.src.testers.utils.TestUtils; + +@SuppressWarnings("javadoc") +public class MAP_TESTS extends TestCase +{ + public static Test suite() { + TestSuite suite = new TestSuite("MAPS"); + suite(suite); + constructorSuite(suite); + pairSuite(suite); + System.out.println("Generated ["+suite.countTestCases()+"] Tests"); + return suite; + } + + public static void pairSuite(TestSuite suite) { + TestSuite pairs = new TestSuite("Constructors"); + pairs.addTest(new TestSuite(PAIRTester.Mutable.class)); + pairs.addTest(new TestSuite(PAIRTester.Immutable.class)); + suite.addTest(pairs); + } + + public static void constructorSuite(TestSuite suite) { + TestSuite constructors = new TestSuite("Constructors"); + constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.HashMap.class)); + constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.LinkedHashMap.class)); +#if TYPE_OBJECT + constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.EnumMap.class)); + constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.LinkedEnumMap.class)); +#endif + constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.CustomHashMap.class)); + constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.LinkedCustomHashMap.class)); + constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.ImmutableHashMap.class)); + constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.ConcurrentHashMap.class)); + constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.ArrayMap.class)); + constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.RBTreeMap.class)); + constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.AVLTreeMap.class)); + constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.RBTreeMapComparator.class)); + constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.AVLTreeMapComparator.class)); + + constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.HashMapBuilder.class)); + constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.LinkedHashMapBuilder.class)); + constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.CustomHashMapBuilder.class)); + constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.LinkedCustomHashMapBuilder.class)); + constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.ImmutableHashMapBuilder.class)); + constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.ConcurrentHashMapBuilder.class)); + constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.ArrayMapBuilder.class)); + constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.RBTreeMapBuilder.class)); + constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.AVLTreeMapBuilder.class)); + constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.RBTreeMapComparatorBuilder.class)); + constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.AVLTreeMapComparatorBuilder.class)); + suite.addTest(constructors); + } + + public static void suite(TestSuite suite) { + suite.addTest(mapSuite("HASH_MAP", HASH_MAP::new, getFeatures(), -1, true)); + suite.addTest(orderedMapSuite("LINKED_HASH_MAP", LINKED_HASH_MAP::new, getFeatures(), -1)); + suite.addTest(orderedMapSuite("IMMUTABLE_HASH_MAP", IMMUTABLE_HASH_MAP::new, getImmutableFeatures(), -1)); +#if TYPE_OBJECT + suite.addTest(enumMapSuite("ENUM_MAP", ENUM_MAP::new, getFeatures(), 5)); + suite.addTest(enumOrderedMapSuite("LINKED_ENUM_MAP", (K, V) -> K.length <= 0 ? new LINKED_ENUM_MAP<>(AnEnum.class) : new LINKED_ENUM_MAP<>(K, V), getFeatures(), 5)); +#endif + suite.addTest(mapSuite("CUSTOM_HASH_MAP", (K, V) -> new CUSTOM_HASH_MAPKV_BRACES(K, V, HashStrategy.INSTANCE), getFeatures(), -1, true)); + suite.addTest(orderedMapSuite("LINKED_CUSTOM_HASH_MAP", (K, V) -> new LINKED_CUSTOM_HASH_MAPKV_BRACES(K, V, HashStrategy.INSTANCE), getFeatures(), -1)); + suite.addTest(orderedMapSuite("ARRAY_MAP", ARRAY_MAP::new, getFeatures(), -1)); + suite.addTest(concurrentMapSuite("CONCURRENT_HASH_MAP", CONCURRENT_HASH_MAP::new, getFeatures(), 2)); + suite.addTest(concurrentMapSuite("CONCURRENT_HASH_MAP", CONCURRENT_HASH_MAP::new, getFeatures(), 3)); + suite.addTest(navigableMapSuite("RB_TREE_MAP", RB_TREE_MAP::new, getFeatures(), -1)); + suite.addTest(navigableMapSuite("AVL_TREE_MAP", AVL_TREE_MAP::new, getFeatures(), -1)); + suite.addTest(navigableMapSuite("SynchronizedRB_TREE_MAP", (K, V) -> new RB_TREE_MAPKV_BRACES(K, V).synchronize(), getLimitedFeatures(), -1)); + suite.addTest(navigableMapSuite("UnmodifiableRB_TREE_MAP", (K, V) -> new RB_TREE_MAPKV_BRACES(K, V).unmodifiable(), getLimitedImmutableFeatures(), -1)); + suite.addTest(orderedMapSuite("SynchronizedORDERED_MAP", (K, V) -> new LINKED_HASH_MAPKV_BRACES(K, V).synchronize(), getFeatures(), -1)); + suite.addTest(orderedMapSuite("UnmodifiableORDERED_MAP", (K, V) -> new LINKED_HASH_MAPKV_BRACES(K, V).unmodifiable(), getImmutableFeatures(), -1)); + suite.addTest(mapSuite("EmptyMAP", (K, V) -> MAPS.empty(), getEmptyFeatures(), 0, false)); + suite.addTest(mapSuite("SingletonMAP", (K, V) -> MAPS.singleton(K[0], V[0]), getEmptyFeatures(), 1, false)); + suite.addTest(mapSuite("AbstractMap", SIMPLE_TEST_MAP::new, getTestFeatures(), -1, false)); + } + +#if TYPE_OBJECT +#if VALUE_OBJECT + private static Test enumMapSuite(String name, BiFunction> factory, Collection> features, int size) { + SIMPLE_MAP_TEST_GENERATOR.Maps generator = new SIMPLE_MAP_TEST_GENERATOR.Maps(factory); + MAP_TEST_BUILDER builder = MAP_TEST_BUILDER.using(generator); +#else + private static Test enumMapSuite(String name, BiFunction> factory, Collection> features, int size) { + SIMPLE_MAP_TEST_GENERATOR.Maps generator = new SIMPLE_MAP_TEST_GENERATOR.Maps(factory); + MAP_TEST_BUILDER builder = MAP_TEST_BUILDER.using(generator); +#endif + builder.shouldBlockKeys(true); + generator.setKeys(AnEnum.values()); +#if VALUE_OBJECT + generator.setValues(createValues()); +#ignore + builder.withFeatures(MapFeature.ALLOWS_NULL_VALUES); +#endignore +#if SAME_TYPE + builder.withFeatures(MapFeature.ALLOWS_NULL_ENTRY_QUERIES); +#endif +#endif + builder.withFeatures(getSizes(size)).withFeatures(features); +#if VALUE_BOOLEAN + builder.suppressing(getSuppression()); +#endif + return builder.named(name).createTestSuite(); +} + +#if VALUE_OBJECT + private static Test enumOrderedMapSuite(String name, BiFunction> factory, Collection> features, int size) { + SIMPLE_MAP_TEST_GENERATOR.OrderedMaps generator = new SIMPLE_MAP_TEST_GENERATOR.OrderedMaps(factory); + ORDERED_MAP_TEST_BUILDER builder = ORDERED_MAP_TEST_BUILDER.using(generator); +#else + private static Test enumOrderedMapSuite(String name, BiFunction> factory, Collection> features, int size) { + SIMPLE_MAP_TEST_GENERATOR.OrderedMaps generator = new SIMPLE_MAP_TEST_GENERATOR.OrderedMaps(factory); + ORDERED_MAP_TEST_BUILDER builder = ORDERED_MAP_TEST_BUILDER.using(generator); +#endif + generator.setKeys(AnEnum.values()); +#if VALUE_OBJECT + generator.setValues(createValues()); +#ignore + builder.withFeatures(MapFeature.ALLOWS_NULL_VALUES); +#endignore +#if SAME_TYPE + builder.withFeatures(MapFeature.ALLOWS_NULL_ENTRY_QUERIES); +#endif +#endif + builder.withFeatures(getSizes(size)).withFeatures(features); +#if VALUE_BOOLEAN + builder.suppressing(getSuppression()); +#endif + return builder.named(name).createTestSuite(); + } + +#endif + + private static Test mapSuite(String name, BiFunction factory, Collection> features, int size, boolean sorted) { + SIMPLE_MAP_TEST_GENERATOR.Maps KEY_VALUE_STRING_GENERIC_TYPE generator = new SIMPLE_MAP_TEST_GENERATOR.Maps KEY_VALUE_STRING_GENERIC_TYPE(factory); + MAP_TEST_BUILDER KEY_VALUE_STRING_GENERIC_TYPE builder = MAP_TEST_BUILDER.using(generator); + builder.shouldBlockKeys(sorted); +#if TYPE_OBJECT + generator.setKeys(createKeys()); +#ignore + builder.withFeatures(MapFeature.ALLOWS_NULL_KEYS); +#endignore +#endif +#if VALUE_OBJECT + generator.setValues(createValues()); +#ignore + builder.withFeatures(MapFeature.ALLOWS_NULL_VALUES); +#endignore +#if SAME_TYPE + builder.withFeatures(MapFeature.ALLOWS_NULL_ENTRY_QUERIES); +#endif +#endif + builder.withFeatures(getSizes(size)).withFeatures(features); +#if VALUE_BOOLEAN + builder.suppressing(getSuppression()); +#endif + return builder.named(name).createTestSuite(); + } + + private static Test concurrentMapSuite(String name, BiFunction factory, Collection> features, int size) { + SIMPLE_MAP_TEST_GENERATOR.Maps KEY_VALUE_STRING_GENERIC_TYPE generator = new SIMPLE_MAP_TEST_GENERATOR.Maps KEY_VALUE_STRING_GENERIC_TYPE(factory); + MAP_TEST_BUILDER KEY_VALUE_STRING_GENERIC_TYPE builder = MAP_TEST_BUILDER.using(generator); +#if TYPE_OBJECT + generator.setKeys(createKeys()); +#ignore + builder.withFeatures(MapFeature.ALLOWS_NULL_KEYS); +#endignore +#endif +#if VALUE_OBJECT + generator.setValues(createValues()); +#ignore + builder.withFeatures(MapFeature.ALLOWS_NULL_VALUES); +#endignore +#if SAME_TYPE + builder.withFeatures(MapFeature.ALLOWS_NULL_ENTRY_QUERIES); +#endif +#endif + builder.withFeatures(getSizes(size)).withFeatures(features); + if(size == 3) { + builder.suppressing(TestUtils.getSurpession(ObjectCollectionIteratorTester.class, "testIterator_unknownOrderRemoveSupported")); + builder.suppressing(TestUtils.getSurpession(FILE_KEY_TYPECollectionIteratorTester.class, "testIterator_unknownOrderRemoveSupported")); + builder.suppressing(TestUtils.getSurpession(FILE_VALUE_TYPECollectionIteratorTester.class, "testIterator_unknownOrderRemoveSupported")); + } +#if VALUE_BOOLEAN + builder.suppressing(getSuppression()); +#endif + return builder.named(name).createTestSuite(); + } + + private static Test orderedMapSuite(String name, BiFunction factory, Collection> features, int size) { + SIMPLE_MAP_TEST_GENERATOR.OrderedMaps KEY_VALUE_STRING_GENERIC_TYPE generator = new SIMPLE_MAP_TEST_GENERATOR.OrderedMaps KEY_VALUE_STRING_GENERIC_TYPE(factory); + ORDERED_MAP_TEST_BUILDER KEY_VALUE_STRING_GENERIC_TYPE builder = ORDERED_MAP_TEST_BUILDER.using(generator); +#if TYPE_OBJECT + generator.setKeys(createKeys()); +#ignore + builder.withFeatures(MapFeature.ALLOWS_NULL_KEYS); +#endignore +#endif +#if VALUE_OBJECT + generator.setValues(createValues()); +#ignore + builder.withFeatures(MapFeature.ALLOWS_NULL_VALUES); +#endignore +#if SAME_TYPE + builder.withFeatures(MapFeature.ALLOWS_NULL_ENTRY_QUERIES); +#endif +#endif + builder.withFeatures(getSizes(size)).withFeatures(features); +#if VALUE_BOOLEAN + builder.suppressing(getSuppression()); +#endif + return builder.named(name).createTestSuite(); + } + + private static Test navigableMapSuite(String name, BiFunction factory, Collection> features, int size) { + SIMPLE_MAP_TEST_GENERATOR.SortedMaps KEY_VALUE_STRING_GENERIC_TYPE generator = new SIMPLE_MAP_TEST_GENERATOR.SortedMaps KEY_VALUE_STRING_GENERIC_TYPE(factory); + NAVIGABLE_MAP_TEST_BUILDER KEY_VALUE_STRING_GENERIC_TYPE builder = NAVIGABLE_MAP_TEST_BUILDER.using(generator); +#if TYPE_OBJECT + generator.setKeys(createKeys()); +#endif +#if VALUE_OBJECT + generator.setValues(createValues()); +#ignore + builder.withFeatures(MapFeature.ALLOWS_NULL_VALUES); +#endignore +#if SAME_TYPE + builder.withFeatures(MapFeature.ALLOWS_NULL_ENTRY_QUERIES); +#endif +#endif + builder.withFeatures(getSizes(size)).withFeatures(features); +#if VALUE_BOOLEAN + builder.suppressing(getSuppression()); +#endif + return builder.named(name).createTestSuite(); + } + + private static class HashStrategy implements STRATEGY KEY_STRING_GENERIC_TYPE { + static final HashStrategy INSTANCE = new HashStrategy(); + @Override + public int hashCode(KEY_STRING_TYPE o) { return KEY_TO_HASH(o); } + @Override + public boolean equals(KEY_STRING_TYPE key, KEY_STRING_TYPE value) { return KEY_EQUALS(key, value); } + } + +#ignore + private static Collection getSizes(int size) { + switch(size) { + case 0: return Arrays.asList(CollectionSize.ZERO); + case 1: return Arrays.asList(CollectionSize.ONE); + case 2: return Arrays.asList(CollectionSize.ZERO, CollectionSize.ONE); + case 3: return Arrays.asList(CollectionSize.SEVERAL); + case 4: return Arrays.asList(CollectionSize.ZERO, CollectionSize.SEVERAL); + case 5: return Arrays.asList(CollectionSize.ONE, CollectionSize.SEVERAL); + default: return Arrays.asList(CollectionSize.ANY); + } + } + + private static Collection> getFeatures() { + return Arrays.asList(MapFeature.GENERAL_PURPOSE, CollectionFeature.SUPPORTS_ITERATOR_REMOVE, SpecialFeature.COPYING, SpecialFeature.MODIFIABLE); + } + + private static Collection> getTestFeatures() { + return Arrays.asList(MapFeature.GENERAL_PURPOSE, CollectionFeature.SUPPORTS_ITERATOR_REMOVE, SpecialFeature.MODIFIABLE); + } + + private static Collection> getEmptyFeatures() { + return Arrays.asList(SpecialFeature.CHILDREN_COPY); + } + + private static Collection> getImmutableFeatures() { + return Arrays.asList(SpecialFeature.COPYING); + } + + private static Collection> getLimitedFeatures() { + return Arrays.asList(MapFeature.GENERAL_PURPOSE, CollectionFeature.SUPPORTS_ITERATOR_REMOVE, SpecialFeature.SUBMAP, SpecialFeature.DESCENDING, SpecialFeature.COPYING, SpecialFeature.MODIFIABLE); + } + + private static Collection> getLimitedImmutableFeatures() { + return Arrays.asList(SpecialFeature.SUBMAP, SpecialFeature.DESCENDING, SpecialFeature.COPYING); + } +#endignore +#if TYPE_OBJECT + private static String[] createKeys() { + return new String[]{"one", "two", "three", "four", "five", "!! a", "!! b", "~~ a", "~~ b"}; + } + +#endif +#if VALUE_OBJECT + private static String[] createValues() { + return new String[]{"January", "February", "March", "April", "May", "below view", "below view", "above view", "above view"}; + } + +#endif +#if VALUE_BOOLEAN + public static List getSuppression() { + List list = new ArrayList<>(); + TestUtils.getSurpession(list, FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeTester.class, "testCompute_absentToPresent", "testCompute_presentToPresent"); + TestUtils.getSurpession(list, FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeIfAbsentTester.class, "testComputeIfAbsent_supportedAbsent"); + TestUtils.getSurpession(list, FILE_KEY_TYPE2FILE_VALUE_TYPEMapComputeIfPresentTester.class, "testCompute_presentToPresent", "testComputeIfPresent_supportedPresent"); + TestUtils.getSurpession(list, FILE_KEY_TYPE2FILE_VALUE_TYPEMapSupplyIfAbsentTester.class, "testSupplyIfAbsent_supportedAbsent"); + TestUtils.getSurpession(list, FILE_KEY_TYPE2FILE_VALUE_TYPEMapMergeTester.class, "testAbsent"); + TestUtils.getSurpession(list, FILE_KEY_TYPE2FILE_VALUE_TYPEMapPutIfAbsentTester.class, "testPutIfAbsent_supportedAbsent"); + TestUtils.getSurpession(list, FILE_KEY_TYPE2FILE_VALUE_TYPEMapRemoveEntryTester.class, "testRemove_supportedPresentLastWrongValue", "testRemoveObject_supportedPresentLastWrongValue"); + + TestUtils.getSurpession(list, CollectionAddTester.class, "testAdd_unsupportedNotPresent"); + TestUtils.getSurpession(list, CollectionAddAllTester.class, "testAddAll_unsupportedNonePresent"); + TestUtils.getSurpession(list, FILE_KEY_TYPE2FILE_VALUE_TYPEMapContainsValueTester.class, "testContains_no"); + TestUtils.getSurpession(list, CollectionContainsTester.class, "testContains_no"); + TestUtils.getSurpession(list, CollectionRetainAllTester.class, "testRetainAll_disjointPreviouslyNonEmpty"); + TestUtils.getSurpession(list, BooleanCollectionAddAllTester.class, "testAddAll_unsupportedNonePresent"); + TestUtils.getSurpession(list, BooleanCollectionAddAllArrayTester.class, "testAddAllArray_unsupportedNonePresent"); + TestUtils.getSurpession(list, CollectionContainsAllTester.class, "testContainsAll_disjoint", "testContainsAll_partialOverlap"); + return list; + } + +#endif +} diff --git a/src/test/java/speiger/src/collections/ints/base/BaseInt2IntMapTest.java b/src/test/java/speiger/src/collections/ints/base/BaseInt2IntMapTest.java index df9bc64..bc5dc29 100644 --- a/src/test/java/speiger/src/collections/ints/base/BaseInt2IntMapTest.java +++ b/src/test/java/speiger/src/collections/ints/base/BaseInt2IntMapTest.java @@ -1,163 +1,164 @@ -package speiger.src.collections.ints.base; - -import java.util.EnumSet; -import java.util.stream.IntStream; - -import org.junit.Assert; -import org.junit.Test; - -import speiger.src.collections.ints.maps.interfaces.Int2IntMap; -import speiger.src.collections.ints.utils.IntStrategy; -import speiger.src.collections.tests.MapTests; - -@SuppressWarnings("javadoc") -public abstract class BaseInt2IntMapTest -{ - protected static final IntStrategy STRATEGY = new Strategy(); - protected static final int[] TEST_ARRAY = IntStream.range(0, 100).toArray(); - protected static final int[] PUT_ARRAY = IntStream.range(512, 1024).toArray(); - protected static final int[] PUT_VALUE_ARRAY = IntStream.range(0, 512).toArray(); - - public abstract Int2IntMap createMap(int[] keys, int[] values); - public abstract Int2IntMap createEmptyMap(); - - public EnumSet getValidMapTests() { return EnumSet.allOf(MapTests.class); } - - @Test - public void testPut() - { - if(!getValidMapTests().contains(MapTests.PUT)) return; - Int2IntMap putMap = createMap(PUT_ARRAY, PUT_VALUE_ARRAY); - Assert.assertEquals(PUT_ARRAY.length, putMap.size()); - Assert.assertEquals(0, putMap.put(0, 512)); - Assert.assertEquals(1, putMap.put(513, 2)); - Assert.assertEquals(PUT_ARRAY.length + 1, putMap.size()); - Assert.assertEquals(512, putMap.addTo(0, 1)); - Assert.assertEquals(513, putMap.get(0)); - } - - @Test - public void testPutAll() - { - if(!getValidMapTests().contains(MapTests.PUT_ALL)) return; - Int2IntMap putMap = createMap(TEST_ARRAY, TEST_ARRAY); - Assert.assertEquals(TEST_ARRAY.length, putMap.size()); - putMap.putAll(createMap(PUT_ARRAY, PUT_VALUE_ARRAY)); - Assert.assertEquals(TEST_ARRAY.length + PUT_ARRAY.length, putMap.size()); - putMap = createMap(TEST_ARRAY, TEST_ARRAY); - putMap.putAll(createMap(PUT_VALUE_ARRAY, PUT_ARRAY)); - Assert.assertEquals(PUT_ARRAY.length, putMap.size()); - } - - @Test - public void testContains() - { - if(!getValidMapTests().contains(MapTests.CONTAINS)) return; - Int2IntMap map = createMap(TEST_ARRAY, TEST_ARRAY); - Assert.assertTrue(map.containsKey(0)); - Assert.assertFalse(map.containsKey(-1)); - Assert.assertTrue(map.containsKey(Integer.valueOf(10))); - Assert.assertFalse(map.containsKey(Short.valueOf((short)10))); - Assert.assertTrue(map.containsValue(50)); - Assert.assertFalse(map.containsValue(150)); - Assert.assertTrue(map.containsValue(Integer.valueOf(10))); - Assert.assertFalse(map.containsValue(Short.valueOf((short)10))); - } - - @Test - public void testReplace() - { - if(!getValidMapTests().contains(MapTests.REPLACE)) return; - Int2IntMap map = createMap(TEST_ARRAY, TEST_ARRAY); - Assert.assertEquals(0, map.replace(0, 512)); - Assert.assertEquals(512, map.get(0)); - Assert.assertTrue(map.replace(0, 512, 0)); - Assert.assertFalse(map.replace(0, 512, 0)); - map = createMap(TEST_ARRAY, TEST_ARRAY); - map.replaceInts((K, V) -> 99 - V); - Assert.assertEquals(99, map.get(0)); - Assert.assertEquals(0, map.get(99)); - } - - @Test - public void testCompute() - { - if(!getValidMapTests().contains(MapTests.COMPUTE)) return; - Int2IntMap map = createMap(TEST_ARRAY, TEST_ARRAY); - Assert.assertEquals(512, map.computeInt(0, (K, V) -> 512)); - Assert.assertEquals(512, map.get(0)); - Assert.assertEquals(512, map.computeIntIfAbsent(0, T -> 0)); - Assert.assertEquals(0, map.computeIntIfPresent(0, (T, V) -> 0)); - Assert.assertEquals(0, map.computeIntIfAbsent(-10, T -> 0)); - } - - @Test - public void testMerge() - { - if(!getValidMapTests().contains(MapTests.MERGE)) return; - Int2IntMap map = createMap(TEST_ARRAY, TEST_ARRAY); - Assert.assertEquals(50, map.mergeInt(1, 50, Integer::max)); - Assert.assertEquals(2, map.mergeInt(2, 50, Integer::min)); - } - - @Test - public void testGet() - { - if(!getValidMapTests().contains(MapTests.GET)) return; - Int2IntMap map = createMap(TEST_ARRAY, TEST_ARRAY); - for(int i = 0;i Assert.assertEquals(PUT_ARRAY[K], V)); - map.int2IntEntrySet().forEach(T -> Assert.assertEquals(PUT_ARRAY[T.getIntKey()], T.getIntValue())); - map.keySet().forEach(T -> Assert.assertEquals(PUT_VALUE_ARRAY[T], T)); - map.values().forEach(T -> Assert.assertTrue(T >= 512 && T <= 1024)); - Assert.assertTrue(map.keySet().contains(50)); - Assert.assertFalse(map.keySet().contains(-50)); - Assert.assertTrue(map.values().contains(1000)); - Assert.assertFalse(map.values().contains(-1000)); - } - - @Test - public void testRemove() - { - if(!getValidMapTests().contains(MapTests.REMOVE)) return; - Int2IntMap map = createMap(PUT_VALUE_ARRAY, PUT_ARRAY); - Assert.assertEquals(PUT_ARRAY[50], map.remove(PUT_VALUE_ARRAY[50])); - Assert.assertTrue(map.remove(PUT_VALUE_ARRAY[51], PUT_ARRAY[51])); - } - - @Test - public void testSort() - { - if(!getValidMapTests().contains(MapTests.COPY)) return; - Int2IntMap map = createMap(TEST_ARRAY, TEST_ARRAY); - Int2IntMap copy = map.copy(); - Assert.assertFalse(map == copy); - Assert.assertEquals(map, copy); - } - - public static class Strategy implements IntStrategy - { - @Override - public int hashCode(int o) - { - return o; - } - - @Override - public boolean equals(int key, int value) - { - return key == value; - } - - } +package speiger.src.collections.ints.base; + +import java.util.EnumSet; +import java.util.stream.IntStream; + +import org.junit.Assert; +import org.junit.Test; + +import speiger.src.collections.ints.maps.interfaces.Int2IntMap; +import speiger.src.collections.ints.utils.IntStrategy; +import speiger.src.collections.tests.MapTests; + +@SuppressWarnings("javadoc") +public abstract class BaseInt2IntMapTest +{ + protected static final IntStrategy STRATEGY = new Strategy(); + protected static final int[] TEST_ARRAY = IntStream.range(0, 100).toArray(); + protected static final int[] PUT_ARRAY = IntStream.range(512, 1024).toArray(); + protected static final int[] PUT_VALUE_ARRAY = IntStream.range(0, 512).toArray(); + + public abstract Int2IntMap createMap(int[] keys, int[] values); + public abstract Int2IntMap createEmptyMap(); + + public EnumSet getValidMapTests() { return EnumSet.allOf(MapTests.class); } + + @Test + public void testPut() + { + if(!getValidMapTests().contains(MapTests.PUT)) return; + Int2IntMap putMap = createMap(PUT_ARRAY, PUT_VALUE_ARRAY); + Assert.assertEquals(PUT_ARRAY.length, putMap.size()); + Assert.assertEquals(0, putMap.put(0, 512)); + Assert.assertEquals(1, putMap.put(513, 2)); + Assert.assertEquals(PUT_ARRAY.length + 1, putMap.size()); + Assert.assertEquals(512, putMap.addTo(0, 1)); + Assert.assertEquals(513, putMap.get(0)); + } + + @Test + public void testPutAll() + { + if(!getValidMapTests().contains(MapTests.PUT_ALL)) return; + Int2IntMap putMap = createMap(TEST_ARRAY, TEST_ARRAY); + Assert.assertEquals(TEST_ARRAY.length, putMap.size()); + putMap.putAll(createMap(PUT_ARRAY, PUT_VALUE_ARRAY)); + Assert.assertEquals(TEST_ARRAY.length + PUT_ARRAY.length, putMap.size()); + putMap = createMap(TEST_ARRAY, TEST_ARRAY); + putMap.putAll(createMap(PUT_VALUE_ARRAY, PUT_ARRAY)); + Assert.assertEquals(PUT_ARRAY.length, putMap.size()); + } + + @Test + @SuppressWarnings("unlikely-arg-type") + public void testContains() + { + if(!getValidMapTests().contains(MapTests.CONTAINS)) return; + Int2IntMap map = createMap(TEST_ARRAY, TEST_ARRAY); + Assert.assertTrue(map.containsKey(0)); + Assert.assertFalse(map.containsKey(-1)); + Assert.assertTrue(map.containsKey(Integer.valueOf(10))); + Assert.assertFalse(map.containsKey(Short.valueOf((short)10))); + Assert.assertTrue(map.containsValue(50)); + Assert.assertFalse(map.containsValue(150)); + Assert.assertTrue(map.containsValue(Integer.valueOf(10))); + Assert.assertFalse(map.containsValue(Short.valueOf((short)10))); + } + + @Test + public void testReplace() + { + if(!getValidMapTests().contains(MapTests.REPLACE)) return; + Int2IntMap map = createMap(TEST_ARRAY, TEST_ARRAY); + Assert.assertEquals(0, map.replace(0, 512)); + Assert.assertEquals(512, map.get(0)); + Assert.assertTrue(map.replace(0, 512, 0)); + Assert.assertFalse(map.replace(0, 512, 0)); + map = createMap(TEST_ARRAY, TEST_ARRAY); + map.replaceInts((K, V) -> 99 - V); + Assert.assertEquals(99, map.get(0)); + Assert.assertEquals(0, map.get(99)); + } + + @Test + public void testCompute() + { + if(!getValidMapTests().contains(MapTests.COMPUTE)) return; + Int2IntMap map = createMap(TEST_ARRAY, TEST_ARRAY); + Assert.assertEquals(512, map.computeInt(0, (K, V) -> 512)); + Assert.assertEquals(512, map.get(0)); + Assert.assertEquals(512, map.computeIntIfAbsent(0, T -> 0)); + Assert.assertEquals(0, map.computeIntIfPresent(0, (T, V) -> 0)); + Assert.assertEquals(0, map.computeIntIfAbsent(-10, T -> 0)); + } + + @Test + public void testMerge() + { + if(!getValidMapTests().contains(MapTests.MERGE)) return; + Int2IntMap map = createMap(TEST_ARRAY, TEST_ARRAY); + Assert.assertEquals(50, map.mergeInt(1, 50, Integer::max)); + Assert.assertEquals(2, map.mergeInt(2, 50, Integer::min)); + } + + @Test + public void testGet() + { + if(!getValidMapTests().contains(MapTests.GET)) return; + Int2IntMap map = createMap(TEST_ARRAY, TEST_ARRAY); + for(int i = 0;i Assert.assertEquals(PUT_ARRAY[K], V)); + map.int2IntEntrySet().forEach(T -> Assert.assertEquals(PUT_ARRAY[T.getIntKey()], T.getIntValue())); + map.keySet().forEach(T -> Assert.assertEquals(PUT_VALUE_ARRAY[T], T)); + map.values().forEach(T -> Assert.assertTrue(T >= 512 && T <= 1024)); + Assert.assertTrue(map.keySet().contains(50)); + Assert.assertFalse(map.keySet().contains(-50)); + Assert.assertTrue(map.values().contains(1000)); + Assert.assertFalse(map.values().contains(-1000)); + } + + @Test + public void testRemove() + { + if(!getValidMapTests().contains(MapTests.REMOVE)) return; + Int2IntMap map = createMap(PUT_VALUE_ARRAY, PUT_ARRAY); + Assert.assertEquals(PUT_ARRAY[50], map.remove(PUT_VALUE_ARRAY[50])); + Assert.assertTrue(map.remove(PUT_VALUE_ARRAY[51], PUT_ARRAY[51])); + } + + @Test + public void testSort() + { + if(!getValidMapTests().contains(MapTests.COPY)) return; + Int2IntMap map = createMap(TEST_ARRAY, TEST_ARRAY); + Int2IntMap copy = map.copy(); + Assert.assertFalse(map == copy); + Assert.assertEquals(map, copy); + } + + public static class Strategy implements IntStrategy + { + @Override + public int hashCode(int o) + { + return o; + } + + @Override + public boolean equals(int key, int value) + { + return key == value; + } + + } } \ No newline at end of file