44 Commits
Author SHA1 Message Date
Speiger 21ccbee3b2 Disabled Google Tests that we don't have to deal. 2026-05-14 21:32:16 +02:00
Speiger 58a9eb38b4 Loads of additions.
-Added: Indirect Sorters.
-Added: ReferenceMaps
-Fixed: A bunch of smaller bugs found due to tests
2026-05-14 19:21:38 +02:00
Speiger 2f1525ab57 Fixes and new updates.
- Added: Collectors to lists/queues/sets
- Fixed: Bugs in linked hash sets.
- Fixed: Bugs in unit tests.
2026-05-14 02:51:38 +02:00
Speiger 9f46091282 Added Tests for Ordered Maps and more work on completing the
implementation
2026-05-12 13:37:22 +02:00
Speiger 3d39d5526d Breaking update
- Added: Optionals for the missing JDK ones.
- Removed: Default values for Reduce and FindFirst. Using Optionals
instead.
2026-05-11 18:00:00 +02:00
Speiger c6f656ee66 Switched to yearly activity 2026-05-11 00:36:08 +02:00
Speiger f0139d1a22 Fixed Badge Generator 2026-05-11 00:34:48 +02:00
Speiger 58e20bb513 Fixed Enums 2026-05-11 00:10:44 +02:00
Speiger 502f22cea3 Removed java 25 support. Gradlew isn't supporting this yet. 2026-05-10 22:11:18 +02:00
Speiger 90e3b7110a Updated Actions 2026-05-10 22:09:21 +02:00
Speiger a26106cc89 Fixed a bunch of Iterator code and implemented Reverse Map/Set Tests 2026-05-10 22:00:55 +02:00
Speiger d002f0094f Updated Build Matrix to incude newer java versions and remove obsolete
ones
2026-05-09 05:25:26 +02:00
Speiger 042460a338 Started Adding support for JDK21 SequencedCollections.
Implementation is mostly finished. Just need to iron out bugs.
But at this point i want to push activity.
2026-05-09 05:22:35 +02:00
Speiger 20927a97eb Reworked Module Settings System
Changelog:
- Added: Dependency System that will resolve missing classes and enable
them as needed. (This isn't perfect on some low level modules like
Functions)
- Added: Dependency Error system that will throw errors if a dependency
is that is required is specifically disabled.
- Added: Default setting for "undefined" entries.
- Fixed: A few bugs that made the dependency system unnecessary
difficult.
- Updated: Documentation
2025-03-09 23:29:13 +01:00
Speiger ebe75b0fea Fixing a few things and testing more. Not useable atm. 2025-03-08 01:08:31 +01:00
Speiger a6be24c59d Start of a Advanced Dependency System.
The idea behind this system is that you can select systems a lot easier.
So if a custom system isn't required it can be disabled and all the
subsystems that require it either get disabled too.
it also allows you to set systems as: Only if they are required. Meaning
if only a specific system is required its dependencies can still load.
2025-03-08 01:08:31 +01:00
Speiger afdd27648e Updated Changelog and Readme to include Maven Central 2024-04-11 19:11:07 +02:00
Speiger 7e475b5472 Fixed a few bugs in the maven central script 2024-03-30 05:12:57 +01:00
Speiger e65fde736b Fixed 2024-03-30 01:08:38 +01:00
Speiger bf0b4172de Added Maven central Badge 2024-03-30 01:07:46 +01:00
Speiger 961b47a58c Fixed java8 compat 2024-03-30 01:02:42 +01:00
Speiger 330be87338 finalizing the maven central release. 2024-03-30 00:32:37 +01:00
Speiger 4b30ce12c9 Upgraded thread workers and disable GPG temporarly. 2024-03-29 22:35:44 +01:00
Speiger 0be7dba5d3 Fixed script bug 2024-03-29 22:26:34 +01:00
SpeigerandSpeiger 6eaa992f5f Create SECURITY.md 2024-03-29 22:19:29 +01:00
Speiger 9b23d713ff Started maven publish plugin. 2024-03-29 22:17:38 +01:00
Speiger 85d230c561 Fixed a auto generation bug where iterators wouldn't accept settings 2023-07-04 17:29:32 +02:00
Speiger 6afed5e174 Version Bump 2023-06-29 22:52:44 +02:00
Speiger 640a1a8161 Fixed tests and added missing changelog 2023-06-29 20:04:45 +02:00
Speiger 274d37c4d6 New Features.
-Added: List.indexedIterator which allows you to create a iterator with a customized iteration indecies. Useful if you want to transform lists output.
-Added: PriorityQueue.contains is now a function
-Added: Iterators/Async Builders now support MapToPrimitiveType function on the object variant. So more processing can be done. (Will be expanded upon later versions)
-Updated: SimpleCodeGenerator 1.3.0 is now being used which allows for iterative code support.
2023-06-29 18:30:22 +02:00
Speiger a89c812c06 Added Infinite Iterators 2023-06-17 01:22:56 +02:00
Speiger 6af0656216 Adding coverage to master to make things simpler! 2023-06-15 18:53:08 +02:00
Speiger e76db94136 Upgrading Other dependencies! 2023-06-15 18:31:22 +02:00
Speiger 7011101b05 Upgraded Gradle to be java19/20 friendly 2023-06-15 18:19:12 +02:00
Speiger d0599b99ec Upgraded Build Script and support now java19/20 2023-06-15 18:09:14 +02:00
Speiger d7c5b9ad7d Optimized SelectionSort a tiny bit. 2023-06-15 18:08:57 +02:00
Speiger d2c81e7779 Fixed all the reported issues by the Unit testing. 2023-06-15 17:12:11 +02:00
Speiger ef5fdbd377 Finished Code Cleanup with Compute functions and added ReversedWrappers 2023-06-14 17:40:27 +02:00
Speiger 5e67e45910 Fixed failing tests/errors 2023-06-06 11:21:52 +02:00
Speiger 63ef68fb95 New Compute function and better toArray implementations 2023-06-05 23:40:48 +02:00
Speiger 0f9751bf70 Fixed that setValue wasn't working with ForEach implementations. 2023-05-18 23:02:27 +02:00
Speiger bcc2ffdc13 New features.
-Added: Improved Map documentation for compute methods
-Added: Dedicated toArray implementations to TreeSets
2023-05-17 09:58:55 +02:00
Speiger 2da4588430 Added getFirst/getLast/removeFirst/removeLast to lists 2023-05-17 09:20:45 +02:00
Speiger ed9ce60af4 Small Fixes to doc and Useless Imports 2023-05-17 09:01:09 +02:00
276 changed files with 71397 additions and 61508 deletions
-6
View File
@@ -6,12 +6,6 @@
<attribute name="gradle_used_by_scope" value="main,test"/> <attribute name="gradle_used_by_scope" value="main,test"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="src" output="bin/main" path="src/main/resources">
<attributes>
<attribute name="gradle_scope" value="main"/>
<attribute name="gradle_used_by_scope" value="main,test"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="bin/test" path="src/test/java"> <classpathentry kind="src" output="bin/test" path="src/test/java">
<attributes> <attributes>
<attribute name="gradle_scope" value="test"/> <attribute name="gradle_scope" value="test"/>
+33 -32
View File
@@ -1,32 +1,33 @@
name: Latest Build name: Latest Build
on: on:
push: push:
branches: [ master ] branches: [ master ]
pull_request: pull_request:
branches: [ master ] branches: [ master ]
jobs: jobs:
build: build:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
jdk: [8, 11, 14, 16, 17, 18] jdk: [8, 11, 17, 20, 21]
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v6
- name: Set up JDK ${{ matrix.jdk }} - name: Set up JDK ${{ matrix.jdk }}
uses: actions/setup-java@v1 uses: actions/setup-java@v5
with: with:
java-version: ${{ matrix.jdk }} distribution: 'temurin'
java-version: ${{ matrix.jdk }}
- name: Validate Gradle wrapper
uses: gradle/wrapper-validation-action@e6e38bacfdf1a337459f332974bb2327a31aaf4b - name: Validate Gradle wrapper
uses: gradle/actions/wrapper-validation@v6
- name: Make gradlew executable
run: chmod +x ./gradlew - name: Make gradlew executable
run: chmod +x ./gradlew
- name: Build with Gradle
run: ./gradlew build - name: Build with Gradle
run: ./gradlew build
+3 -3
View File
@@ -9,12 +9,12 @@ jobs:
name: Unit Tests name: Unit Tests
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v6
with: with:
fetch-depth: 0 fetch-depth: 0
- name: Set up JDK 11 - name: Set up JDK 11
uses: actions/setup-java@v3 uses: actions/setup-java@v5
with: with:
distribution: temurin distribution: temurin
java-version: 11 java-version: 11
@@ -54,7 +54,7 @@ jobs:
esac esac
- name: Create Test Badge - name: Create Test Badge
uses: emibcn/badge-action@v1.2.4 uses: emibcn/badge-action@v2
with: with:
label: Tests label: Tests
status: '${{ fromJSON( steps.test-results.outputs.json ).conclusion }}, Passed: ${{ fromJSON( steps.test-results.outputs.json ).formatted.stats.tests_succ }}, Skipped: ${{ fromJSON( steps.test-results.outputs.json ).formatted.stats.tests_skip }}, Failed: ${{ fromJSON( steps.test-results.outputs.json ).formatted.stats.tests_fail }}' status: '${{ fromJSON( steps.test-results.outputs.json ).conclusion }}, Passed: ${{ fromJSON( steps.test-results.outputs.json ).formatted.stats.tests_succ }}, Skipped: ${{ fromJSON( steps.test-results.outputs.json ).formatted.stats.tests_skip }}, Failed: ${{ fromJSON( steps.test-results.outputs.json ).formatted.stats.tests_fail }}'
+27
View File
@@ -0,0 +1,27 @@
name: Measure coverage
on:
push:
branches: [ debug ]
jobs:
build:
name: Code Quality Check
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
- name: Set up JDK 11
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 11
cache: 'gradle'
- name: Make gradlew executable
run: chmod +x ./gradlew
- name: Build and analyze
run: ./gradlew generateTestSource test jacocoTestReport --info -Dfull_test_suite=true
- name: Upload to CodeCov
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
run: bash <(curl -s https://codecov.io/bash) -t $CODECOV_TOKEN
@@ -9,12 +9,12 @@ jobs:
name: Unit Tests name: Unit Tests
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v6
with: with:
fetch-depth: 0 fetch-depth: 0
- name: Set up JDK 11 - name: Set up JDK 11
uses: actions/setup-java@v3 uses: actions/setup-java@v5
with: with:
distribution: temurin distribution: temurin
java-version: 11 java-version: 11
+14 -13
View File
@@ -2,21 +2,22 @@
<projectDescription> <projectDescription>
<name>Primitive-Collections</name> <name>Primitive-Collections</name>
<comment></comment> <comment></comment>
<projects/> <projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures> <natures>
<nature>org.eclipse.jdt.core.javanature</nature> <nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature> <nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures> </natures>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments/>
</buildCommand>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments/>
</buildCommand>
</buildSpec>
<linkedResources/>
<filteredResources/>
</projectDescription> </projectDescription>
+295 -259
View File
@@ -1,260 +1,296 @@
# Changelog of versions # Changelog of versions
### Version 0.8.0 ### Version 0.9.0
- Added: ISizeProvider interface (Optimization Helper) - Added: getFirst/getLast/removeFirst/removeLast to List.class.
- Added: ISizeProvider into most Iterable implementations (Distinct/Filter/FlatMap/ArrayFlatMap don't support it, for obvious reasons) - Added: Dedicated Set toArray implementations.
- Added: ToArray function into Iterable which uses ISizeProvider to reduce overhead of duplicating arrays. - Added: ToArray/pushTop functions to Stack.class.
- Added: Functions that have the same type, Int2IntFunction as example, have now a identity function. - Added: ComputeNonDefault functions which will contain the current behavior of the Compute function, while the Compute will be changed to be more java compliant!
- Added: Functions of a BooleanValue have now alwaysTrue/False function. - Added: List.reversed, which returns a SubList that has all elements in reversed order and also inserts reversed.
- Added: ForEachIndexed for all Iterable implementations - Added: Iterators.infinite as an option that will create a Infinite Iterator based on the inputed one.
- Added: RandomGenerator support (Java17), though requires self compilation - Added: List.indexedIterator which allows you to create a iterator with a customized iteration indecies. Useful if you want to transform lists output.
- Added: Optimizations for HashUtils next power of function. - Added: PriorityQueue.contains is now a function
- Added: toArray() now returns a cached empty array if the collection is empty. - Added: Iterators/Async Builders now support MapToPrimitiveType function on the object variant. So more processing can be done. (Will be expanded upon later versions)
- Added: toArray function for AsyncBuilder - Fixed: SetValue wasn't working on forEach implementations.
- Added: Modularization to the library where feature can be disabled as needed. (Requires Self-Compilation) - Fixed: Compute functions now perform with primitives more java compliant. Meaning that getDefaultReturnValue function no longer is seen as null.
- Fixed: putIfAbsent now replaces defaultValues - Fixed: Supplier was using the wrong dataType in their function name.
- Fixed: OpenHashSet/Map and their Custom Variants no longer rely on List implementations. - Updated: SimpleCodeGenerator 1.3.0 is now being used which allows for iterative code support.
- Fixed: ObjectCopyOnWriteList.of did create a ObjectArrayList instead of the CopyOnWrite variant. - Breaking Change: Map.compute/IfAbsent/Present and Map.supplyIfAbsent if the value is a primitive it will no longer accept the defaultReturnValue() as "null" if that functionality is desired then use: computeNonDefault which contains the functionality!
- Removed: BooleanSet and Maps that start with a Boolean classes since they can not be used anyways.
- Breaking Change: Function classes now use the "apply/applyAs/test" format from Java itself, instead of the "get" format. This cleans up a lot of things. But will break existing function class implementations ### Version 0.8.1
- Breaking Change: Classes that used PrimitiveCollection functions now default to java functions where applicable, this is to increase compat. - Added: getFirst/getLast/removeFirst/removeLast to List.class.
- Breaking Change: Some function classes now get closer to javas terms. (Predicate/UnaryOperator etc) - Added: Dedicated Set toArray implementations.
- Added: ToArray/pushTop functions to Stack.class.
### Version 0.7.0 - Added: ComputeNonDefault functions which will contain the current behavior of the Compute function, while the Compute will be changed to be more java compliant!
- Added: Over 11 Million Unit Tests to this library to ensure quality. - Added: List.reversed, which returns a SubList that has all elements in reversed order and also inserts reversed.
- Added: ArrayList size constructor now throws IllegalStateException if the size parameter is negative - Added: Iterators.infinite as an option that will create a Infinite Iterator based on the inputed one.
- Added: EnumMap specialized forEach implementation. - Added: List.indexedIterator which allows you to create a iterator with a customized iteration indecies. Useful if you want to transform lists output.
- Added: AbstractMap.remove now delegates to its primitive counterpart. - Added: PriorityQueue.contains is now a function
- Added: ConcurrentHashMap now implements ITrimmable - Added: Iterators/Async Builders now support MapToPrimitiveType function on the object variant. So more processing can be done. (Will be expanded upon later versions)
- Refactor: Removed a lot of disabled code from ArraySet. - Fixed: SetValue wasn't working on forEach implementations.
- Removed: LinkedList.addAll(index, List) now delegates to LinkedList.addAll(index, Collection) due to no special optimization required. - Fixed: Compute functions now perform with primitives more java compliant. Meaning that getDefaultReturnValue function no longer is seen as null.
- Fixed: AbstractList.SubList.get/set/swapRemove didn't calculate their List index Properly - Fixed: Supplier was using the wrong dataType in their function name.
- Fixed: AbstractList.SubList chains now properly if you create SubLists within SubLists. - Updated: SimpleCodeGenerator 1.3.0 is now being used which allows for iterative code support.
- Fixed: AbstractList.Iterator.add now respects Immutable/UnmodifiableLists.
- Fixed: AbstractList.Iterator.skip/back now keep track of the last returned value for remove function to work properly. ### Version 0.8.0
- Fixed: CopyOnWriteArrayList.extract/removeElements(int, int) does now proper range checks and remove elements properly. - Added: getFirst/getLast/removeFirst/removeLast to Lists
- Fixed: CopyOnWriteArrayList.SubList now works properly. (Reimplemented entirely) - Added: Dedicated implementations for toArray into TreeSets
- Fixed: CopyOnWriteArrayList.Iterator.previous() was returning the wrong values. - Fixed: forEach methods in Maps now can use "setValue" functions.
- Fixed: CopyOnWriteArrayList.Iterator.skip now skips the right amount of elements and stops where it should.
- Fixed: LinkedList.first/last/dequeue/dequeueLast now throws NoSuchElementException when empty instead of IllegalStateException. ### Version 0.8.0
- Fixed: LinkedList had an edge case where the entire reverse iterator would break if the wrong element was removed. - Added: ISizeProvider interface (Optimization Helper)
- Fixed: LinkedList.extractElement now returns the correct values. - Added: ISizeProvider into most Iterable implementations (Distinct/Filter/FlatMap/ArrayFlatMap don't support it, for obvious reasons)
- Fixed: AbstractMap.entrySet().remove(Object) now returns true if defaultReturnValue elements were removed. - Added: ToArray function into Iterable which uses ISizeProvider to reduce overhead of duplicating arrays.
- Fixed: ConcurrentHashMap.remove(Object, Object) checks if the type matches before comparing against null Values. - Added: Functions that have the same type, Int2IntFunction as example, have now a identity function.
- Fixed: LinkedHashMap.clearAndTrim() was checking the wrong value for determining the full reset or clearing of a Map. - Added: Functions of a BooleanValue have now alwaysTrue/False function.
- Fixed: HashMap.trim/clearToTrim() was using the wrong value to determin if something should be done. - Added: ForEachIndexed for all Iterable implementations
- Fixed: HashMap now compares empty values (0) against nullKeys when Object Variants of the type are used. - Added: RandomGenerator support (Java17), though requires self compilation
- Fixed: ImmutableMap now compares empty values (0) against nullKeys when Object Variants of the type are used. - Added: Optimizations for HashUtils next power of function.
- Fixed: ArrayMap.iterator(key) now throws NoSuchElementException when the element wasn't found. - Added: toArray() now returns a cached empty array if the collection is empty.
- Fixed: Linked/EnumMap array constructor was creating the wrong size values array. - Added: toArray function for AsyncBuilder
- Fixed: LinkedEnumMap.getAndMoveToFirst/Last was moving elements even if the element wasn't present. - Added: Modularization to the library where feature can be disabled as needed. (Requires Self-Compilation)
- Fixed: AVL/RBTreeMap.getFirst/LastKey was not throwing a NoSuchElementException if the map was empty. - Fixed: putIfAbsent now replaces defaultValues
- Fixed: Map.Builder wasn't throwing a IllegalStateException when creating a negative size builder. - Fixed: OpenHashSet/Map and their Custom Variants no longer rely on List implementations.
- Fixed: AVL/RBTreeSet.DecendingSet.subSet(from, fromInclusive, to, toInclusive) was creating a corrupt asending subset. - Fixed: ObjectCopyOnWriteList.of did create a ObjectArrayList instead of the CopyOnWrite variant.
- Fixed: ArraySet throws now a IllegalStateException when trying to create it with a negative size. - Removed: BooleanSet and Maps that start with a Boolean classes since they can not be used anyways.
- Fixed: ArraySet.addMoveToLast(key) was crashing when a key was already present. - Breaking Change: Function classes now use the "apply/applyAs/test" format from Java itself, instead of the "get" format. This cleans up a lot of things. But will break existing function class implementations
- Fixed: Immutable/LinkedHashSet now keep track of their iteration index properly. - Breaking Change: Classes that used PrimitiveCollection functions now default to java functions where applicable, this is to increase compat.
- Fixed: LinkedHashSet.moveToFirst/Last(key) would crash if the Set was empty. - Breaking Change: Some function classes now get closer to javas terms. (Predicate/UnaryOperator etc)
- Fixed: LinkedHashSet.clearAndTrim() was checking the wrong value for determining the full reset or clearing of a Map.
- Fixed: HashSet.trim/clearToTrim() was using the wrong value to determin if something should be done. ### Version 0.7.0
- Added: Over 11 Million Unit Tests to this library to ensure quality.
- Added: ArrayList size constructor now throws IllegalStateException if the size parameter is negative
### Version 0.6.2 - Added: EnumMap specialized forEach implementation.
- Added: Array only sorting function return the inputed array. This was done to allow for static final references to use the method in one go without having to make lambda wrappers. Cleaner code. - Added: AbstractMap.remove now delegates to its primitive counterpart.
- Added: Iterator Wrappers are now a bit more in Compliance with Java Standards. - Added: ConcurrentHashMap now implements ITrimmable
- Added: AsyncBuilders now Support Array Inputs to create cleaner code. - Refactor: Removed a lot of disabled code from ArraySet.
- Changed: LinkedList.addBulk variable definition was triggering a false positive. - Removed: LinkedList.addAll(index, List) now delegates to LinkedList.addAll(index, Collection) due to no special optimization required.
- Fixed: TreeMap.subMap().entrySet().remove() wouldn't check primitives properly. - Fixed: AbstractList.SubList.get/set/swapRemove didn't calculate their List index Properly
- Fixed: SortedMap.sub/tail/headMap were looping into themselves. - Fixed: AbstractList.SubList chains now properly if you create SubLists within SubLists.
- Fixed: AbstractCollection.retainAll didn't push removed values through the consumer. - Fixed: AbstractList.Iterator.add now respects Immutable/UnmodifiableLists.
- Fixed: AbstractCollection.toArray wouldn't reset the last entry if the input array was larger then the elements in the collection. - Fixed: AbstractList.Iterator.skip/back now keep track of the last returned value for remove function to work properly.
- Fixed: SubList didn't check for ranges properly or didn't use parent list to validate changes. - Fixed: CopyOnWriteArrayList.extract/removeElements(int, int) does now proper range checks and remove elements properly.
- Fixed: ArrayList.addElements didn't check input array fully and used the wrong variable to move the elements around. - Fixed: CopyOnWriteArrayList.SubList now works properly. (Reimplemented entirely)
- Fixed: LinkedList.addElements(EmptyInput) would crash. - Fixed: CopyOnWriteArrayList.Iterator.previous() was returning the wrong values.
- Fixed: LinkedList.swapRemove didn't account for if the removed element was the prelast one. - Fixed: CopyOnWriteArrayList.Iterator.skip now skips the right amount of elements and stops where it should.
- Fixed: LinkedList.removeElements would break the implementation if the list was almost empty and the middle element was removed. - Fixed: LinkedList.first/last/dequeue/dequeueLast now throws NoSuchElementException when empty instead of IllegalStateException.
- Fixed: LinkedHashSet.addAndMoveToFirst wouldn't move elements to the first place. - Fixed: LinkedList had an edge case where the entire reverse iterator would break if the wrong element was removed.
- Fixed: ArrayList/LinkedList extractElements crashing when 0 or less elements are desired. - Fixed: LinkedList.extractElement now returns the correct values.
- Fixed: TreeMap pollFirst/LastKey should return the defaultMin/max value instead of a Empty value. - Fixed: AbstractMap.entrySet().remove(Object) now returns true if defaultReturnValue elements were removed.
- Fixed: TreeMap keySet implementation was missing the class type implementations to pass keySet tests. - Fixed: ConcurrentHashMap.remove(Object, Object) checks if the type matches before comparing against null Values.
- Fixed: TreeMap.SubMap Iterator (primitive Keys) was crashing because a Null was set on to a primitive. - Fixed: LinkedHashMap.clearAndTrim() was checking the wrong value for determining the full reset or clearing of a Map.
- Fixed: HashMap.trim/clearToTrim() was using the wrong value to determin if something should be done.
- Fixed: HashMap now compares empty values (0) against nullKeys when Object Variants of the type are used.
### Version 0.6.1 - Fixed: ImmutableMap now compares empty values (0) against nullKeys when Object Variants of the type are used.
- Fixed: FIFO queue crashing when the last index is before the first index when peek is called. - Fixed: ArrayMap.iterator(key) now throws NoSuchElementException when the element wasn't found.
- Fixed: FIFO queue only clears the array if it was in use. - Fixed: Linked/EnumMap array constructor was creating the wrong size values array.
- Added: Sorted Method for the stream replacing functions. - Fixed: LinkedEnumMap.getAndMoveToFirst/Last was moving elements even if the element wasn't present.
- Fixed: AVL/RBTreeMap.getFirst/LastKey was not throwing a NoSuchElementException if the map was empty.
### Version 0.6.0 - Fixed: Map.Builder wasn't throwing a IllegalStateException when creating a negative size builder.
- Added: addOrGet for sets. - Fixed: AVL/RBTreeSet.DecendingSet.subSet(from, fromInclusive, to, toInclusive) was creating a corrupt asending subset.
- Added: Async API which allows to easily execute Iterables/Collections offthread without the complexity. - Fixed: ArraySet throws now a IllegalStateException when trying to create it with a negative size.
- Added: CopyOnWriteArrayList and tests for it - Fixed: ArraySet.addMoveToLast(key) was crashing when a key was already present.
- Added: Support up to Java17. - Fixed: Immutable/LinkedHashSet now keep track of their iteration index properly.
- Added: Build System now adds module-info if the Running JVM is 9 or higher - Fixed: LinkedHashSet.moveToFirst/Last(key) would crash if the Set was empty.
- Added: ArrayList.of(Class, size) that allows you to allocate a size right at the creation of the List without having to create a wrapper array. - Fixed: LinkedHashSet.clearAndTrim() was checking the wrong value for determining the full reset or clearing of a Map.
- Added: A ConcurrentHashMap implementation. - Fixed: HashSet.trim/clearToTrim() was using the wrong value to determin if something should be done.
- Fixed: containsValue in the HashMap wouldn't check the nullKey
- Removed: Deprecated functions from SortedMaps/Sets
### Version 0.6.2
### Version 0.5.3 - Added: Array only sorting function return the inputed array. This was done to allow for static final references to use the method in one go without having to make lambda wrappers. Cleaner code.
- Added: OrderedMap/Set - Added: Iterator Wrappers are now a bit more in Compliance with Java Standards.
- Added: Deprecation to Functions that are specific to Ordered interfaces in the SortedMap/Set - Added: AsyncBuilders now Support Array Inputs to create cleaner code.
- Added: subFrom to Maps which is the counterpart of the addTo method - Changed: LinkedList.addBulk variable definition was triggering a false positive.
- Added: pourAsList and pourAsSet (booleans excluded for sets) to Iterable - Fixed: TreeMap.subMap().entrySet().remove() wouldn't check primitives properly.
- Fixed: ArrayList.grow had a small bug where it would trigger to early causing performance problems with exact sized collections. - Fixed: SortedMap.sub/tail/headMap were looping into themselves.
- Fixed: FIFOQueue size constructor had a small bug where it would trigger a array enlargement when all elements were inserted. - Fixed: AbstractCollection.retainAll didn't push removed values through the consumer.
- Fixed: AbstractCollection.toArray wouldn't reset the last entry if the input array was larger then the elements in the collection.
### Version 0.5.2 - Fixed: SubList didn't check for ranges properly or didn't use parent list to validate changes.
- Fixed: Bugs with Queues starting with the wrong size - Fixed: ArrayList.addElements didn't check input array fully and used the wrong variable to move the elements around.
- Fixed: ArrayGrowth for Queues was +1 instead of +50% - Fixed: LinkedList.addElements(EmptyInput) would crash.
- Added: Benchmarks with java and FastUtil - Fixed: LinkedList.swapRemove didn't account for if the removed element was the prelast one.
- Fixed: LinkedList.removeElements would break the implementation if the list was almost empty and the middle element was removed.
### Version 0.5.1 - Fixed: LinkedHashSet.addAndMoveToFirst wouldn't move elements to the first place.
- Fixed: Reworked the NavigableSet/Map implementations of RBTree/AVLTree/Array Sets/Maps so they are now deemed stable. - Fixed: ArrayList/LinkedList extractElements crashing when 0 or less elements are desired.
- Added: Another 150k Unit tests. - Fixed: TreeMap pollFirst/LastKey should return the defaultMin/max value instead of a Empty value.
- Added: List and Set Unit tests for Integer (or Primitives in this case) to ensure basic stability there. (Now covering all sets and lists) - Fixed: TreeMap keySet implementation was missing the class type implementations to pass keySet tests.
- Fixed: Bugs with null values for primitive collections. - Fixed: TreeMap.SubMap Iterator (primitive Keys) was crashing because a Null was set on to a primitive.
- Removed: ArraySet/Map subSet/subMap implementation was removed.
### Version 0.5.0 ### Version 0.6.1
- Added: 2 Helper functions to find out how many bits are required to store a Number. - Fixed: FIFO queue crashing when the last index is before the first index when peek is called.
- Added: pour function directly into Iterable which allows to collect all elements in the Iterable directly. - Fixed: FIFO queue only clears the array if it was in use.
- Added: The new ToArray method from Java9 and newer into the library. Using a functional interface. (Just a backport) - Added: Sorted Method for the stream replacing functions.
- Changed: Reworked how the Map Builder functions are created. They are now in a SubClass that moves them out of the way. Less Clutter. (This might break things if that was used before)
- Added: Map Builder that allows now to Build Maps like Guava ImmutableMaps can be build. Note: This has a slight performance overhead. ### Version 0.6.0
- Added: Unmodifiable and Synchronize wrapper functions direclty into Collection Interfaces. This is mostly a quality of life thing. - Added: addOrGet for sets.
- Added: Unmodifiable and Synchronized Wrapper Collections can now be cloned. They clone the underlying map which doesn't break functionality. (Had a usecase for it) - Added: Async API which allows to easily execute Iterables/Collections offthread without the complexity.
- Added: A boxed putAll array variant. - Added: CopyOnWriteArrayList and tests for it
- Fixed: EnumMaps didn't keep track of their size and now got proper care and implementations as needed. There might be more work required but at least the core functionality is now up to date. - Added: Support up to Java17.
- Added: Tests for the new Stream replace functions to ensure no bugs are left. - Added: Build System now adds module-info if the Running JVM is 9 or higher
- Fixed: Custom HashSet reduce function with a default value was checking incorrectly for present keys. - Added: ArrayList.of(Class, size) that allows you to allocate a size right at the creation of the List without having to create a wrapper array.
- Added: Guava TestSuit - Added: A ConcurrentHashMap implementation.
- Fixed: HashCode and toString method would crash if the Object Key/Value was null - Fixed: containsValue in the HashMap wouldn't check the nullKey
- Added: AbstractTypeCollection now delegates the contains check to type-specific Collections if it detects it. - Removed: Deprecated functions from SortedMaps/Sets
- Fixed: Map.Entry toString wasn't writing values not like it should do.
- Fixed: Set.hashCode now is the sum of the elements instead of a Unique HashCode based on the elements. ### Version 0.5.3
- Fixed: Added missing NonNull Checks. - Added: OrderedMap/Set
- Fixed: Custom/OpenHashMap.containsValue implementation was wrong. - Added: Deprecation to Functions that are specific to Ordered interfaces in the SortedMap/Set
- Fixed: Custom/OpenHashMap.compute/present/absent now works how it is specified in the Java Documentation - Added: subFrom to Maps which is the counterpart of the addTo method
- Fixed: Custom/OpenHashMap.merge/BulkMerge now works how it is specified in the Java Documentation - Added: pourAsList and pourAsSet (booleans excluded for sets) to Iterable
- Fixed: Custom/Linked/OpenHashMap.keySet.remove was causing a infinite loop. - Fixed: ArrayList.grow had a small bug where it would trigger to early causing performance problems with exact sized collections.
- Fixed: Custom/Linked/OpenHashMap.entrySet.contains was not correctly comparing the entry. - Fixed: FIFOQueue size constructor had a small bug where it would trigger a array enlargement when all elements were inserted.
- Fixed: Custom/OpenHashMap.mapIterator now no longer crashes in certain cases.
- Added: Custom/LinkedOpenHashMap now takes use of the improved Iterator it has for containsValue ### Version 0.5.2
- Fixed: CustomOpenHashMap.keySet.forEach was basically putting out keys even if they were present - Fixed: Bugs with Queues starting with the wrong size
- Fixed: ImmutableMaps issues thanks to the tests. Roughly the same as the rest of the maps - Fixed: ArrayGrowth for Queues was +1 instead of +50%
- Fixed: RB/AVLTreeMaps issues. Roughly the same as the rest of the maps - Added: Benchmarks with java and FastUtil
- Fixed: SubLists are now properly implemented.
- Fixed: HashSet Iterator bugs now fixed... That was Painful. ### Version 0.5.1
- Added: Tests for Lists and Sets - Fixed: Reworked the NavigableSet/Map implementations of RBTree/AVLTree/Array Sets/Maps so they are now deemed stable.
- Added: Another 150k Unit tests.
### Version 0.4.5 - Added: List and Set Unit tests for Integer (or Primitives in this case) to ensure basic stability there. (Now covering all sets and lists)
- Added: removeAll/retainAll(Collection c, Consumer r) which receives all the elements that got deleted from the collection - Fixed: Bugs with null values for primitive collections.
- Fixed: Supplier get function wasn't referencing original function. - Removed: ArraySet/Map subSet/subMap implementation was removed.
- Added: addIfPresent/Absent to lists
- Added: distinct, limit and peek iterators ### Version 0.5.0
- Added: Iterable's can now reduce its contents - Added: 2 Helper functions to find out how many bits are required to store a Number.
- Added: Better ForEach support for IterableWrappers so a Iterator chain is not created - Added: pour function directly into Iterable which allows to collect all elements in the Iterable directly.
- Added: SwapRemove to Lists which moves the last element into the desired space to be deleted - Added: The new ToArray method from Java9 and newer into the library. Using a functional interface. (Just a backport)
- Added: More Test cases - Changed: Reworked how the Map Builder functions are created. They are now in a SubClass that moves them out of the way. Less Clutter. (This might break things if that was used before)
- Added: Map Builder that allows now to Build Maps like Guava ImmutableMaps can be build. Note: This has a slight performance overhead.
### Version 0.4.4 - Added: Unmodifiable and Synchronize wrapper functions direclty into Collection Interfaces. This is mostly a quality of life thing.
- Fixed: ObjectArrayList.of was causing crashes because of a Poor implementation. - Added: Unmodifiable and Synchronized Wrapper Collections can now be cloned. They clone the underlying map which doesn't break functionality. (Had a usecase for it)
- Added: Unsorted HashMaps/Sets now throw Concurrent exceptions if they were modified during a rehash. - Added: A boxed putAll array variant.
- Added: Array/Collection version of enqueue and enqueueFirst to PriorityQueues. - Fixed: EnumMaps didn't keep track of their size and now got proper care and implementations as needed. There might be more work required but at least the core functionality is now up to date.
- Added: fillBuffer function into PrimitiveLists which allow to optimize JavaNio buffers if needed. - Added: Tests for the new Stream replace functions to ensure no bugs are left.
- Fixed: Custom HashSet reduce function with a default value was checking incorrectly for present keys.
### Version 0.4.3 - Added: Guava TestSuit
- Added: Wrapper now support the Optimized Lambda replacer functions to improve performance. - Fixed: HashCode and toString method would crash if the Object Key/Value was null
- Added: FIFO Queue has now a minimum capacity and that is now checked more consistently. - Added: AbstractTypeCollection now delegates the contains check to type-specific Collections if it detects it.
- Fixed: Map.Entry toString wasn't writing values not like it should do.
### Version 0.4.2 - Fixed: Set.hashCode now is the sum of the elements instead of a Unique HashCode based on the elements.
- Added: Lists/Sets/Maps/PriorityQueues are now copy-able. with the new copy() function. - Fixed: Added missing NonNull Checks.
Note: subLists/subMaps/subSets or synchronize/unmodifyable wrappers do not support that function. - Fixed: Custom/OpenHashMap.containsValue implementation was wrong.
- Fixed: PriorityQueues didn't implement: hashCode/equals/toString - Fixed: Custom/OpenHashMap.compute/present/absent now works how it is specified in the Java Documentation
- Fixed: Custom/OpenHashMap.merge/BulkMerge now works how it is specified in the Java Documentation
### Version 0.4.1 - Fixed: Custom/Linked/OpenHashMap.keySet.remove was causing a infinite loop.
- Changed: ForEach with input now provides input, value instead of value, input, this improves the usage of method references greatly - Fixed: Custom/Linked/OpenHashMap.entrySet.contains was not correctly comparing the entry.
- Added: addAll with Array-types in collections. - Fixed: Custom/OpenHashMap.mapIterator now no longer crashes in certain cases.
- Added: Java Iterator/Iterable support for Stream replacing methods - Added: Custom/LinkedOpenHashMap now takes use of the improved Iterator it has for containsValue
- Added: Suppliers. - Fixed: CustomOpenHashMap.keySet.forEach was basically putting out keys even if they were present
- Added: SupplyIfAbsent. It is ComputeIfAbsent but using suppliers - Fixed: ImmutableMaps issues thanks to the tests. Roughly the same as the rest of the maps
- Added: Count feature into Iterable - Fixed: RB/AVLTreeMaps issues. Roughly the same as the rest of the maps
- Fixed: A couple bugs with the new StreamReplacing functions in LinkedCollections Iterating to Infinity - Fixed: SubLists are now properly implemented.
- Fixed: HashSet Iterator bugs now fixed... That was Painful.
### Version 0.4.0 - Added: Tests for Lists and Sets
- Changed: Iterable specific helper functions were moved out of Iterators and moved into Iterables
- Added: New Stream replacing functions: findFirst, matchesAny/All/None ### Version 0.4.5
- Fixed: Compute/ComputeIfAbsent/ComputeIfPresent/Merge/BulkMerge in maps now behave like they should. - Added: removeAll/retainAll(Collection c, Consumer r) which receives all the elements that got deleted from the collection
- Added: Implementations for New Stream replacing functions. - Fixed: Supplier get function wasn't referencing original function.
- Changed: Removed a lot of duplicated forEach implementations - Added: addIfPresent/Absent to lists
- Added: Flat/Mapping functions (to object) are now accessible to primitive maps. - Added: distinct, limit and peek iterators
- Added: Filter function to Iterators/Iterables (Iterable implements it by default) - Added: Iterable's can now reduce its contents
- Changed: Cleanup of some variables/mappers - Added: Better ForEach support for IterableWrappers so a Iterator chain is not created
- Added/Fixed: AVL/RBTreeMap got reworked and SubMaps work more properly now. Also forEach support got improved a lot - Added: SwapRemove to Lists which moves the last element into the desired space to be deleted
- Added/Fixed: TreeSubSets (RB/AVL) got their functional implementations improved too. - Added: More Test cases
- Added: Pairs are now a thing. In Mutable/Immutable Form
### Version 0.4.4
### Version 0.3.6 - Fixed: ObjectArrayList.of was causing crashes because of a Poor implementation.
- Fixed: addAll non Type Specific Lists was causing crashes. - Added: Unsorted HashMaps/Sets now throw Concurrent exceptions if they were modified during a rehash.
- Fixed/Changed: clearAndTrim's implementation was all over the place. In some cases causing crash scenarios. - Added: Array/Collection version of enqueue and enqueueFirst to PriorityQueues.
- Fixed: Wrappers didn't implement toString/equals/hashCode - Added: fillBuffer function into PrimitiveLists which allow to optimize JavaNio buffers if needed.
- Added: Tests for addAll Bug
- Changed: Cleaned up CodeStyle as bugs were fixed. ### Version 0.4.3
- Added: Wrapper now support the Optimized Lambda replacer functions to improve performance.
### Version 0.3.5 - Added: FIFO Queue has now a minimum capacity and that is now checked more consistently.
- Fixed: Simple Code Generator dependency was declared wrong. Its only needed for runtime. Not for Compilation.
- Fixed: ObjectLists Crashed when a null was provided as a Comparator. (Unless the List was Initialized with the ClassType) ### Version 0.4.2
- Fixed: LinkedLists didn't implement add(Object) - Added: Lists/Sets/Maps/PriorityQueues are now copy-able. with the new copy() function.
- Fixed: Object Collections did have the JavaCollections deprecated as the Constructor. This should only be deprecated for Primitives Note: subLists/subMaps/subSets or synchronize/unmodifyable wrappers do not support that function.
- Added: Tests with 5k Random names for Object sorting. - Fixed: PriorityQueues didn't implement: hashCode/equals/toString
- Changed: Object Arrays no longer require a Comparable[] it just assumes now that the elements in the Array are Comparable
- Fixed: Dependency to SimpleCodeGenerator should be no longer a thing. Because the resulting library doesn't need it only the builder does. ### Version 0.4.1
- Changed: ForEach with input now provides input, value instead of value, input, this improves the usage of method references greatly
### Version 0.3.4 - Added: addAll with Array-types in collections.
- Fixed: ArrayLists didn't resize properly if they were empty. - Added: Java Iterator/Iterable support for Stream replacing methods
- Added: Suppliers.
- Added: SupplyIfAbsent. It is ComputeIfAbsent but using suppliers
### Version 0.3.3 - Added: Count feature into Iterable
- Added: Flat/Mapping function for Iterables/Iterators to help avoid streams for cleaner looking code - Fixed: A couple bugs with the new StreamReplacing functions in LinkedCollections Iterating to Infinity
- Fixed: AVLTrees pollFirst/Last is now keeping orders and is fixed
- Fixed: AbstractCollection bulk adding methods now link to the specialized implementations. ### Version 0.4.0
- Fixed: A bug with getElements in ArrayList. - Changed: Iterable specific helper functions were moved out of Iterators and moved into Iterables
- Fixed: PriorityQueue remove/toArray function were renamed so they fit better with other interfaces. (remove => removeFirst and toArray uses a different genericType) - Added: New Stream replacing functions: findFirst, matchesAny/All/None
- Added: LinkedList which is a List/PriorityDequeue/Stack which allows for more optimized use-cases and reduced boxing/unboxing. - Fixed: Compute/ComputeIfAbsent/ComputeIfPresent/Merge/BulkMerge in maps now behave like they should.
- Added: Tests for LinkedList - Added: Implementations for New Stream replacing functions.
- Changed: Removed a lot of duplicated forEach implementations
### Version 0.3.2 - Added: Flat/Mapping functions (to object) are now accessible to primitive maps.
- Fixed: Map.put wasn't referring to primitive variants. - Added: Filter function to Iterators/Iterables (Iterable implements it by default)
- Added: ImmutableList. - Changed: Cleanup of some variables/mappers
- Added: Iterator pour function into a List or Array - Added/Fixed: AVL/RBTreeMap got reworked and SubMaps work more properly now. Also forEach support got improved a lot
- Changed: Arrays Wrap is now accessible to Objects and now is ? extends TYPE instead of TYPE. - Added/Fixed: TreeSubSets (RB/AVL) got their functional implementations improved too.
- Added: OpenHashSets now implement foreach and have less overhead. - Added: Pairs are now a thing. In Mutable/Immutable Form
- Added: ImmutableOpenHashSet that is not editable (is linked by default for fast iteration)
- Added: CustomOpenHashSets now implement foreach and have less overhead. ### Version 0.3.6
- Added: ImmutableOpenHashMap that is not editable (is linked by default for fast iteration) - Fixed: addAll non Type Specific Lists was causing crashes.
- Added: Maps can now be created through the interface. - Fixed/Changed: clearAndTrim's implementation was all over the place. In some cases causing crash scenarios.
- Fixed: Lists.addElements(T...elements) was adding elements at the beginning of a list instead of the end. - Fixed: Wrappers didn't implement toString/equals/hashCode
- Fixed: Bugs with the AVLTreeSet. And marked bugs with AVLTreeX that are still present. - Added: Tests for addAll Bug
- Changed: Cleaned up CodeStyle as bugs were fixed.
### Version 0.3.1
- Fixed: containsKey & containsValue in HashMaps were deprecated for Object Variants. ### Version 0.3.5
- Fixed: HashMap wasn't deleting Keys & Values references when removing a Object - Fixed: Simple Code Generator dependency was declared wrong. Its only needed for runtime. Not for Compilation.
- Fixed: AVLTreeMap didn't balance properly. - Fixed: ObjectLists Crashed when a null was provided as a Comparator. (Unless the List was Initialized with the ClassType)
- Changed: EnumMap no longer tries to access SharedSecrets since its gone in java11 - Fixed: LinkedLists didn't implement add(Object)
- Added: HashMaps now implement ITrimmable - Fixed: Object Collections did have the JavaCollections deprecated as the Constructor. This should only be deprecated for Primitives
- Added: AVLTreeSet didn't balance properly - Added: Tests with 5k Random names for Object sorting.
- Fixed: HashMaps & LinkedMaps weren't clearing references properly. - Changed: Object Arrays no longer require a Comparable[] it just assumes now that the elements in the Array are Comparable
- Fixed: Dependency to SimpleCodeGenerator should be no longer a thing. Because the resulting library doesn't need it only the builder does.
### Version 0.3.0 (Breaking 0.2.0)
- Added: Stack.isEmpty was missing ### Version 0.3.4
- Changed: remove/removeLast/enqueue/enqueueFirst no longer use Type Suffixes - Fixed: ArrayLists didn't resize properly if they were empty.
- Removed: Suffixes for unmodifiable & synchronize functions.
- Changed: Primitive Stacks no longer depend on the base Stack class. Because seriously not needed.
- Changed: PriorityQueues no longer extends Object Variant. ### Version 0.3.3
- Changed: Maps.get function is no longer using Suffixes unless its absolutely necessary. - Added: Flat/Mapping function for Iterables/Iterators to help avoid streams for cleaner looking code
- Changed: Maps.remove function is no longer using Suffixes unless its absolutely necessary. - Fixed: AVLTrees pollFirst/Last is now keeping orders and is fixed
- Changed: ObjectList methods are no longer marked Deprecated even so it was for primitive ones. - Fixed: AbstractCollection bulk adding methods now link to the specialized implementations.
- Added: Shuffle & Reverse Methods. - Fixed: A bug with getElements in ArrayList.
- Added: Concat Iterators. - Fixed: PriorityQueue remove/toArray function were renamed so they fit better with other interfaces. (remove => removeFirst and toArray uses a different genericType)
- Added: LinkedList which is a List/PriorityDequeue/Stack which allows for more optimized use-cases and reduced boxing/unboxing.
- Added: Tests for LinkedList
### Version 0.3.2
- Fixed: Map.put wasn't referring to primitive variants.
- Added: ImmutableList.
- Added: Iterator pour function into a List or Array
- Changed: Arrays Wrap is now accessible to Objects and now is ? extends TYPE instead of TYPE.
- Added: OpenHashSets now implement foreach and have less overhead.
- Added: ImmutableOpenHashSet that is not editable (is linked by default for fast iteration)
- Added: CustomOpenHashSets now implement foreach and have less overhead.
- Added: ImmutableOpenHashMap that is not editable (is linked by default for fast iteration)
- Added: Maps can now be created through the interface.
- Fixed: Lists.addElements(T...elements) was adding elements at the beginning of a list instead of the end.
- Fixed: Bugs with the AVLTreeSet. And marked bugs with AVLTreeX that are still present.
### Version 0.3.1
- Fixed: containsKey & containsValue in HashMaps were deprecated for Object Variants.
- Fixed: HashMap wasn't deleting Keys & Values references when removing a Object
- Fixed: AVLTreeMap didn't balance properly.
- Changed: EnumMap no longer tries to access SharedSecrets since its gone in java11
- Added: HashMaps now implement ITrimmable
- Added: AVLTreeSet didn't balance properly
- Fixed: HashMaps & LinkedMaps weren't clearing references properly.
### Version 0.3.0 (Breaking 0.2.0)
- Added: Stack.isEmpty was missing
- Changed: remove/removeLast/enqueue/enqueueFirst no longer use Type Suffixes
- Removed: Suffixes for unmodifiable & synchronize functions.
- Changed: Primitive Stacks no longer depend on the base Stack class. Because seriously not needed.
- Changed: PriorityQueues no longer extends Object Variant.
- Changed: Maps.get function is no longer using Suffixes unless its absolutely necessary.
- Changed: Maps.remove function is no longer using Suffixes unless its absolutely necessary.
- Changed: ObjectList methods are no longer marked Deprecated even so it was for primitive ones.
- Added: Shuffle & Reverse Methods.
- Added: Concat Iterators.
- Added: PriorityQueues - Added: PriorityQueues
+4 -1
View File
@@ -30,10 +30,13 @@ There is 3 layers of control inside of the ModuleSettings.
Allowing for greater control without having to edit hundreds of lines of code. Allowing for greater control without having to edit hundreds of lines of code.
On top of that: On top of that:
Any Setting that isn't "Present" is counted as "Enabled". Any Setting that isn't "Present" can be defined as "Enabled" or "Disabled" using the "Default" argument.
If "Default" is missing, then it will just default to "Enabled".
So if you want to disable just 1 thing you can keep that 1 thing and delete the rest of the Setting. So if you want to disable just 1 thing you can keep that 1 thing and delete the rest of the Setting.
It will still work as the same. It will still work as the same.
The default settings just come with everything so you can see what is controllable. The default settings just come with everything so you can see what is controllable.
Note: If a global Module setting is disabled but a dependency needs said Module, it will enable only the required classes.
If a Module type (Float-Collection as example) is specifically disabled, the Dependency Resolver will throw errors telling you whats wrong.
How to compile the Code with the ModuleSettings enabled: How to compile the Code with the ModuleSettings enabled:
``` ```
+1
View File
@@ -1,4 +1,5 @@
{ {
"Default": true,
"Async": true, "Async": true,
"Base": true, "Base": true,
"Collection": true, "Collection": true,
+13 -5
View File
@@ -1,11 +1,12 @@
![build](https://github.com/Speiger/Primitive-Collections/actions/workflows/build_action.yml/badge.svg) ![build](https://github.com/Speiger/Primitive-Collections/actions/workflows/build_action.yml/badge.svg)
[![Latest Release](https://jitpack.io/v/Speiger/Primitive-Collections.svg)](https://jitpack.io/#Speiger/Primitive-Collections) [![Latest Release](https://jitpack.io/v/Speiger/Primitive-Collections.svg)](https://jitpack.io/#Speiger/Primitive-Collections)
![Maven Central Version](https://img.shields.io/maven-central/v/io.github.speiger/Primitive-Collections)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
![GitHub commit activity](https://img.shields.io/github/commit-activity/m/Speiger/Primitive-Collections) ![GitHub commit activity](https://img.shields.io/github/commit-activity/y/Speiger/Primitive-Collections)
![Unit Tests](https://github.com/Speiger/Primitive-Collections/actions/workflows/build_tests_action.yml/badge.svg) ![Unit Tests](https://github.com/Speiger/Primitive-Collections/actions/workflows/build_tests_action.yml/badge.svg)
![Coverage](https://gist.githubusercontent.com/Speiger/280257cd19cbe1dda3789bebd4ff65cf/raw/405abd1d2f6c19ac70f20b8b1772176f42d5c5d3/jacoco.svg) ![Coverage](https://gist.githubusercontent.com/Speiger/280257cd19cbe1dda3789bebd4ff65cf/raw/jacoco.svg)
[![codecov](https://codecov.io/gh/Speiger/Primitive-Collections/branch/debug/graph/badge.svg?token=WSTSNJM0EN)](https://codecov.io/gh/Speiger/Primitive-Collections) [![codecov](https://codecov.io/gh/Speiger/Primitive-Collections/branch/debug/graph/badge.svg?token=WSTSNJM0EN)](https://codecov.io/gh/Speiger/Primitive-Collections)
![Tests Done](https://gist.githubusercontent.com/Speiger/280257cd19cbe1dda3789bebd4ff65cf/raw/405abd1d2f6c19ac70f20b8b1772176f42d5c5d3/tests.svg) ![Tests Done](https://gist.githubusercontent.com/Speiger/280257cd19cbe1dda3789bebd4ff65cf/raw/tests.svg)
# Primitive-Collections # Primitive-Collections
This is a Simple Primitive Collections Library aimed to outperform Java's Collection Library and FastUtil. This is a Simple Primitive Collections Library aimed to outperform Java's Collection Library and FastUtil.
Both in Performance and Quality of Life Features. Both in Performance and Quality of Life Features.
@@ -43,14 +44,21 @@ To ensure that problems can be dealt with even if it is breaking the current API
# How to install # How to install
Using Jitpack Gradle Using Jitpack Gradle
```gradle ```groovy
repositories { repositories {
maven { maven {
url = "https://jitpack.io" url = "https://jitpack.io"
} }
} }
dependencies { dependencies {
implementation 'com.github.Speiger:Primitive-Collections:0.7.0' implementation 'com.github.Speiger:Primitive-Collections:0.9.0'
}
```
Using Maven Central
```groovy
dependencies {
implementation 'io.github.speiger:Primitive-Collections:0.9.0'
} }
``` ```
+15
View File
@@ -0,0 +1,15 @@
# Security Policy
## Supported Versions
Due to how the releases work, only the latest versions will be supported.
## Reporting a Vulnerability
If you have discovered a security vulnerability in this project, please report it privately.
**Please refrain from posting in public issues.**
This gives me time to process issues that are being found, and reduces the possiblity of abuse while patches are being created.
Please disclose it [here](https://github.com/Speiger/Primitive-Collections/security/advisories/new).
Please consider that this project is developed by a single person.
So please provide a reasonable timeframe when reporting.
+117 -48
View File
@@ -10,6 +10,7 @@ tasks.withType(JavaCompile) {
apply plugin: 'java' apply plugin: 'java'
apply plugin: 'eclipse' apply plugin: 'eclipse'
apply plugin: 'maven-publish' apply plugin: 'maven-publish'
apply plugin: 'signing'
repositories { repositories {
mavenCentral() mavenCentral()
@@ -19,16 +20,22 @@ repositories {
} }
archivesBaseName = 'Primitive Collections' archivesBaseName = 'Primitive Collections'
version = '0.8.0'; version = RELEASE_VERSION;
sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = JavaVersion.current(); sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = JavaVersion.current();
System.out.println("Java Version: "+compileJava.sourceCompatibility) System.out.println("Java Version: "+compileJava.sourceCompatibility)
java {
withJavadocJar()
withSourcesJar()
}
javadoc { javadoc {
options.tags = [ "implSpec", "note" ] options.tags = [ "implSpec", "note" ]
} }
eclipse { eclipse {
classpath { classpath {
downloadJavadoc = true downloadJavadoc = true
@@ -40,15 +47,16 @@ sourceSets {
builder builder
} }
configurations { configurations {
builderCompile.extendsFrom compile builderCompile.extendsFrom compile
} }
dependencies { dependencies {
builderImplementation 'com.google.code.gson:gson:2.10' builderImplementation 'com.google.code.gson:gson:2.10'
builderImplementation 'de.speiger:Simple-Code-Generator:1.2.2' builderImplementation 'de.speiger:Simple-Code-Generator:1.3.0'
testImplementation 'junit:junit:4.12' testImplementation 'junit:junit:4.12'
testImplementation 'com.google.guava:guava-testlib:31.0.1-jre' testImplementation 'com.google.guava:guava-testlib:33.6.0-jre'
} }
@@ -83,6 +91,14 @@ task generateTestSource(type: JavaExec) {
args = ['tests', 'silent'] args = ['tests', 'silent']
} }
task forceGenerateTestSource(type: JavaExec) {
group = 'internal'
description = 'Builds the sourcecode for the Tests'
classpath = sourceSets.builder.runtimeClasspath
main = 'speiger.src.builder.PrimitiveCollectionsBuilder'
args = ['tests', 'silent', 'force']
}
task generateLimitSource(type: JavaExec) { task generateLimitSource(type: JavaExec) {
group = 'internal' group = 'internal'
description = 'Builds the Sourcecode with the ModuleSettings.json applied' description = 'Builds the Sourcecode with the ModuleSettings.json applied'
@@ -91,26 +107,12 @@ task generateLimitSource(type: JavaExec) {
args = ['silent', 'load'] args = ['silent', 'load']
} }
task javadocJar(type: Jar) {
from javadoc
classifier = 'javadoc'
}
task srcJar(type: Jar) {
from sourceSets.main.allSource
classifier = 'sources'
}
compileJava.dependsOn generateGithubSource compileJava.dependsOn generateGithubSource
javadoc.failOnError = false javadoc.failOnError = false
javadoc.options.memberLevel = JavadocMemberLevel.PUBLIC javadoc.options.memberLevel = JavadocMemberLevel.PUBLIC
javadoc.options.quiet() javadoc.options.quiet()
artifacts {
archives javadocJar
archives srcJar
}
task testBooleans(type: Test) { task testBooleans(type: Test) {
group 'tests' group 'tests'
@@ -121,7 +123,7 @@ task testBooleans(type: Test) {
} }
useJUnit() useJUnit()
ignoreFailures = true ignoreFailures = true
maxHeapSize = "1024m" maxHeapSize = maxMemory
} }
task testBytes(type: Test) { task testBytes(type: Test) {
@@ -133,8 +135,8 @@ task testBytes(type: Test) {
} }
useJUnit() useJUnit()
ignoreFailures = true ignoreFailures = true
maxHeapSize = "1024m" maxHeapSize = maxMemory
maxParallelForks = 2 maxParallelForks = testThreads as Integer
} }
task testShorts(type: Test) { task testShorts(type: Test) {
@@ -146,8 +148,8 @@ task testShorts(type: Test) {
} }
useJUnit() useJUnit()
ignoreFailures = true ignoreFailures = true
maxHeapSize = "1024m" maxHeapSize = maxMemory
maxParallelForks = 2 maxParallelForks = testThreads as Integer
} }
task testChars(type: Test) { task testChars(type: Test) {
@@ -159,8 +161,8 @@ task testChars(type: Test) {
} }
useJUnit() useJUnit()
ignoreFailures = true ignoreFailures = true
maxHeapSize = "1024m" maxHeapSize = maxMemory
maxParallelForks = 2 maxParallelForks = testThreads as Integer
} }
task testInts(type: Test) { task testInts(type: Test) {
@@ -172,8 +174,8 @@ task testInts(type: Test) {
} }
useJUnit() useJUnit()
ignoreFailures = true ignoreFailures = true
maxHeapSize = "1024m" maxHeapSize = maxMemory
maxParallelForks = 2 maxParallelForks = testThreads as Integer
} }
task testLongs(type: Test) { task testLongs(type: Test) {
@@ -185,8 +187,8 @@ task testLongs(type: Test) {
} }
useJUnit() useJUnit()
ignoreFailures = true ignoreFailures = true
maxHeapSize = "1024m" maxHeapSize = maxMemory
maxParallelForks = 2 maxParallelForks = testThreads as Integer
} }
task testFloats(type: Test) { task testFloats(type: Test) {
@@ -198,8 +200,8 @@ task testFloats(type: Test) {
} }
useJUnit() useJUnit()
ignoreFailures = true ignoreFailures = true
maxHeapSize = "1024m" maxHeapSize = maxMemory
maxParallelForks = 2 maxParallelForks = testThreads as Integer
} }
task testDoubles(type: Test) { task testDoubles(type: Test) {
@@ -211,8 +213,8 @@ task testDoubles(type: Test) {
} }
useJUnit() useJUnit()
ignoreFailures = true ignoreFailures = true
maxHeapSize = "1024m" maxHeapSize = maxMemory
maxParallelForks = 2 maxParallelForks = testThreads as Integer
} }
task testObjects(type: Test) { task testObjects(type: Test) {
@@ -224,8 +226,8 @@ task testObjects(type: Test) {
} }
useJUnit() useJUnit()
ignoreFailures = true ignoreFailures = true
maxHeapSize = "1024m" maxHeapSize = maxMemory
maxParallelForks = 2 maxParallelForks = testThreads as Integer
} }
if(System.getProperty("full_test_suite", "false").toBoolean()) { if(System.getProperty("full_test_suite", "false").toBoolean()) {
@@ -248,25 +250,22 @@ test {
} }
useJUnit() useJUnit()
ignoreFailures = true ignoreFailures = true
maxHeapSize = "1024m" maxHeapSize = maxMemory
} }
jacocoTestReport { jacocoTestReport {
executionData fileTree(project.buildDir.absolutePath).include("jacoco/*.exec") executionData fileTree(project.buildDir.absolutePath).include("jacoco/*.exec")
reports { reports {
xml.enabled true xml.required = true
html.enabled = true html.required = true
csv.enabled true csv.required = true
} }
} }
publishing { publishing {
Properties props = new Properties()
if(file("$buildDir/credentials.properties").exists()) {
props.load(new FileInputStream("$buildDir/credentials.properties"))
}
publications { publications {
mavenJava(MavenPublication) { personal(MavenPublication) {
pom { pom {
name = 'Primitive Collections' name = 'Primitive Collections'
description = 'A Primitive Collection library that reduces memory usage and improves performance' description = 'A Primitive Collection library that reduces memory usage and improves performance'
@@ -275,8 +274,6 @@ publishing {
artifactId = project.archivesBaseName.replace(" ", "-") artifactId = project.archivesBaseName.replace(" ", "-")
groupId = 'de.speiger' groupId = 'de.speiger'
from components.java from components.java
artifact tasks.srcJar
artifact tasks.javadocJar
licenses { licenses {
license { license {
name = 'The Apache License, Version 2.0' name = 'The Apache License, Version 2.0'
@@ -301,11 +298,83 @@ publishing {
} }
repositories { repositories {
maven { maven {
name = "Speiger_Maven"
def auth = System.getenv("Speiger_Maven_Auth")?.split(';');
url version.endsWith('SNAPSHOT') ? "https://maven.speiger.com/repository/debug" : "https://maven.speiger.com/repository/main" url version.endsWith('SNAPSHOT') ? "https://maven.speiger.com/repository/debug" : "https://maven.speiger.com/repository/main"
credentials(PasswordCredentials) { credentials(PasswordCredentials) {
username props.mavenUser username auth?[0]
password props.mavenPassword password auth?[1]
} }
} }
} }
} }
tasks.withType(PublishToMavenRepository) {
def predicate = provider {
(repository == publishing.repositories.mavenCentral && publication == publishing.publications.maven) ||
(repository != publishing.repositories.mavenCentral && publication != publishing.publications.maven)
}
onlyIf("publishing binary to the external repository, or binary and sources to the internal one") {
predicate.get()
}
}
tasks.withType(PublishToMavenLocal) {
def predicate = provider {
publication == publishing.publications.personal
}
onlyIf("publishing binary and sources") {
predicate.get()
}
}
//Maven central Start
//Disabling due to java8 incompat, only needed to manually publishing anyways
//signing.useGpgCmd()
//
//import com.vanniktech.maven.publish.SonatypeHost
//import com.vanniktech.maven.publish.JavaLibrary
//import com.vanniktech.maven.publish.JavadocJar
//
//mavenPublishing {
// configure(new JavaLibrary(new JavadocJar.None(), true))
//}
//
//mavenPublishing {
// publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL)
//
// signAllPublications()
// pom {
// name = 'Primitive Collections'
// description = 'A Primitive Collection library that reduces memory usage and improves performance'
// url = 'https://github.com/Speiger/Primitive-Collections'
// version = project.version
// group = 'io.github.speiger'
// licenses {
// license {
// name = 'The Apache License, Version 2.0'
// url = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
// }
// }
//
// developers {
// developer {
// id = 'speiger'
// name = 'Speiger'
// }
// }
//
// scm {
// connection = 'scm:git:git://github.com/Speiger/Primitive-Collections.git'
// developerConnection = 'scm:git:ssh://github.com:Speiger/Primitive-Collections.git'
// url = 'https://github.com/Speiger/Primitive-Collections'
// }
//
// issueManagement {
// system = 'github'
// url = 'https://github.com/Speiger/Primitive-Collections/issues'
// }
// }
//}
//
+6 -1
View File
@@ -1 +1,6 @@
org.gradle.jvmargs=-Xmx3G org.gradle.jvmargs=-Xmx3G
maxMemory = 2048m
testThreads = 4
RELEASE_VERSION = 0.9.0
+5 -5
View File
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
@@ -1,155 +1,155 @@
package speiger.src.builder; package speiger.src.builder;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.function.UnaryOperator; import java.util.function.UnaryOperator;
import speiger.src.builder.mappers.IMapper; import speiger.src.builder.mappers.IMapper;
import speiger.src.builder.processor.TemplateProcess; import speiger.src.builder.processor.TemplateProcess;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class ModulePackage public class ModulePackage
{ {
private static final BiConsumer<String, RequiredType> VOID = (K, V) -> {}; private static final BiConsumer<String, RequiredType> VOID = (K, V) -> {};
public static final ClassType[] TYPE = ClassType.values(); public static final ClassType[] TYPE = ClassType.values();
final ClassType keyType; final ClassType keyType;
final ClassType valueType; final ClassType valueType;
Set<String> blocked = new HashSet<>(); Set<String> blocked = new HashSet<>();
Map<String, String> nameRemapper = new HashMap<>(); Map<String, String> nameRemapper = new HashMap<>();
Map<String, String> splitters = new HashMap<>(); Map<String, String> splitters = new HashMap<>();
List<Predicate<String>> blockedFilters = new ArrayList<>(); List<Predicate<String>> blockedFilters = new ArrayList<>();
List<IMapper> mappers = new ArrayList<>(); List<IMapper> mappers = new ArrayList<>();
Set<String> flags = new LinkedHashSet<>(); Set<String> flags = new LinkedHashSet<>();
Set<String> globalFlags; Set<String> globalFlags;
Map<String, Integer> flaggedValues = new HashMap<>(); Map<String, Integer> flaggedValues = new HashMap<>();
BiConsumer<String, RequiredType> requirements = VOID; BiConsumer<String, RequiredType> requirements = VOID;
public ModulePackage(Set<String> globalFlags, ClassType keyType, ClassType valueType) { public ModulePackage(Set<String> globalFlags, ClassType keyType, ClassType valueType) {
this.globalFlags = globalFlags; this.globalFlags = globalFlags;
this.keyType = keyType; this.keyType = keyType;
this.valueType = valueType; this.valueType = valueType;
} }
public void finish() { public void finish() {
requirements = VOID; requirements = VOID;
mappers.sort(Comparator.comparing(IMapper::getSearchValue, Comparator.comparingInt(String::length).reversed())); mappers.sort(Comparator.comparing(IMapper::getSearchValue, Comparator.comparingInt(String::length).reversed()));
mappers.sort(Comparator.comparing(IMapper::getSearchValue, this::sort)); mappers.sort(Comparator.comparing(IMapper::getSearchValue, this::sort));
} }
public void setRequirements(BiConsumer<String, RequiredType> requirements) { public void setRequirements(BiConsumer<String, RequiredType> requirements) {
this.requirements = requirements; this.requirements = requirements;
} }
public boolean isSame() { public boolean isSame() {
return keyType == valueType; return keyType == valueType;
} }
public boolean isEnumValid() { public boolean isEnumValid() {
return keyType == ClassType.OBJECT; return keyType == ClassType.OBJECT;
} }
public ClassType getKeyType() { public ClassType getKeyType() {
return keyType; return keyType;
} }
public ClassType getValueType() { public ClassType getValueType() {
return valueType; return valueType;
} }
public void addFlag(String flag) { public void addFlag(String flag) {
flags.add(flag); flags.add(flag);
} }
public void addGlobalFlag(String flag) { public void addGlobalFlag(String flag) {
globalFlags.add(flag); globalFlags.add(flag);
} }
public void addValue(String key, int value) { public void addValue(String key, int value) {
flaggedValues.put(key, value); flaggedValues.put(key, value);
} }
public void addRequirement(String fileName, RequiredType type) { public void addRequirement(String fileName, RequiredType type) {
requirements.accept(fileName, type); requirements.accept(fileName, type);
} }
public void addMapper(IMapper mapper) { public void addMapper(IMapper mapper) {
mappers.add(mapper); mappers.add(mapper);
} }
public void addBlockedFilter(Predicate<String> filter) { public void addBlockedFilter(Predicate<String> filter) {
blockedFilters.add(filter); blockedFilters.add(filter);
} }
public void addBlockedFiles(String... names) { public void addBlockedFiles(String... names) {
blocked.addAll(Arrays.asList(names)); blocked.addAll(Arrays.asList(names));
} }
public void addSplitter(String fileName, String splitter) { public void addSplitter(String fileName, String splitter) {
splitters.put(fileName, splitter); splitters.put(fileName, splitter);
} }
public void addRemapper(String fileName, String actualName) { public void addRemapper(String fileName, String actualName) {
nameRemapper.put(fileName, actualName); nameRemapper.put(fileName, actualName);
} }
public void process(String fileName, Consumer<TemplateProcess> result) { public void process(String fileName, Consumer<TemplateProcess> result) {
if(isBlocked(fileName)) return; if(isBlocked(fileName)) return;
String splitter = String.format(splitters.getOrDefault(fileName, keyType.getFileType()), keyType.getFileType(), valueType.getFileType()); String splitter = String.format(splitters.getOrDefault(fileName, keyType.getFileType()), keyType.getFileType(), valueType.getFileType());
String newName = String.format(nameRemapper.getOrDefault(fileName, "%s"+fileName), splitter); String newName = String.format(nameRemapper.getOrDefault(fileName, "%s"+fileName), splitter);
TemplateProcess process = new TemplateProcess(newName+".java"); TemplateProcess process = new TemplateProcess(newName+".java");
process.setPathBuilder(new PathBuilder(keyType.getPathType())); process.setPathBuilder(new PathBuilder(keyType.getPathType()));
process.addFlags(flags); process.addFlags(flags);
process.addFlags(globalFlags); process.addFlags(globalFlags);
process.addMappers(mappers); process.addMappers(mappers);
process.addValues(flaggedValues); process.addValues(flaggedValues);
result.accept(process); result.accept(process);
} }
private boolean isBlocked(String fileName) { private boolean isBlocked(String fileName) {
if(blocked.contains(fileName)) return true; if(blocked.contains(fileName)) return true;
for(int i = 0,m=blockedFilters.size();i<m;i++) { for(int i = 0,m=blockedFilters.size();i<m;i++) {
if(blockedFilters.get(i).test(fileName)) return true; if(blockedFilters.get(i).test(fileName)) return true;
} }
return false; return false;
} }
public static List<ModulePackage> createPackages(Set<String> globalFlags) { public static List<ModulePackage> createPackages(Set<String> globalFlags) {
List<ModulePackage> list = new ArrayList<>(); List<ModulePackage> list = new ArrayList<>();
for(ClassType key : TYPE) { for(ClassType key : TYPE) {
for(ClassType value : TYPE) { for(ClassType value : TYPE) {
list.add(new ModulePackage(globalFlags, key, value)); list.add(new ModulePackage(globalFlags, key, value));
} }
} }
return list; return list;
} }
private int sort(String key, String value) { private int sort(String key, String value) {
if(value.contains(key)) return 1; if(value.contains(key)) return 1;
else if(key.contains(value)) return -1; else if(key.contains(value)) return -1;
return 0; return 0;
} }
class PathBuilder implements UnaryOperator<Path> { class PathBuilder implements UnaryOperator<Path> {
String before; String before;
public PathBuilder(String before) { public PathBuilder(String before) {
this.before = before; this.before = before;
} }
@Override @Override
public Path apply(Path t) { public Path apply(Path t) {
return t.subpath(0, 6).resolve(before).resolve(t.subpath(6, t.getNameCount())); return t.subpath(0, 6).resolve(before).resolve(t.subpath(6, t.getNameCount()));
} }
} }
} }
@@ -1,270 +1,230 @@
package speiger.src.builder; package speiger.src.builder;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.StringJoiner; import java.util.StringJoiner;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.stream.Stream; import java.util.stream.Stream;
import speiger.src.builder.modules.AsyncModule; import speiger.src.builder.modules.AsyncModule;
import speiger.src.builder.modules.BaseModule; import speiger.src.builder.modules.BaseModule;
import speiger.src.builder.modules.CollectionModule; import speiger.src.builder.modules.CollectionModule;
import speiger.src.builder.modules.FunctionModule; import speiger.src.builder.modules.FunctionModule;
import speiger.src.builder.modules.JavaModule; import speiger.src.builder.modules.JavaModule;
import speiger.src.builder.modules.ListModule; import speiger.src.builder.modules.ListModule;
import speiger.src.builder.modules.MapModule; import speiger.src.builder.modules.MapModule;
import speiger.src.builder.modules.PairModule; import speiger.src.builder.modules.PairModule;
import speiger.src.builder.modules.PrioQueueModule; import speiger.src.builder.modules.PrioQueueModule;
import speiger.src.builder.modules.SetModule; import speiger.src.builder.modules.SetModule;
import speiger.src.builder.processor.TemplateProcess; import speiger.src.builder.processor.TemplateProcess;
import speiger.src.builder.processor.TemplateProcessor; import speiger.src.builder.processor.TemplateProcessor;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class PrimitiveCollectionsBuilder extends TemplateProcessor public class PrimitiveCollectionsBuilder extends TemplateProcessor
{ {
private static final int SPECIAL = 0x1; //Detects if the Builder is generating tests 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 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 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 private static final int SAVE = 0x4; //if the configuration should be created
Set<String> globalFlags = new HashSet<>(); Set<String> globalFlags = new HashSet<>();
List<ModulePackage> simplePackages = new ArrayList<>(); List<ModulePackage> simplePackages = new ArrayList<>();
List<ModulePackage> biPackages = new ArrayList<>(); List<ModulePackage> biPackages = new ArrayList<>();
List<ModulePackage> enumPackages = new ArrayList<>(); List<ModulePackage> enumPackages = new ArrayList<>();
Map<String, RequiredType> requirements = new HashMap<>(); Map<String, RequiredType> requirements = new HashMap<>();
SettingsManager manager = new SettingsManager(); SettingsManager manager = new SettingsManager();
int flags; int flags;
public PrimitiveCollectionsBuilder() public PrimitiveCollectionsBuilder() {
{ this(false);
this(false); }
}
public PrimitiveCollectionsBuilder(boolean silencedSuccess) {
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/"));
{ }
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(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);
}
public PrimitiveCollectionsBuilder(boolean silencedSuccess, Path sourceFolder, Path outputFolder, Path dataFolder)
{ private PrimitiveCollectionsBuilder setFlags(int flags) {
super(silencedSuccess, sourceFolder, outputFolder, dataFolder); this.flags = flags;
} if((flags & ANTI_SAVE) != 0) {
this.flags &= ~SAVE;
private PrimitiveCollectionsBuilder setFlags(int flags) { }
this.flags = flags; return this;
if((flags & ANTI_SAVE) != 0) { }
this.flags &= ~SAVE;
} private static PrimitiveCollectionsBuilder createTests(boolean silent, int flags) {
return this; return new PrimitiveCollectionsBuilder(silent,
} Paths.get("src/builder/resources/speiger/assets/tests/templates/"),
Paths.get("src/test/java/speiger/src/tests/"),
private static PrimitiveCollectionsBuilder createTests(boolean silent, int flags) { Paths.get("src/builder/resources/speiger/assets/tests/")).setFlags(flags | SPECIAL);
return new PrimitiveCollectionsBuilder(silent, }
Paths.get("src/builder/resources/speiger/assets/tests/templates/"),
Paths.get("src/test/java/speiger/src/tests/"), private static PrimitiveCollectionsBuilder createTesters(boolean silent, int flags) {
Paths.get("src/builder/resources/speiger/assets/tests/")).setFlags(flags | SPECIAL); return new PrimitiveCollectionsBuilder(silent,
} Paths.get("src/builder/resources/speiger/assets/testers/templates/"),
Paths.get("src/test/java/speiger/src/testers/"),
private static PrimitiveCollectionsBuilder createTesters(boolean silent, int flags) { Paths.get("src/builder/resources/speiger/assets/testers/")).setFlags(flags | SPECIAL);
return new PrimitiveCollectionsBuilder(silent, }
Paths.get("src/builder/resources/speiger/assets/testers/templates/"),
Paths.get("src/test/java/speiger/src/testers/"), @Override
Paths.get("src/builder/resources/speiger/assets/testers/")).setFlags(flags | SPECIAL); protected boolean isFileValid(Path fileName) { return true; }
} @Override
protected boolean relativePackages() { return true; }
@Override @Override
protected boolean isFileValid(Path fileName) protected boolean debugUnusedMappers() { return false; }
{
return true; @Override
} protected void afterFinish() {
if((flags & SPECIAL) == 0 && getVersion() > 8) {
@Override Path basePath = Paths.get("src/main/java");
protected boolean relativePackages() try(BufferedWriter writer = Files.newBufferedWriter(basePath.resolve("module-info.java"))) {
{ writer.write(getModuleInfo(basePath));
return true; }
} catch(Exception e) { e.printStackTrace(); }
}
@Override }
protected boolean debugUnusedMappers()
{ public List<BaseModule> createModules() {
return false; List<BaseModule> modules = new ArrayList<>();
} modules.add(JavaModule.INSTANCE);
modules.add(FunctionModule.INSTANCE);
@Override modules.add(CollectionModule.INSTANCE);
protected void afterFinish() modules.add(PrioQueueModule.INSTANCE);
{ modules.add(ListModule.INSTANCE);
if((flags & SPECIAL) == 0 && getVersion() > 8) modules.add(SetModule.INSTANCE);
{ modules.add(MapModule.INSTANCE);
Path basePath = Paths.get("src/main/java"); modules.add(PairModule.INSTANCE);
try(BufferedWriter writer = Files.newBufferedWriter(basePath.resolve("module-info.java"))) modules.add(AsyncModule.INSTANCE);
{ return modules;
writer.write(getModuleInfo(basePath)); }
}
catch(Exception e)
{ @Override
e.printStackTrace(); protected void init() {
} prepPackages();
} //Init Modules here
} addModules(createModules());
finishPackages();
public List<BaseModule> createModules() }
{
List<BaseModule> modules = new ArrayList<>(); public void addModules(List<BaseModule> modules) {
modules.add(JavaModule.INSTANCE); for(int i = 0,m=modules.size();i<m;i++) {
modules.add(FunctionModule.INSTANCE); modules.get(i).setManager(manager);
modules.add(CollectionModule.INSTANCE); }
modules.add(PrioQueueModule.INSTANCE); manager.resolve();
modules.add(ListModule.INSTANCE); for(int i = 0,m=modules.size();i<m;i++) {
modules.add(SetModule.INSTANCE); biPackages.forEach(modules.get(i)::init);
modules.add(MapModule.INSTANCE); }
modules.add(PairModule.INSTANCE); modules.forEach(BaseModule::cleanup);
modules.add(AsyncModule.INSTANCE); }
return modules;
} private void finishPackages() {
biPackages.forEach(ModulePackage::finish);
if((flags & SAVE) != 0) manager.save();
@Override }
protected void init()
{ private void prepPackages() {
prepPackages(); if((flags & LOAD) != 0) manager.load();
//Init Modules here for(ModulePackage entry : ModulePackage.createPackages(globalFlags)) {
addModules(createModules()); entry.setRequirements(requirements::put);
finishPackages(); biPackages.add(entry);
} if(entry.isSame()) simplePackages.add(entry);
if(entry.isEnumValid()) enumPackages.add(entry);
public void addModules(List<BaseModule> modules) }
{ }
for(int i = 0,m=modules.size();i<m;i++) {
modules.get(i).setManager(manager); @Override
} public void createProcesses(String fileName, Consumer<TemplateProcess> process) {
for(int i = 0,m=modules.size();i<m;i++) { List<ModulePackage> packages = getPackagesByRequirement(requirements.get(fileName));
biPackages.forEach(modules.get(i)::init); for(int i = 0,m=packages.size();i<m;i++) {
} packages.get(i).process(fileName, process);
for(int i = 0,m=modules.size();i<m;i++) { }
modules.get(i).cleanup(); }
}
} protected List<ModulePackage> getPackagesByRequirement(RequiredType type) {
if(type == null) return simplePackages;
private void finishPackages() if(type == RequiredType.BI_CLASS) return biPackages;
{ if(type == RequiredType.ENUM) return enumPackages;
biPackages.forEach(ModulePackage::finish); return Collections.emptyList();
if((flags & SAVE) != 0) manager.save(); }
}
private String getModuleInfo(Path basePath) {
private void prepPackages() StringJoiner joiner = new StringJoiner("\n", "", "\n");
{ try(Stream<Path> stream = Files.walk(getOutputFolder())) {
if((flags & LOAD) != 0) manager.load(); stream.filter(Files::isDirectory)
for(ModulePackage entry : ModulePackage.createPackages(globalFlags)) .filter(this::containsFiles)
{ .map(basePath::relativize)
entry.setRequirements(requirements::put); .map(Path::toString)
biPackages.add(entry); .map(this::sanitize)
if(entry.isSame()) simplePackages.add(entry); .forEach(T -> joiner.add("\texports "+T+";"));
if(entry.isEnumValid()) enumPackages.add(entry); }
} catch(Exception e) {
} e.printStackTrace();
throw new RuntimeException(e);
@Override }
public void createProcesses(String fileName, Consumer<TemplateProcess> process) StringBuilder builder = new StringBuilder();
{ builder.append("/** @author Speiger */\n");
List<ModulePackage> packages = getPackagesByRequirement(requirements.get(fileName)); builder.append("module ").append(sanitize(basePath.relativize(getOutputFolder()).toString())).append(" {\n");
for(int i = 0,m=packages.size();i<m;i++) builder.append(joiner.toString()).append("}");
{ return builder.toString();
packages.get(i).process(fileName, process); }
}
} private String sanitize(String input) {
return input.replace("\\", ".").replace("/", ".");
protected List<ModulePackage> getPackagesByRequirement(RequiredType type) { }
if(type == null) return simplePackages;
if(type == RequiredType.BI_CLASS) return biPackages; private boolean containsFiles(Path path) {
if(type == RequiredType.ENUM) return enumPackages; try(Stream<Path> stream = Files.walk(path, 1)) {
return Collections.emptyList(); return stream.filter(Files::isRegularFile).findFirst().isPresent();
} }
catch(Exception e) { e.printStackTrace(); }
private String getModuleInfo(Path basePath) { return false;
StringJoiner joiner = new StringJoiner("\n", "", "\n"); }
try(Stream<Path> stream = Files.walk(getOutputFolder()))
{ private int getVersion() {
stream.filter(Files::isDirectory) String version = System.getProperty("java.version");
.filter(this::containsFiles) if(version.startsWith("1.")) return Integer.parseInt(version.substring(2, 3));
.map(basePath::relativize) int dot = version.indexOf(".");
.map(Path::toString) return Integer.parseInt(dot != -1 ? version.substring(0, dot) : version);
.map(this::sanitize) }
.forEach(T -> joiner.add("\texports "+T+";"));
} public static void main(String...args) {
catch(Exception e) try
{ {
e.printStackTrace(); Set<String> flags = new HashSet<>(Arrays.asList(args));
throw new RuntimeException(e); boolean silent = flags.contains("silent");
} boolean force = flags.contains("force");
StringBuilder builder = new StringBuilder(); boolean tests = flags.contains("tests");
builder.append("/** @author Speiger */\n"); boolean forceTests = flags.contains("force-tests");
builder.append("module ").append(sanitize(basePath.relativize(getOutputFolder()).toString())).append(" {\n"); boolean load = flags.contains("load");
builder.append(joiner.toString()).append("}"); boolean save = flags.contains("save");
return builder.toString(); int flag = (load ? LOAD : 0) | (save ? SAVE : 0);
} new PrimitiveCollectionsBuilder(silent).setFlags(flag).process(force);
if(tests) {
private String sanitize(String input) createTests(silent, flag).process(force || forceTests);
{ createTesters(silent, flag).process(force || forceTests);
return input.replace("\\", ".").replace("/", "."); }
} }
catch(InterruptedException | IOException e)
private boolean containsFiles(Path path) {
{ e.printStackTrace();
try(Stream<Path> 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<String> 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();
}
}
}
@@ -1,54 +1,100 @@
package speiger.src.builder; package speiger.src.builder;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet; import java.util.TreeSet;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import com.google.gson.internal.Streams; import com.google.gson.internal.Streams;
import com.google.gson.stream.JsonWriter; import com.google.gson.stream.JsonWriter;
import speiger.src.builder.dependencies.IDependency;
import speiger.src.builder.dependencies.IDependency.LoadingState;
import speiger.src.builder.modules.BaseModule; import speiger.src.builder.modules.BaseModule;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class SettingsManager public class SettingsManager
{ {
boolean loaded; boolean loaded;
Map<String, LoadingState> parsedData = new TreeMap<>();
JsonObject data = new JsonObject(); JsonObject data = new JsonObject();
Set<String> moduleNames = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); Set<String> moduleNames = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
Set<IDependency> allDependencies = new LinkedHashSet<>();
public boolean isModuleEnabled(BaseModule base, ClassType keyType, ClassType valueType) { public void resolve() {
if(!loaded) return true; if(!loaded) return;
if(!isEnabled(data, base.getModuleName())) return false; Set<IDependency> roots = new LinkedHashSet<>();
JsonObject result = getObject(data, keyType.getClassPath(), false); Set<IDependency> leafs = new LinkedHashSet<>();
if(!isEnabled(result, "Enabled")) return false; for(IDependency entry : allDependencies) {
if(base.isBiModule()) { if(entry.isRoot()) {
result = getObject(result, valueType.getClassPath(), false); roots.add(entry);
if(!isEnabled(result, "Enabled")) return false; }
if(entry.isLeaf()) {
leafs.add(entry);
}
} }
result = getObject(result, base.getModuleName(), false); /**
return (result.size() <= 0 || isEnabled(result, "Enabled")) && base.areDependenciesLoaded(); * This has to be 2 iteration passes.
} * Due to Key Value Pairs, first pass does all initials keys, and the second pass processes the values.
* May require more passes but extremely unlikely
public boolean isModuleEnabled(BaseModule base, ClassType keyType, ClassType valueType, String entry) */
{ for(int i = 0;i<2;i++) {
if(!loaded) return true; for(ClassType keyType : ModulePackage.TYPE) {
if(!isEnabled(data, base.getModuleName())) return false; for(ClassType valueType : ModulePackage.TYPE) {
JsonObject result = getObject(data, keyType.getClassPath(), false); for(IDependency entry : roots) {
if(!isEnabled(result, "Enabled")) return false; entry.resolveRequirements(keyType, valueType);
if(base.isBiModule()) { }
result = getObject(result, valueType.getClassPath(), false); }
if(!isEnabled(result, "Enabled")) return false; }
}
List<String> errors = new ArrayList<>();
for(ClassType keyType : ModulePackage.TYPE) {
for(ClassType valueType : ModulePackage.TYPE) {
for(IDependency entry : leafs) {
entry.validateDependency(errors::add, keyType, valueType);
}
}
}
if(errors.size() > 0) {
throw new IllegalStateException("Issues with dependencies found: "+String.join("\n", errors));
} }
result = getObject(result, base.getModuleName(), false);
return (result.size() <= 0 || (isEnabled(result, "Enabled") && isEnabled(result, entry))) && base.areDependenciesLoaded();
} }
public void addModule(BaseModule module) { public void addModule(BaseModule module) {
if(loaded) return; if(loaded) {
if(module.isBiModule()) {
for(ClassType keyType : ModulePackage.TYPE) {
for(ClassType valueType : ModulePackage.TYPE) {
if(!module.isModuleValid(keyType, valueType)) continue;
for(IDependency dependency : module.getDependencies(keyType, valueType)) {
dependency.set(parsedData);
allDependencies.add(dependency);
}
}
}
return;
}
for(ClassType keyType : ModulePackage.TYPE) {
if(!module.isModuleValid(keyType, keyType)) continue;
for(IDependency dependency : module.getDependencies(keyType, keyType)) {
dependency.set(parsedData);
allDependencies.add(dependency);
}
}
return;
}
String moduleName = module.getModuleName(); String moduleName = module.getModuleName();
moduleNames.add(moduleName); moduleNames.add(moduleName);
data.addProperty(moduleName, true); data.addProperty(moduleName, true);
@@ -57,9 +103,9 @@ public class SettingsManager
for(ClassType valueType : ModulePackage.TYPE) { for(ClassType valueType : ModulePackage.TYPE) {
if(!module.isModuleValid(keyType, valueType)) continue; if(!module.isModuleValid(keyType, valueType)) continue;
JsonObject obj = new JsonObject(); JsonObject obj = new JsonObject();
obj.addProperty("Enabled", true); for(IDependency dependency : module.getDependencies(keyType, valueType)) {
for(String key : module.getModuleKeys(keyType, valueType)) { String key = dependency.getName();
obj.addProperty(key, true); if(key != null) obj.addProperty(key, true);
} }
addModule(keyType, valueType, true, moduleName, obj); addModule(keyType, valueType, true, moduleName, obj);
} }
@@ -69,18 +115,61 @@ public class SettingsManager
for(ClassType keyType : ModulePackage.TYPE) { for(ClassType keyType : ModulePackage.TYPE) {
if(!module.isModuleValid(keyType, keyType)) continue; if(!module.isModuleValid(keyType, keyType)) continue;
JsonObject obj = new JsonObject(); JsonObject obj = new JsonObject();
obj.addProperty("Enabled", true); for(IDependency dependency : module.getDependencies(keyType, keyType)) {
for(String key : module.getModuleKeys(keyType, keyType)) { String key = dependency.getName();
obj.addProperty(key, true); if(key != null) obj.addProperty(key, true);
} }
addModule(keyType, keyType, false, moduleName, obj); addModule(keyType, keyType, false, moduleName, obj);
} }
} }
public void printModuleSettings(List<BaseModule> modules) {
JsonObject data = new JsonObject();
for(BaseModule module : modules) {
String moduleName = module.getModuleName();
if(module.isBiModule()) {
for(ClassType keyType : ModulePackage.TYPE) {
for(ClassType valueType : ModulePackage.TYPE) {
if(!module.isModuleValid(keyType, valueType)) continue;
JsonObject obj = new JsonObject();
for(IDependency dependency : module.getDependencies(keyType, valueType)) {
String key = dependency.getName();
if(key != null) obj.addProperty(key, dependency.isLoaded(keyType, valueType).getJsonResult());
}
addModule(data, keyType, valueType, true, moduleName, obj);
}
}
continue;
}
for(ClassType keyType : ModulePackage.TYPE) {
if(!module.isModuleValid(keyType, keyType)) continue;
JsonObject obj = new JsonObject();
for(IDependency dependency : module.getDependencies(keyType, keyType)) {
String key = dependency.getName();
if(key != null) obj.addProperty(key, dependency.isLoaded(keyType, keyType).getJsonResult());
}
addModule(data, keyType, keyType, false, moduleName, obj);
}
}
try {
System.out.println();
JsonWriter writer = new JsonWriter(new OutputStreamWriter(System.out));
writer.setIndent("\t");
Streams.write(data, writer);
writer.flush();
System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
}
public void load() { public void load() {
try(BufferedReader reader = Files.newBufferedReader(Paths.get("ModulSettings.json"))) { try(BufferedReader reader = Files.newBufferedReader(Paths.get("ModulSettings.json"))) {
data = JsonParser.parseReader(reader).getAsJsonObject(); data = JsonParser.parseReader(reader).getAsJsonObject();
loaded = true; loaded = true;
IDependency.flatten("", false, data, parsedData);
JsonElement element = data.get("Default");
LoadingState.setOptionalResolver(LoadingState.of(element == null ? true : element.getAsBoolean()));
} }
catch(Exception e) { e.printStackTrace(); } catch(Exception e) { e.printStackTrace(); }
} }
@@ -100,6 +189,14 @@ public class SettingsManager
catch(Exception e) { e.printStackTrace(); } catch(Exception e) { e.printStackTrace(); }
} }
private void addModule(JsonObject data, ClassType keyType, ClassType valueType, boolean bi, String moduleName, JsonObject obj) {
JsonObject result = getObject(data, keyType.getClassPath(), true);
if(bi) {
result = getObject(result, valueType.getClassPath(), true);
}
result.add(moduleName, obj);
}
private void addModule(ClassType keyType, ClassType valueType, boolean bi, String moduleName, JsonObject obj) { private void addModule(ClassType keyType, ClassType valueType, boolean bi, String moduleName, JsonObject obj) {
JsonObject result = getObject(data, keyType.getClassPath(), true); JsonObject result = getObject(data, keyType.getClassPath(), true);
if(bi) { if(bi) {
@@ -117,9 +214,4 @@ public class SettingsManager
} }
return obj; return obj;
} }
private boolean isEnabled(JsonObject obj, String key) {
if(obj.has(key)) return obj.getAsJsonPrimitive(key).getAsBoolean();
return true;
}
} }
@@ -0,0 +1,137 @@
package speiger.src.builder.dependencies;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringJoiner;
import java.util.TreeSet;
import java.util.function.Consumer;
import speiger.src.builder.ClassType;
import speiger.src.builder.dependencies.Requirements.Requirement;
@SuppressWarnings("javadoc")
public abstract class BaseDependency implements IDependency {
protected static boolean FETCH_FAILURES = false;
protected static Set<String> FAILURE_KEYS = new TreeSet<>();
protected final String name;
protected final boolean biType;
protected Map<String, LoadingState> dependencies;
protected List<IDependency> children = new ArrayList<>();
protected List<Requirement> requirements = new ArrayList<>();
protected ClassType keyType;
protected ClassType valueType;
public BaseDependency(String name, boolean biType) {
this.name = name;
this.biType = biType;
}
@Override
public String toString() {
return name;
}
@Override
public void set(Map<String, LoadingState> dependency) {
dependencies = dependency;
}
@Override
public IDependency addDependency(Requirement require) {
requirements.add(require);
require.dependency.addChild(this);
return this;
}
@Override
public void addChild(IDependency child) {
children.add(child);
}
@Override
public boolean isLeaf() {
return children.isEmpty();
}
@Override
public boolean isRoot() {
return requirements.isEmpty();
}
protected LoadingState getGlobalState() {
return dependencies.getOrDefault(name, LoadingState.OPTIONAL);
}
@Override
public String getLocalStateKey(ClassType keyType, ClassType valueType) {
return (biType ? keyType.getClassPath()+"-"+valueType.getClassPath() : keyType.getClassPath())+"-"+name;
}
protected LoadingState getLocalState(ClassType keyType, ClassType valueType) {
return dependencies.getOrDefault(getLocalStateKey(keyType, valueType), LoadingState.OPTIONAL);
}
protected LoadingState getReqirementState(ClassType keyType, ClassType valueType) {
LoadingState state = requirements.isEmpty() ? LoadingState.REQUIRED : LoadingState.OPTIONAL;
for(int i = 0,m=requirements.size();i<m;i++) {
state = state.merge(requirements.get(i).test(keyType, valueType));
}
return state.resolveIfUndefined();
}
@Override
public void resolveRequirements(ClassType keyType, ClassType valueType) {
if(!children.isEmpty()) {
for(IDependency child : children) {
if(child == this) continue;
child.resolveRequirements(keyType, valueType);
}
}
if(getLocalState(keyType, valueType) == LoadingState.REQUIRED) {
for(Requirement req : requirements) {
dependencies.putIfAbsent(req.key(keyType, valueType), LoadingState.REQUIRED);
}
}
}
@Override
public void validateDependency(Consumer<String> result, ClassType keyType, ClassType valueType) {
if(getLocalState(keyType, valueType) == LoadingState.REQUIRED) {
FETCH_FAILURES = true;
for(Requirement req : requirements) {
req.test(keyType, valueType);
}
FETCH_FAILURES = false;
if(FAILURE_KEYS.size() > 0) {
int size = FAILURE_KEYS.size();
StringJoiner joiner = new StringJoiner("], [", "[", "]");
FAILURE_KEYS.forEach(joiner::add);
FAILURE_KEYS.clear();
String joins = size > 1 ? "["+joiner.toString()+"]" : joiner.toString();
result.accept("["+getLocalStateKey(keyType, valueType)+"] Requires "+joins+" but it specifically has been disabled!");
}
}
}
@Override
public void set(ClassType key, ClassType value) {
this.keyType = key;
this.valueType = value;
}
@Override
public boolean isEnabled() {
if(keyType == null || keyType == null) return false;
return isLoaded(keyType, valueType).getJsonResult();
}
@Override
public String getName() {
return name;
}
}
@@ -0,0 +1,29 @@
package speiger.src.builder.dependencies;
import speiger.src.builder.ClassType;
@SuppressWarnings("javadoc")
public class FunctionDependency extends BaseDependency {
ModuleDependency owner;
public FunctionDependency(ModuleDependency owner, String name) {
super(name, owner.biType);
this.owner = owner;
}
@Override
public LoadingState isLoaded(ClassType key, ClassType value) {
if(dependencies == null) return LoadingState.REQUIRED;
LoadingState result = getLocalState(key, value);
if(FETCH_FAILURES && result == LoadingState.REJECTED) {
FAILURE_KEYS.add(getLocalStateKey(key, value));
}
return result.resolveIfUndefined().merge(getReqirementState(key, value));
}
@Override
public String getLocalStateKey(ClassType keyType, ClassType valueType) {
return (biType ? keyType.getClassPath()+"-"+valueType.getClassPath() : keyType.getClassPath())+"-"+owner.getName()+"-"+name;
}
}
@@ -0,0 +1,104 @@
package speiger.src.builder.dependencies;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Consumer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import speiger.src.builder.ClassType;
import speiger.src.builder.dependencies.Requirements.Requirement;
@SuppressWarnings("javadoc")
public interface IDependency {
public void set(Map<String, LoadingState> dependency);
public void set(ClassType key, ClassType value);
public LoadingState isLoaded(ClassType key, ClassType value);
public String getLocalStateKey(ClassType keyType, ClassType valueType);
public boolean isEnabled();
public boolean isLeaf();
public boolean isRoot();
public String getName();
public void validateDependency(Consumer<String> result, ClassType keyType, ClassType valueType);
public void resolveRequirements(ClassType keyType, ClassType valueType);
public void addChild(IDependency child);
public <T extends IDependency> T addDependency(Requirement require);
public default <T extends IDependency> T addKeyDependency(IDependency dependency) { return addDependency(new Requirement(dependency, Requirements.KEY_TEST, Requirements.KEY_GETTER)); }
public default <T extends IDependency> T addValueDependency(IDependency dependency) { return addDependency(new Requirement(dependency, Requirements.VALUE_TEST, Requirements.VALUE_GETTER)); }
public default <T extends IDependency> T addEntryDependency(IDependency dependency) { return addDependency(new Requirement(dependency, Requirements.ENTRY_TEST, Requirements.ENTRY_GETTER)); }
public default <T extends IDependency> T addTypeDependency(IDependency dependency, ClassType type) { return addDependency(new Requirement(dependency, Requirements.typedTest(type), Requirements.typedKey(type))); }
public default <T extends IDependency> T addOptionalTypeDependency(IDependency dependency, ClassType type, boolean key) { return addDependency(new Requirement(dependency, Requirements.optionalTest(type, key), Requirements.optionalKey(type, key))); }
public default <T extends IDependency> T addOptionalTypeDependency(ClassType type, boolean key) { return addDependency(new Requirement(this, Requirements.optionalTest(type, key), Requirements.optionalKey(type, key))); }
public static void flatten(String prefix, boolean applyMiddle, JsonObject object, Map<String, LoadingState> result) {
if(applyMiddle) prefix+="-";
for(Entry<String, JsonElement> entry : object.entrySet()) {
String key = entry.getKey();
JsonElement value = entry.getValue();
if(value instanceof JsonPrimitive) {
String entryKey = prefix+key;
if("Enabled".equalsIgnoreCase(key)) {
entryKey = prefix.substring(0, prefix.length()-1);
}
result.put(entryKey, LoadingState.of(((JsonPrimitive)value).getAsBoolean()));
}
if(value instanceof JsonObject) {
flatten(prefix+key, true, (JsonObject)value, result);
}
}
}
public static enum LoadingState {
OPTIONAL,
REQUIRED,
REJECTED;
private static LoadingState RESOLVED = LoadingState.REQUIRED;
public static LoadingState of(boolean value) {
return value ? REQUIRED : REJECTED;
}
public LoadingState merge(LoadingState merge) {
return ordinal() > merge.ordinal() ? this : merge;
}
public LoadingState replaceIfUndefined(LoadingState state) {
return this == OPTIONAL ? state : this;
}
public LoadingState resolveIfUndefined() {
return this == OPTIONAL ? RESOLVED : this;
}
public LoadingState mergeDown(LoadingState merge) {
if(merge == REJECTED || ordinal() > merge.ordinal()) {
return this;
}
return merge;
}
public LoadingState mergeUp(LoadingState merge) {
if(merge == REQUIRED || ordinal() > merge.ordinal()) {
return this;
}
return merge;
}
public static void setOptionalResolver(LoadingState state) {
RESOLVED = state;
}
public boolean getJsonResult() {
LoadingState state = this == OPTIONAL ? RESOLVED : this;
return state == REQUIRED;
}
}
}
@@ -0,0 +1,31 @@
package speiger.src.builder.dependencies;
import speiger.src.builder.ClassType;
import speiger.src.builder.modules.BaseModule;
@SuppressWarnings("javadoc")
public class ModuleDependency extends BaseDependency {
BaseModule owner;
public ModuleDependency(BaseModule owner, boolean biType) {
super(owner.getModuleName(), biType);
this.owner = owner;
}
public FunctionDependency createDependency(String name) {
FunctionDependency result = new FunctionDependency(this, name);
if(biType) result.addEntryDependency(this);
else result.addKeyDependency(this);
return result;
}
@Override
public LoadingState isLoaded(ClassType key, ClassType value) {
if(dependencies == null) return LoadingState.REQUIRED;
LoadingState result = getLocalState(key, value);
if(FETCH_FAILURES && result == LoadingState.REJECTED) {
FAILURE_KEYS.add(getLocalStateKey(key, value));
}
return result.replaceIfUndefined(getGlobalState()).resolveIfUndefined().merge(getReqirementState(key, value));
}
}
@@ -0,0 +1,68 @@
package speiger.src.builder.dependencies;
import java.util.function.Consumer;
import speiger.src.builder.ClassType;
import speiger.src.builder.dependencies.IDependency.LoadingState;
@SuppressWarnings("javadoc")
public class Requirements {
public static final RequirementTest KEY_TEST = (T, K, V) -> T.isLoaded(K, K);
public static final RequirementTest VALUE_TEST = (T, K, V) -> T.isLoaded(V, V);
public static final RequirementTest ENTRY_TEST = (T, K, V) -> T.isLoaded(K, V);
public static RequirementTest typedTest(ClassType type) {
return (T, K, V) -> T.isLoaded(type, type);
}
public static RequirementTest optionalTest(ClassType type, boolean key) {
return (T, K, V) -> (key ? K : V) != type ? T.isLoaded(type, type) : LoadingState.REQUIRED;
}
public static final RequirementKey KEY_GETTER = (T, K, V) -> T.getLocalStateKey(K, K);
public static final RequirementKey VALUE_GETTER = (T, K, V) -> T.getLocalStateKey(V, V);
public static final RequirementKey ENTRY_GETTER = (T, K, V) -> T.getLocalStateKey(K, V);
public static RequirementKey typedKey(ClassType type) {
return (T, K, V) -> T.getLocalStateKey(type, type);
}
public static RequirementKey optionalKey(ClassType type, boolean key) {
return (T, K, V) -> (key ? K : V) != type ? T.getLocalStateKey(type, type) : "";
}
public interface RequirementTest {
public LoadingState test(IDependency test, ClassType keyType, ClassType valueType);
}
public static interface RequirementKey {
public String key(IDependency test, ClassType keyType, ClassType valueType);
}
public static interface RequirementResolver {
public void resolve(IDependency test, Consumer<String> result, ClassType keyType, ClassType valueType);
}
public static class Requirement {
IDependency dependency;
RequirementTest test;
RequirementKey key;
public Requirement(IDependency dependency, RequirementTest test, RequirementKey key) {
this.dependency = dependency;
this.test = test;
this.key = key;
}
public LoadingState test(ClassType keyType, ClassType valueType) {
return test.test(dependency, keyType, valueType);
}
public String key(ClassType keyType, ClassType valueType) {
return key.key(dependency, keyType, valueType);
}
}
}
@@ -1,9 +1,17 @@
package speiger.src.builder.modules; package speiger.src.builder.modules;
import java.util.Arrays;
import java.util.List;
import speiger.src.builder.ClassType;
import speiger.src.builder.dependencies.IDependency;
import speiger.src.builder.dependencies.ModuleDependency;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class AsyncModule extends BaseModule public class AsyncModule extends BaseModule
{ {
public static final BaseModule INSTANCE = new AsyncModule(); public static final BaseModule INSTANCE = new AsyncModule();
public static final ModuleDependency MODULE = new ModuleDependency(INSTANCE, false).addKeyDependency(JavaModule.MODULE);
@Override @Override
public String getModuleName() { return "Async"; } public String getModuleName() { return "Async"; }
@@ -16,16 +24,16 @@ public class AsyncModule extends BaseModule
@Override @Override
protected void loadFunctions() {} protected void loadFunctions() {}
@Override @Override
public boolean areDependenciesLoaded() { return isDependencyLoaded(CollectionModule.INSTANCE); } public List<IDependency> getDependencies(ClassType keyType, ClassType valueType) { return Arrays.asList(MODULE); }
@Override @Override
protected void loadBlockades() { protected void loadBlockades() {
if(!isModuleEnabled()) { if(!MODULE.isEnabled()) {
addBlockedFiles("AsyncBuilder", "Task"); addBlockedFiles("AsyncBuilder", "Task");
} }
} }
@Override @Override
protected void loadFlags() { protected void loadFlags() {
if(isModuleEnabled()) { if(MODULE.isEnabled()) {
addKeyFlag("ASYNC_MODULE"); addKeyFlag("ASYNC_MODULE");
} }
} }
@@ -1,13 +1,15 @@
package speiger.src.builder.modules; package speiger.src.builder.modules;
import java.util.Collections; import java.util.Collections;
import java.util.Set; import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate; import java.util.function.Predicate;
import speiger.src.builder.ClassType; import speiger.src.builder.ClassType;
import speiger.src.builder.ModulePackage; import speiger.src.builder.ModulePackage;
import speiger.src.builder.RequiredType; import speiger.src.builder.RequiredType;
import speiger.src.builder.SettingsManager; import speiger.src.builder.SettingsManager;
import speiger.src.builder.dependencies.IDependency;
import speiger.src.builder.mappers.ArgumentMapper; import speiger.src.builder.mappers.ArgumentMapper;
import speiger.src.builder.mappers.InjectMapper; import speiger.src.builder.mappers.InjectMapper;
import speiger.src.builder.mappers.LineMapper; import speiger.src.builder.mappers.LineMapper;
@@ -30,6 +32,9 @@ public abstract class BaseModule
this.entry = entry; this.entry = entry;
keyType = entry.getKeyType(); keyType = entry.getKeyType();
valueType = entry.getValueType(); valueType = entry.getValueType();
for(IDependency dependency : getDependencies(keyType, valueType)) {
dependency.set(keyType, valueType);
}
loadVariables(); loadVariables();
loadClasses(); loadClasses();
loadTestClasses(); loadTestClasses();
@@ -56,28 +61,11 @@ public abstract class BaseModule
public abstract String getModuleName(); public abstract String getModuleName();
public boolean isBiModule() { return false; } public boolean isBiModule() { return false; }
public Set<String> getModuleKeys(ClassType keyType, ClassType valueType) { return Collections.emptySet(); } public List<IDependency> getDependencies(ClassType keyType, ClassType valueType) { return Collections.emptyList(); }
public boolean isModuleValid(ClassType keyType, ClassType valueType) { return true; } public boolean isModuleValid(ClassType keyType, ClassType valueType) { return true; }
protected boolean isModuleEnabled() { public ClassType keyType() { return keyType; }
return manager == null || manager.isModuleEnabled(this, keyType, valueType); public ClassType valueType() { return valueType; }
}
protected boolean isModuleEnabled(String name) {
return manager == null || manager.isModuleEnabled(this, keyType, valueType, name);
}
protected boolean isDependencyLoaded(BaseModule module) {
return isDependencyLoaded(module, true);
}
protected boolean isDependencyLoaded(BaseModule module, boolean key) {
return manager == null || (module.isBiModule() ? manager.isModuleEnabled(module, keyType, valueType) : (key ? manager.isModuleEnabled(module, keyType, keyType) : manager.isModuleEnabled(module, valueType, valueType)));
}
public boolean areDependenciesLoaded() {
return true;
}
protected void addFlag(String name) { protected void addFlag(String name) {
entry.addFlag(name); entry.addFlag(name);
@@ -202,4 +190,9 @@ public abstract class BaseModule
entry.addMapper(mapper); entry.addMapper(mapper);
return mapper; return mapper;
} }
public static <T> T make(T input, Consumer<T> processor) {
processor.accept(input);
return input;
}
} }
@@ -1,52 +1,59 @@
package speiger.src.builder.modules; package speiger.src.builder.modules;
import java.util.Arrays; import java.util.Arrays;
import java.util.Set; import java.util.List;
import java.util.TreeSet;
import speiger.src.builder.ClassType; import speiger.src.builder.ClassType;
import speiger.src.builder.dependencies.FunctionDependency;
import speiger.src.builder.dependencies.IDependency;
import speiger.src.builder.dependencies.ModuleDependency;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class CollectionModule extends BaseModule public class CollectionModule extends BaseModule
{ {
public static final BaseModule INSTANCE = new CollectionModule(); public static final BaseModule INSTANCE = new CollectionModule();
public static final ModuleDependency MODULE = new ModuleDependency(INSTANCE, false)
.addKeyDependency(FunctionModule.MODULE)
.addOptionalTypeDependency(FunctionModule.MODULE, ClassType.OBJECT, true)
.addOptionalTypeDependency(FunctionModule.MODULE, ClassType.INT, true)
.addOptionalTypeDependency(ClassType.OBJECT, true);
public static final FunctionDependency STREAMS = MODULE.createDependency("Streams");
public static final FunctionDependency SPLIT_ITERATORS = MODULE.createDependency("Splititerators").addKeyDependency(STREAMS);
public static final FunctionDependency IARRAY = MODULE.createDependency("IArray");
public static final FunctionDependency STRATEGY = MODULE.createDependency("Strategy");
@Override @Override
public String getModuleName() { return "Collection"; } public String getModuleName() { return "Collection"; }
@Override @Override
protected void loadVariables() {} protected void loadVariables() {}
@Override @Override
public boolean areDependenciesLoaded(){ return isDependencyLoaded(JavaModule.INSTANCE); } public List<IDependency> getDependencies(ClassType keyType, ClassType valueType) { return Arrays.asList(MODULE, STREAMS, SPLIT_ITERATORS, IARRAY, STRATEGY); }
@Override
public Set<String> getModuleKeys(ClassType keyType, ClassType valueType)
{
return new TreeSet<>(Arrays.asList("Streams", "Splititerators", "IArray", "Strategy"));
}
@Override @Override
protected void loadFlags() { protected void loadFlags() {
if(isModuleEnabled()) addKeyFlag("COLLECTION_MODULE"); if(MODULE.isEnabled()) addKeyFlag("COLLECTION_MODULE");
if(isModuleEnabled("Streams")) addKeyFlag("STREAM_FEATURE"); if(STREAMS.isEnabled()) addKeyFlag("STREAM_FEATURE");
if(isModuleEnabled("Splititerators")) addKeyFlag("SPLIT_ITERATOR_FEATURE"); if(SPLIT_ITERATORS.isEnabled()) addKeyFlag("SPLIT_ITERATOR_FEATURE");
if(isModuleEnabled("IArray")) addKeyFlag("IARRAY_FEATURE"); if(IARRAY.isEnabled()) addKeyFlag("IARRAY_FEATURE");
} }
@Override @Override
protected void loadBlockades() { protected void loadBlockades() {
if(!isModuleEnabled()) { if(!MODULE.isEnabled()) {
addBlockedFiles("Iterable", "Iterables", "Iterator", "Iterators", "BidirectionalIterator", "ListIterator"); addBlockedFiles("Iterable", "Iterables", "Iterator", "Iterators", "BidirectionalIterator", "ListIterator");
addBlockedFiles("Arrays", "Collection", "AbstractCollection", "Collections", "Stack"); addBlockedFiles("Arrays", "Collection", "OrderedCollection", "AbstractCollection", "Collections", "Stack");
} }
if(!isModuleEnabled("Splititerators")) addBlockedFiles("Splititerator", "Splititerators"); if(!SPLIT_ITERATORS.isEnabled()) addBlockedFiles("Splititerator", "Splititerators");
if(!isModuleEnabled("IArray")) addBlockedFiles("IArray"); if(!IARRAY.isEnabled()) addBlockedFiles("IArray");
if(!isModuleEnabled("Strategy")) addBlockedFiles("Strategy"); if(!STRATEGY.isEnabled()) addBlockedFiles("Strategy");
if(keyType.isObject()) { if(keyType.isObject())
{
addBlockedFiles("Stack"); addBlockedFiles("Stack");
addBlockedFiles("CollectionStreamTester"); addBlockedFiles("CollectionStreamTester");
} }
if(keyType == ClassType.BOOLEAN) { if(keyType == ClassType.BOOLEAN)
{
addBlockedFiles("CollectionRemoveIfTester", "CollectionStreamTester"); addBlockedFiles("CollectionRemoveIfTester", "CollectionStreamTester");
addBlockedFilter(T -> T.endsWith("Tester") && T.startsWith("Iterable")); addBlockedFilter(T -> T.endsWith("Tester") && T.startsWith("Iterable"));
} }
@@ -84,6 +91,7 @@ public class CollectionModule extends BaseModule
{ {
//Abstract Classes //Abstract Classes
addAbstractMapper("ABSTRACT_COLLECTION", "Abstract%sCollection"); addAbstractMapper("ABSTRACT_COLLECTION", "Abstract%sCollection");
addAbstractMapper("REVERSED_ORDERED_COLLECTION", "Reverse%sOrderedCollection");
//Helper Classes //Helper Classes
addClassMapper("ARRAYS", "Arrays"); addClassMapper("ARRAYS", "Arrays");
@@ -94,6 +102,7 @@ public class CollectionModule extends BaseModule
//Interfaces //Interfaces
addClassMapper("COLLECTION", "Collection"); addClassMapper("COLLECTION", "Collection");
addClassMapper("ORDERED_COLLECTION", "OrderedCollection");
addClassMapper("ITERABLE", "Iterable"); addClassMapper("ITERABLE", "Iterable");
addClassMapper("SPLIT_ITERATOR", "Splititerator"); addClassMapper("SPLIT_ITERATOR", "Splititerator");
addClassMapper("LIST_ITERATOR", "ListIterator"); addClassMapper("LIST_ITERATOR", "ListIterator");
@@ -1,12 +1,18 @@
package speiger.src.builder.modules; package speiger.src.builder.modules;
import java.util.Arrays;
import java.util.List;
import speiger.src.builder.ClassType; import speiger.src.builder.ClassType;
import speiger.src.builder.RequiredType; import speiger.src.builder.RequiredType;
import speiger.src.builder.dependencies.IDependency;
import speiger.src.builder.dependencies.ModuleDependency;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class FunctionModule extends BaseModule public class FunctionModule extends BaseModule
{ {
public static final BaseModule INSTANCE = new FunctionModule(); public static final BaseModule INSTANCE = new FunctionModule();
public static final ModuleDependency MODULE = new ModuleDependency(INSTANCE, false).addKeyDependency(JavaModule.MODULE);
@Override @Override
public String getModuleName() { return "Function"; } public String getModuleName() { return "Function"; }
@@ -19,10 +25,17 @@ public class FunctionModule extends BaseModule
@Override @Override
protected void loadTestClasses() {} protected void loadTestClasses() {}
@Override
public List<IDependency> getDependencies(ClassType keyType, ClassType valueType) {
return Arrays.asList(MODULE);
}
@Override @Override
protected void loadBlockades() protected void loadBlockades()
{ {
if(keyType.isObject()) addBlockedFiles("Consumer", "Comparator"); if(keyType.isObject()) addBlockedFiles("Consumer", "Comparator");
if(!MODULE.isEnabled()) addBlockedFiles("Consumer", "BiConsumer", "Comparator", "Supplier", "Optional", "Function", "UnaryOperator");
if(!keyType.needsCustomJDKType()) addBlockedFiles("Optional");
} }
@Override @Override
@@ -48,14 +61,15 @@ public class FunctionModule extends BaseModule
} }
else addBiRequirement("Function"); else addBiRequirement("Function");
addRemapper("BiConsumer", "%sConsumer"); addRemapper("BiConsumer", "%sConsumer");
addRemapper("Optional", "Optional%s");
} }
@Override @Override
protected void loadFunctions() protected void loadFunctions()
{ {
addSimpleMapper("APPLY", keyType.getApply(valueType)); addSimpleMapper("APPLY", keyType.getApply(valueType));
addSimpleMapper("SUPPLY_GET", keyType.isObject() ? "get" : "getAs"+keyType.getCustomJDKType().getNonFileType()); addSimpleMapper("SUPPLY_GET", keyType.isObject() ? "get" : "getAs"+keyType.getNonFileType());
addSimpleMapper("VALUE_SUPPLY_GET", valueType.isObject() ? "get" : "getAs"+valueType.getCustomJDKType().getNonFileType()); addSimpleMapper("VALUE_SUPPLY_GET", valueType.isObject() ? "get" : "getAs"+valueType.getNonFileType());
} }
@Override @Override
@@ -82,6 +96,8 @@ public class FunctionModule extends BaseModule
addFunctionMappers("PREDICATE", "%sPredicate"); addFunctionMappers("PREDICATE", "%sPredicate");
addClassMapper("SUPPLIER", "Supplier"); addClassMapper("SUPPLIER", "Supplier");
addSimpleMapper("OPTIONAL", keyType.isObject() ? "Optional" : String.format("Optional%s", keyType.getFileType()));
addSimpleMapper("VALUE_OPTIONAL", valueType.isObject() ? "Optional" : String.format("Optional%s", valueType.getFileType()));
addAbstractMapper("SINGLE_UNARY_OPERATOR", "%1$s%1$sUnaryOperator"); addAbstractMapper("SINGLE_UNARY_OPERATOR", "%1$s%1$sUnaryOperator");
addBiClassMapper("UNARY_OPERATOR", "UnaryOperator", ""); addBiClassMapper("UNARY_OPERATOR", "UnaryOperator", "");
if(keyType.isObject()) if(keyType.isObject())
@@ -1,221 +1,235 @@
package speiger.src.builder.modules; package speiger.src.builder.modules;
import speiger.src.builder.ClassType; import java.util.Arrays;
import java.util.List;
@SuppressWarnings("javadoc")
public class JavaModule extends BaseModule import speiger.src.builder.ClassType;
{ import speiger.src.builder.dependencies.IDependency;
public static final BaseModule INSTANCE = new JavaModule(); import speiger.src.builder.dependencies.ModuleDependency;
@Override @SuppressWarnings("javadoc")
public String getModuleName() { return "Base"; } public class JavaModule extends BaseModule
@Override {
protected void loadVariables() public static final BaseModule INSTANCE = new JavaModule();
{ public static final ModuleDependency MODULE = new ModuleDependency(INSTANCE, false);
createHelperVars(keyType, false, "KEY");
createHelperVars(valueType, true, "VALUE"); @Override
loadBaseVariables(); public String getModuleName() { return "Base"; }
} @Override
protected void loadVariables()
@Override {
protected void loadFlags() createHelperVars(keyType, false, "KEY");
{ createHelperVars(valueType, true, "VALUE");
addFlag("TYPE_"+keyType.getCapType()); loadBaseVariables();
addFlag("VALUE_"+valueType.getCapType()); }
addValue("JAVA_VERSION", getVersion());
if(keyType == valueType) addFlag("SAME_TYPE"); @Override
if(keyType.hasFunction(valueType)) addFlag("JDK_FUNCTION"); public List<IDependency> getDependencies(ClassType keyType, ClassType valueType) {
if(!keyType.needsCustomJDKType()) addFlag("JDK_TYPE"); return Arrays.asList(MODULE);
if(!keyType.isPrimitiveBlocking()) addFlag("PRIMITIVES"); }
if(!valueType.isPrimitiveBlocking()) addFlag("VALUE_PRIMITIVES");
if(!valueType.needsCustomJDKType()) addFlag("JDK_VALUE"); @Override
} protected void loadFlags()
{
private int getVersion() { addFlag("TYPE_"+keyType.getCapType());
String version = System.getProperty("java.version"); addFlag("VALUE_"+valueType.getCapType());
if(version.startsWith("1.")) return Integer.parseInt(version.substring(2, 3)); addValue("JAVA_VERSION", getVersion());
int dot = version.indexOf("."); if(keyType == valueType) addFlag("SAME_TYPE");
return Integer.parseInt(dot != -1 ? version.substring(0, dot) : version); if(keyType.hasFunction(valueType)) addFlag("JDK_FUNCTION");
} if(!keyType.needsCustomJDKType()) addFlag("JDK_TYPE");
if(!keyType.isPrimitiveBlocking()) addFlag("PRIMITIVES");
@Override if(!valueType.isPrimitiveBlocking()) addFlag("VALUE_PRIMITIVES");
protected void loadRemappers() {} if(!valueType.needsCustomJDKType()) addFlag("JDK_VALUE");
@Override }
protected void loadBlockades() {}
private int getVersion() {
@Override String version = System.getProperty("java.version");
protected void loadFunctions() if(version.startsWith("1.")) return Integer.parseInt(version.substring(2, 3));
{ int dot = version.indexOf(".");
addSimpleMapper("APPLY_KEY_VALUE", keyType.isObject() ? "apply" : "applyAs"+keyType.getNonFileType()); return Integer.parseInt(dot != -1 ? version.substring(0, dot) : version);
addSimpleMapper("APPLY_VALUE", valueType.isObject() ? "apply" : "applyAs"+valueType.getNonFileType()); }
addSimpleMapper("APPLY_CAST", "applyAs"+keyType.getCustomJDKType().getNonFileType());
@Override
//Shared by Maps and Pairs so moved to java. protected void loadRemappers() {}
addFunctionMappers("ENTRY_KEY", "get%sKey"); @Override
addFunctionValueMappers("ENTRY_VALUE", "get%sValue"); protected void loadBlockades() {}
addFunctionMappers("KEY_ENTRY", "set%sKey");
addFunctionValueMappers("VALUE_ENTRY", "set%sValue"); @Override
} protected void loadFunctions()
{
@Override addSimpleMapper("APPLY_KEY_VALUE", keyType.isObject() ? "apply" : "applyAs"+keyType.getNonFileType());
protected void loadClasses() addSimpleMapper("APPLY_VALUE", valueType.isObject() ? "apply" : "applyAs"+valueType.getNonFileType());
{ addSimpleMapper("APPLY_CAST", "applyAs"+keyType.getCustomJDKType().getNonFileType());
if(getVersion() >= 17) addSimpleMapper("RANDOM", "RandomGenerator"); addSimpleMapper("GET_OPTIONAL", keyType.isObject() ? "ofNullable" : "of");
else addSimpleMapper("RANDOM", "Random"); addSimpleMapper("GET_OPTIONAL_VALUE", valueType.isObject() ? "ofNullable" : "of");
addSimpleMapper("JAVA_PREDICATE", keyType.isPrimitiveBlocking() ? "" : keyType.getCustomJDKType().getFileType()+"Predicate");
addSimpleMapper("JAVA_CONSUMER", keyType.isPrimitiveBlocking() ? "" : "java.util.function."+keyType.getCustomJDKType().getFileType()+"Consumer"); //Shared by Maps and Pairs so moved to java.
addSimpleMapper("JAVA_SUPPLIER", keyType.isPrimitiveBlocking() ? "" : "java.util.function."+keyType.getCustomJDKType().getFileType()+"Supplier"); addFunctionMappers("ENTRY_KEY", "get%sKey");
addSimpleMapper("JAVA_FUNCTION", keyType.getFunctionClass(valueType)); addFunctionValueMappers("ENTRY_VALUE", "get%sValue");
addSimpleMapper("JAVA_BINARY_OPERATOR", keyType == ClassType.BOOLEAN ? "" : (keyType.isObject() ? "java.util.function.BinaryOperator" : "java.util.function."+keyType.getCustomJDKType().getFileType()+"BinaryOperator")); addFunctionMappers("KEY_ENTRY", "set%sKey");
addSimpleMapper("JAVA_UNARY_OPERATOR", keyType.isObject() ? "BinaryOperator" : keyType == ClassType.BOOLEAN ? "" : keyType.getCustomJDKType().getFileType()+"UnaryOperator"); addFunctionValueMappers("VALUE_ENTRY", "set%sValue");
addSimpleMapper("JAVA_SPLIT_ITERATOR", keyType.isPrimitiveBlocking() ? "Spliterator" : "Of"+keyType.getCustomJDKType().getFileType()); }
addSimpleMapper("JAVA_STREAM", keyType.isPrimitiveBlocking() ? "" : keyType.getCustomJDKType().getFileType()+"Stream");
addSimpleMapper("JAVA_BUFFER", keyType.getFileType()+"Buffer"); @Override
} protected void loadClasses()
{
@Override if(getVersion() >= 17) addSimpleMapper("RANDOM", "RandomGenerator");
protected void loadTestClasses() else addSimpleMapper("RANDOM", "Random");
{ addSimpleMapper("JAVA_PREDICATE", keyType.isPrimitiveBlocking() ? "" : keyType.getCustomJDKType().getFileType()+"Predicate");
addClassMapper("HELPERS", "Helpers"); addSimpleMapper("JAVA_CONSUMER", keyType.isPrimitiveBlocking() ? "" : "java.util.function."+keyType.getCustomJDKType().getFileType()+"Consumer");
addClassMapper("SAMPLE_ELEMENTS", "Samples"); addSimpleMapper("JAVA_SUPPLIER", keyType.isPrimitiveBlocking() ? "" : "java.util.function."+keyType.getCustomJDKType().getFileType()+"Supplier");
} addSimpleMapper("JAVA_FUNCTION", keyType.getFunctionClass(valueType));
addSimpleMapper("JAVA_BINARY_OPERATOR", keyType == ClassType.BOOLEAN ? "" : (keyType.isObject() ? "java.util.function.BinaryOperator" : "java.util.function."+keyType.getCustomJDKType().getFileType()+"BinaryOperator"));
private void loadBaseVariables() addSimpleMapper("JAVA_UNARY_OPERATOR", keyType.isObject() ? "BinaryOperator" : keyType == ClassType.BOOLEAN ? "" : keyType.getCustomJDKType().getFileType()+"UnaryOperator");
{ addSimpleMapper("JAVA_SPLIT_ITERATOR", keyType.isPrimitiveBlocking() ? "Spliterator" : "Of"+keyType.getCustomJDKType().getFileType());
addSimpleMapper("VALUE_PACKAGE", valueType.getPathType()); addSimpleMapper("JAVA_STREAM", keyType.isPrimitiveBlocking() ? "" : keyType.getCustomJDKType().getFileType()+"Stream");
addSimpleMapper("PACKAGE", keyType.getPathType()); addSimpleMapper("JAVA_BUFFER", keyType.getFileType()+"Buffer");
addSimpleMapper("CLASS_TYPE", keyType.getClassType()); }
addSimpleMapper("CLASS_VALUE_TYPE", valueType.getClassValueType());
addSimpleMapper("KEY_TYPE", keyType.getKeyType()); @Override
addSimpleMapper("KEY_OBJECT_TYPE", keyType.isObject() ? "Object" : keyType.getKeyType()); protected void loadTestClasses()
addSimpleMapper("KEY_STRING_TYPE", keyType.isObject() ? "String" : keyType.getKeyType()); {
addSimpleMapper("KEY_SPECIAL_TYPE", keyType.isObject() ? "E" : keyType.getKeyType()); addClassMapper("HELPERS", "Helpers");
addSimpleMapper("CLASS_OBJECT_TYPE", keyType.getClassType()); addClassMapper("SAMPLE_ELEMENTS", "Samples");
addSimpleMapper("CLASS_OBJECT_VALUE_TYPE", valueType.getClassValueType()); }
addSimpleMapper("CLASS_STRING_TYPE", keyType.isObject() ? "String" : keyType.getClassType());
addSimpleMapper("CLASS_STRING_VALUE_TYPE", valueType.isObject() ? "String" : valueType.getClassValueType()); private void loadBaseVariables()
addSimpleMapper("VALUE_TYPE", valueType.getValueType()); {
addSimpleMapper("VALUE_OBJECT_TYPE", valueType.isObject() ? "Object" : valueType.getValueType()); addSimpleMapper("VALUE_PACKAGE", valueType.getPathType());
addSimpleMapper("VALUE_STRING_TYPE", valueType.isObject() ? "String" : valueType.getValueType()); addSimpleMapper("PACKAGE", keyType.getPathType());
addSimpleMapper("VALUE_SPECIAL_TYPE", valueType.isObject() ? "E" : valueType.getKeyType()); addSimpleMapper("CLASS_TYPE", keyType.getClassType());
addSimpleMapper("KEY_JAVA_TYPE", keyType.getCustomJDKType().getKeyType()); addSimpleMapper("CLASS_VALUE_TYPE", valueType.getClassValueType());
addSimpleMapper("VALUE_JAVA_TYPE", keyType.getCustomJDKType().getKeyType()); addSimpleMapper("KEY_TYPE", keyType.getKeyType());
addSimpleMapper("KEY_OBJECT_TYPE", keyType.isObject() ? "Object" : keyType.getKeyType());
addSimpleMapper("EMPTY_KEY_VALUE", keyType.getEmptyValue()); addSimpleMapper("KEY_STRING_TYPE", keyType.isObject() ? "String" : keyType.getKeyType());
addSimpleMapper("EMPTY_VALUE", valueType.getEmptyValue()); addSimpleMapper("KEY_SPECIAL_TYPE", keyType.isObject() ? "E" : keyType.getKeyType());
addSimpleMapper("CLASS_OBJECT_TYPE", keyType.getClassType());
addSimpleMapper("INVALID_KEY_VALUE", keyType.getInvalidValue()); addSimpleMapper("CLASS_OBJECT_VALUE_TYPE", valueType.getClassValueType());
addSimpleMapper("INVALID_VALUE", valueType.getInvalidValue()); addSimpleMapper("CLASS_STRING_TYPE", keyType.isObject() ? "String" : keyType.getClassType());
addSimpleMapper("CLASS_STRING_VALUE_TYPE", valueType.isObject() ? "String" : valueType.getClassValueType());
addSimpleMapper(" KEY_STRING_GENERIC_TYPE", keyType.isObject() ? "<String>" : ""); addSimpleMapper("VALUE_TYPE", valueType.getValueType());
addSimpleMapper(" VALUE_STRING_GENERIC_TYPE", valueType.isObject() ? "<String>" : ""); addSimpleMapper("VALUE_OBJECT_TYPE", valueType.isObject() ? "Object" : valueType.getValueType());
addSimpleMapper(" KEY_VALUE_STRING_GENERIC_TYPE", keyType.isObject() ? (valueType.isObject() ? "<String, String>" : "<String>") : (valueType.isObject() ? "<String>" : "")); addSimpleMapper("VALUE_STRING_TYPE", valueType.isObject() ? "String" : valueType.getValueType());
addSimpleMapper("VALUE_SPECIAL_TYPE", valueType.isObject() ? "E" : valueType.getKeyType());
addSimpleMapper(" KEY_SAME_GENERIC_TYPE", keyType.isObject() ? "<T, T>" : ""); addSimpleMapper("KEY_JAVA_TYPE", keyType.getCustomJDKType().getKeyType());
addSimpleMapper(" VALUE_SAME_GENERIC_TYPE", keyType.isObject() ? "<V, V>" : ""); addSimpleMapper("VALUE_JAVA_TYPE", keyType.getCustomJDKType().getKeyType());
addSimpleMapper(" KEY_GENERIC_TYPE", keyType.isObject() ? "<"+keyType.getKeyType()+">" : ""); addSimpleMapper("EMPTY_KEY_VALUE", keyType.getEmptyValue());
addSimpleMapper(" KEY_KEY_GENERIC_TYPE", keyType.isObject() ? "<"+keyType.getKeyType()+", "+keyType.getKeyType()+">" : ""); addSimpleMapper("EMPTY_VALUE", valueType.getEmptyValue());
addSimpleMapper(" KEY_CLASS_GENERIC_TYPE", keyType.isObject() ? "<"+keyType.getClassType()+">" : "");
addSimpleMapper("INVALID_KEY_VALUE", keyType.getInvalidValue());
addSimpleMapper("INVALID_VALUE", valueType.getInvalidValue());
addSimpleMapper(" VALUE_GENERIC_TYPE", valueType.isObject() ? "<"+valueType.getValueType()+">" : "");
addSimpleMapper(" VALUE_VALUE_GENERIC_TYPE", valueType.isObject() ? "<"+valueType.getValueType()+", "+valueType.getValueType()+">" : ""); addSimpleMapper(" KEY_STRING_GENERIC_TYPE", keyType.isObject() ? "<String>" : "");
addSimpleMapper(" VALUE_CLASS_GENERIC_TYPE", valueType.isObject() ? "<"+valueType.getClassValueType()+">" : ""); addSimpleMapper(" VALUE_STRING_GENERIC_TYPE", valueType.isObject() ? "<String>" : "");
addSimpleMapper(" KEY_VALUE_STRING_GENERIC_TYPE", keyType.isObject() ? (valueType.isObject() ? "<String, String>" : "<String>") : (valueType.isObject() ? "<String>" : ""));
addSimpleMapper(" KEY_VALUE_GENERIC_TYPE", keyType.isObject() ? (valueType.isObject() ? "<"+keyType.getKeyType()+", "+valueType.getValueType()+">" : "<"+keyType.getKeyType()+">") : (valueType.isObject() ? "<"+valueType.getValueType()+">" : ""));
addSimpleMapper(" KEY_VALUE_VALUE_GENERIC_TYPE", keyType.isObject() ? (valueType.isObject() ? "<"+keyType.getKeyType()+", "+valueType.getValueType()+", "+valueType.getValueType()+">" : "<"+keyType.getKeyType()+">") : (valueType.isObject() ? "<"+valueType.getValueType()+", "+valueType.getValueType()+">" : "")); addSimpleMapper(" KEY_SAME_GENERIC_TYPE", keyType.isObject() ? "<T, T>" : "");
addInjectMapper(" KEY_VALUE_SPECIAL_GENERIC_TYPE", keyType.isObject() ? (valueType.isObject() ? "<"+keyType.getKeyType()+", "+valueType.getValueType()+", %s>" : "<"+keyType.getKeyType()+", %s>") : (valueType.isObject() ? "<"+valueType.getValueType()+", %s>" : "<%s>")).setBraceType("<>").removeBraces(); addSimpleMapper(" VALUE_SAME_GENERIC_TYPE", keyType.isObject() ? "<V, V>" : "");
addSimpleMapper(" NO_GENERIC_TYPE", keyType.isObject() ? "<?>" : ""); addSimpleMapper(" KEY_GENERIC_TYPE", keyType.isObject() ? "<"+keyType.getKeyType()+">" : "");
addSimpleMapper(" NO_KV_GENERIC_TYPE", keyType.isObject() ? (valueType.isObject() ? "<?, ?>" : "<?>") : valueType.isObject() ? "<?>" : ""); addSimpleMapper(" KEY_KEY_GENERIC_TYPE", keyType.isObject() ? "<"+keyType.getKeyType()+", "+keyType.getKeyType()+">" : "");
addSimpleMapper(" KEY_COMPAREABLE_TYPE", keyType.isObject() ? "<"+keyType.getKeyType()+" extends Comparable<T>>" : ""); addSimpleMapper(" KEY_CLASS_GENERIC_TYPE", keyType.isObject() ? "<"+keyType.getClassType()+">" : "");
addSimpleMapper(" KEY_SUPER_GENERIC_TYPE", keyType.isObject() ? "<? super "+keyType.getKeyType()+">" : "");
addSimpleMapper(" VALUE_SUPER_GENERIC_TYPE", valueType.isObject() ? "<? super "+valueType.getValueType()+">" : ""); addSimpleMapper(" VALUE_GENERIC_TYPE", valueType.isObject() ? "<"+valueType.getValueType()+">" : "");
addSimpleMapper(" KEY_VALUE_SUPER_GENERIC_TYPE", keyType.isObject() ? (valueType.isObject() ? "<? super "+keyType.getKeyType()+", ? super "+valueType.getValueType()+">" : "<? super "+keyType.getKeyType()+">") : (valueType.isObject() ? "<? super "+valueType.getValueType()+">" : "")); addSimpleMapper(" VALUE_VALUE_GENERIC_TYPE", valueType.isObject() ? "<"+valueType.getValueType()+", "+valueType.getValueType()+">" : "");
addSimpleMapper(" VALUE_CLASS_GENERIC_TYPE", valueType.isObject() ? "<"+valueType.getClassValueType()+">" : "");
addSimpleMapper(" KEY_UNKNOWN_GENERIC_TYPE", keyType.isObject() ? "<? extends "+keyType.getKeyType()+">" : "");
addSimpleMapper(" VALUE_UNKNOWN_GENERIC_TYPE", valueType.isObject() ? "<? extends "+valueType.getValueType()+">" : ""); addSimpleMapper(" KEY_VALUE_GENERIC_TYPE", keyType.isObject() ? (valueType.isObject() ? "<"+keyType.getKeyType()+", "+valueType.getValueType()+">" : "<"+keyType.getKeyType()+">") : (valueType.isObject() ? "<"+valueType.getValueType()+">" : ""));
addSimpleMapper(" KEY_VALUE_UNKNOWN_GENERIC_TYPE", keyType.isObject() ? (valueType.isObject() ? "<? extends "+keyType.getKeyType()+", ? extends "+valueType.getValueType()+">" : "<? extends "+keyType.getKeyType()+">") : (valueType.isObject() ? "<? extends "+valueType.getValueType()+">" : "")); addSimpleMapper(" KEY_VALUE_VALUE_GENERIC_TYPE", keyType.isObject() ? (valueType.isObject() ? "<"+keyType.getKeyType()+", "+valueType.getValueType()+", "+valueType.getValueType()+">" : "<"+keyType.getKeyType()+">") : (valueType.isObject() ? "<"+valueType.getValueType()+", "+valueType.getValueType()+">" : ""));
addInjectMapper(" KEY_VALUE_SPECIAL_GENERIC_TYPE", keyType.isObject() ? (valueType.isObject() ? "<"+keyType.getKeyType()+", "+valueType.getValueType()+", %s>" : "<"+keyType.getKeyType()+", %s>") : (valueType.isObject() ? "<"+valueType.getValueType()+", %s>" : "<%s>")).setBraceType("<>").removeBraces();
addSimpleMapper(" KEY_ENUM_VALUE_GENERIC_TYPE", keyType.isObject() ? (valueType.isObject() ? "<"+keyType.getKeyType()+" extends Enum<"+keyType.getKeyType()+">, "+valueType.getValueType()+">" : "<"+keyType.getKeyType()+" extends Enum<"+keyType.getKeyType()+">>") : (valueType.isObject() ? "<"+valueType.getValueType()+">" : ""));
addSimpleMapper(" KEY_VALUE_ENUM_GENERIC_TYPE", keyType.isObject() ? (valueType.isObject() ? "<"+keyType.getKeyType()+", "+valueType.getValueType()+" extends Enum<"+valueType.getValueType()+">>" : "<"+keyType.getKeyType()+">") : (valueType.isObject() ? "<"+valueType.getValueType()+" extends Enum<"+valueType.getValueType()+">>" : "")); addSimpleMapper(" NO_GENERIC_TYPE", keyType.isObject() ? "<?>" : "");
addSimpleMapper(" NO_KV_GENERIC_TYPE", keyType.isObject() ? (valueType.isObject() ? "<?, ?>" : "<?>") : valueType.isObject() ? "<?>" : "");
addInjectMapper(" KEY_SPECIAL_GENERIC_TYPE", keyType.isObject() ? "<%s>" : "").removeBraces().setBraceType("<>"); addSimpleMapper(" KEY_COMPAREABLE_TYPE", keyType.isObject() ? "<"+keyType.getKeyType()+" extends Comparable<T>>" : "");
addInjectMapper(" VALUE_SPECIAL_GENERIC_TYPE", valueType.isObject() ? "<%s>" : "").removeBraces().setBraceType("<>");
addInjectMapper(" KSK_GENERIC_TYPE", keyType.isObject() ? "<%s, "+keyType.getKeyType()+">" : "<%s>").removeBraces().setBraceType("<>"); addSimpleMapper(" KEY_SUPER_GENERIC_TYPE", keyType.isObject() ? "<? super "+keyType.getKeyType()+">" : "");
addInjectMapper(" KKS_GENERIC_TYPE", keyType.isObject() ? "<"+keyType.getKeyType()+", %s>" : "<%s>").removeBraces().setBraceType("<>"); addSimpleMapper(" VALUE_SUPER_GENERIC_TYPE", valueType.isObject() ? "<? super "+valueType.getValueType()+">" : "");
addArgumentMapper(" KSS_GENERIC_TYPE", keyType.isObject() ? "<%1$s, %2$s>" : "<%2$s>").removeBraces().setBraceType("<>"); addSimpleMapper(" KEY_VALUE_SUPER_GENERIC_TYPE", keyType.isObject() ? (valueType.isObject() ? "<? super "+keyType.getKeyType()+", ? super "+valueType.getValueType()+">" : "<? super "+keyType.getKeyType()+">") : (valueType.isObject() ? "<? super "+valueType.getValueType()+">" : ""));
addInjectMapper(" SK_GENERIC_TYPE", keyType.isObject() ? "<%s, "+keyType.getKeyType()+">" : "").removeBraces().setBraceType("<>");
addInjectMapper(" KS_GENERIC_TYPE", keyType.isObject() ? "<"+keyType.getKeyType()+", %s>" : "").removeBraces().setBraceType("<>"); addSimpleMapper(" KEY_UNKNOWN_GENERIC_TYPE", keyType.isObject() ? "<? extends "+keyType.getKeyType()+">" : "");
addInjectMapper(" VSV_GENERIC_TYPE", valueType.isObject() ? "<%s, "+valueType.getValueType()+">" : "<%s>").removeBraces().setBraceType("<>"); addSimpleMapper(" VALUE_UNKNOWN_GENERIC_TYPE", valueType.isObject() ? "<? extends "+valueType.getValueType()+">" : "");
addInjectMapper(" VVS_GENERIC_TYPE", valueType.isObject() ? "<"+valueType.getValueType()+", %s>" : "<%s>").removeBraces().setBraceType("<>"); addSimpleMapper(" KEY_VALUE_UNKNOWN_GENERIC_TYPE", keyType.isObject() ? (valueType.isObject() ? "<? extends "+keyType.getKeyType()+", ? extends "+valueType.getValueType()+">" : "<? extends "+keyType.getKeyType()+">") : (valueType.isObject() ? "<? extends "+valueType.getValueType()+">" : ""));
addArgumentMapper(" VSS_GENERIC_TYPE", valueType.isObject() ? "<%1$s, %2$s>" : "<%2$s>").removeBraces().setBraceType("<>");
addInjectMapper(" SV_GENERIC_TYPE", valueType.isObject() ? "<%s, "+valueType.getValueType()+">" : "").removeBraces().setBraceType("<>"); addSimpleMapper(" KEY_ENUM_VALUE_GENERIC_TYPE", keyType.isObject() ? (valueType.isObject() ? "<"+keyType.getKeyType()+" extends Enum<"+keyType.getKeyType()+">, "+valueType.getValueType()+">" : "<"+keyType.getKeyType()+" extends Enum<"+keyType.getKeyType()+">>") : (valueType.isObject() ? "<"+valueType.getValueType()+">" : ""));
addInjectMapper(" VS_GENERIC_TYPE", valueType.isObject() ? "<"+valueType.getValueType()+", %s>" : "").removeBraces().setBraceType("<>"); addSimpleMapper(" KEY_VALUE_ENUM_GENERIC_TYPE", keyType.isObject() ? (valueType.isObject() ? "<"+keyType.getKeyType()+", "+valueType.getValueType()+" extends Enum<"+valueType.getValueType()+">>" : "<"+keyType.getKeyType()+">") : (valueType.isObject() ? "<"+valueType.getValueType()+" extends Enum<"+valueType.getValueType()+">>" : ""));
addInjectMapper(" KEY_SPECIAL_GENERIC_TYPE", keyType.isObject() ? "<%s>" : "").removeBraces().setBraceType("<>");
addSimpleMapper(" GENERIC_KEY_BRACES", keyType.isObject() ? " <"+keyType.getKeyType()+">" : ""); addInjectMapper(" VALUE_SPECIAL_GENERIC_TYPE", valueType.isObject() ? "<%s>" : "").removeBraces().setBraceType("<>");
addSimpleMapper(" GENERIC_VALUE_BRACES", valueType.isObject() ? " <"+valueType.getValueType()+">" : ""); addInjectMapper(" KSK_GENERIC_TYPE", keyType.isObject() ? "<%s, "+keyType.getKeyType()+">" : "<%s>").removeBraces().setBraceType("<>");
addInjectMapper(" GENERIC_SPECIAL_KEY_BRACES", keyType.isObject() ? " <%s>" : "").removeBraces().setBraceType("<>"); addInjectMapper(" KKS_GENERIC_TYPE", keyType.isObject() ? "<"+keyType.getKeyType()+", %s>" : "<%s>").removeBraces().setBraceType("<>");
addInjectMapper(" GENERIC_SPECIAL_VALUE_BRACES", valueType.isObject() ? " <%s>" : "").removeBraces().setBraceType("<>"); addArgumentMapper(" KSS_GENERIC_TYPE", keyType.isObject() ? "<%1$s, %2$s>" : "<%2$s>").removeBraces().setBraceType("<>");
addSimpleMapper(" GENERIC_KEY_ENUM_VALUE_BRACES", keyType.isObject() ? (valueType.isObject() ? " <"+keyType.getKeyType()+" extends Enum<"+keyType.getKeyType()+">, "+valueType.getValueType()+">" : " <"+keyType.getKeyType()+" extends Enum<"+keyType.getKeyType()+">>") : (valueType.isObject() ? " <"+valueType.getValueType()+">" : "")); addInjectMapper(" SK_GENERIC_TYPE", keyType.isObject() ? "<%s, "+keyType.getKeyType()+">" : "").removeBraces().setBraceType("<>");
addInjectMapper(" KS_GENERIC_TYPE", keyType.isObject() ? "<"+keyType.getKeyType()+", %s>" : "").removeBraces().setBraceType("<>");
addInjectMapper(" GENERIC_KEY_SPECIAL_BRACES", keyType.isObject() ? " <"+keyType.getKeyType()+", %s>" : " <%s>").removeBraces().setBraceType("<>"); addInjectMapper(" VSV_GENERIC_TYPE", valueType.isObject() ? "<%s, "+valueType.getValueType()+">" : "<%s>").removeBraces().setBraceType("<>");
addInjectMapper(" GENERIC_VALUE_SPECIAL_BRACES", valueType.isObject() ? " <"+valueType.getKeyType()+", %s>" : " <%s>").removeBraces().setBraceType("<>"); addInjectMapper(" VVS_GENERIC_TYPE", valueType.isObject() ? "<"+valueType.getValueType()+", %s>" : "<%s>").removeBraces().setBraceType("<>");
addArgumentMapper(" VSS_GENERIC_TYPE", valueType.isObject() ? "<%1$s, %2$s>" : "<%2$s>").removeBraces().setBraceType("<>");
addSimpleMapper(" GENERIC_KEY_VALUE_BRACES", keyType.isObject() ? (valueType.isObject() ? " <"+keyType.getKeyType()+", "+valueType.getValueType()+">" : " <"+keyType.getKeyType()+">") : (valueType.isObject() ? " <"+valueType.getValueType()+">" : "")); addInjectMapper(" SV_GENERIC_TYPE", valueType.isObject() ? "<%s, "+valueType.getValueType()+">" : "").removeBraces().setBraceType("<>");
addSimpleMapper(" COMPAREABLE_KEY_BRACES", keyType.isObject() ? " <"+keyType.getKeyType()+" extends Comparable<T>>" : ""); addInjectMapper(" VS_GENERIC_TYPE", valueType.isObject() ? "<"+valueType.getValueType()+", %s>" : "").removeBraces().setBraceType("<>");
addSimpleMapper("KV_BRACES", keyType.isObject() || valueType.isObject() ? "<>" : "");
addSimpleMapper("VALUE_BRACES", valueType.isObject() ? "<>" : "");
addSimpleMapper("BRACES", keyType.isObject() ? "<>" : ""); addSimpleMapper(" GENERIC_KEY_BRACES", keyType.isObject() ? " <"+keyType.getKeyType()+">" : "");
if(keyType.needsCustomJDKType()) addSimpleMapper(" GENERIC_VALUE_BRACES", valueType.isObject() ? " <"+valueType.getValueType()+">" : "");
{ addInjectMapper(" GENERIC_SPECIAL_KEY_BRACES", keyType.isObject() ? " <%s>" : "").removeBraces().setBraceType("<>");
addSimpleMapper("JAVA_TYPE", keyType.getCustomJDKType().getKeyType()); addInjectMapper(" GENERIC_SPECIAL_VALUE_BRACES", valueType.isObject() ? " <%s>" : "").removeBraces().setBraceType("<>");
addSimpleMapper("SANITY_CAST", "castTo"+keyType.getFileType()); addSimpleMapper(" GENERIC_KEY_ENUM_VALUE_BRACES", keyType.isObject() ? (valueType.isObject() ? " <"+keyType.getKeyType()+" extends Enum<"+keyType.getKeyType()+">, "+valueType.getValueType()+">" : " <"+keyType.getKeyType()+" extends Enum<"+keyType.getKeyType()+">>") : (valueType.isObject() ? " <"+valueType.getValueType()+">" : ""));
}
addSimpleMapper("JAVA_CLASS", keyType.getCustomJDKType().getClassType()); addInjectMapper(" GENERIC_KEY_SPECIAL_BRACES", keyType.isObject() ? " <"+keyType.getKeyType()+", %s>" : " <%s>").removeBraces().setBraceType("<>");
if(valueType.needsCustomJDKType()) addInjectMapper(" GENERIC_VALUE_SPECIAL_BRACES", valueType.isObject() ? " <"+valueType.getKeyType()+", %s>" : " <%s>").removeBraces().setBraceType("<>");
{
addSimpleMapper("SANITY_CAST_VALUE", "castTo"+valueType.getFileType()); addSimpleMapper(" GENERIC_KEY_VALUE_BRACES", keyType.isObject() ? (valueType.isObject() ? " <"+keyType.getKeyType()+", "+valueType.getValueType()+">" : " <"+keyType.getKeyType()+">") : (valueType.isObject() ? " <"+valueType.getValueType()+">" : ""));
} addSimpleMapper(" COMPAREABLE_KEY_BRACES", keyType.isObject() ? " <"+keyType.getKeyType()+" extends Comparable<T>>" : "");
addSimpleMapper("[SPACE]", " "); addSimpleMapper("KV_BRACES", keyType.isObject() || valueType.isObject() ? "<>" : "");
addComment("@ArrayType", "@param <%s> the keyType of array that the operation should be applied"); addSimpleMapper("VALUE_BRACES", valueType.isObject() ? "<>" : "");
addComment("@Type", "@param <%s> the keyType of elements maintained by this Collection"); addSimpleMapper("BRACES", keyType.isObject() ? "<>" : "");
addValueComment("@ValueArrayType", "@param <%s> the keyType of array that the operation should be applied"); if(keyType.needsCustomJDKType())
addValueComment("@ValueType", "@param <%s> the keyType of elements maintained by this Collection"); {
addAnnontion("@PrimitiveOverride", "@Override"); addSimpleMapper("JAVA_TYPE", keyType.getCustomJDKType().getKeyType());
addSimpleMapper("@PrimitiveDoc", ""); addSimpleMapper("SANITY_CAST", "castTo"+keyType.getFileType());
addAnnontion("@Primitive", "@Deprecated"); }
addValueAnnontion("@ValuePrimitiveOverride", "@Override"); addSimpleMapper("JAVA_CLASS", keyType.getCustomJDKType().getClassType());
addValueAnnontion("@ValuePrimitive", "@Deprecated"); if(valueType.needsCustomJDKType())
} {
addSimpleMapper("SANITY_CAST_VALUE", "castTo"+valueType.getFileType());
private void createHelperVars(ClassType type, boolean value, String fix) }
{ addSimpleMapper("[SPACE]", " ");
addArgumentMapper("EQUALS_"+fix+"_TYPE", "Objects.equals(%2$s, "+(type.isObject() ? "%1$s" : fix+"_TO_OBJ(%1$s)")+")").removeBraces(); addComment("@ArrayType", "@param <%s> the keyType of array that the operation should be applied");
addInjectMapper(fix+"_EQUALS_NOT_NULL", type.getComparableValue()+" != "+(type.isPrimitiveBlocking() || type.needsCast() ? type.getEmptyValue() : "0")).removeBraces(); addComment("@Type", "@param <%s> the keyType of elements maintained by this Collection");
addInjectMapper(fix+"_EQUALS_NULL", type.getComparableValue()+" == "+(type.isPrimitiveBlocking() || type.needsCast() ? type.getEmptyValue() : "0")).removeBraces(); addValueComment("@ValueArrayType", "@param <%s> the keyType of array that the operation should be applied");
addArgumentMapper(fix+"_EQUALS_NOT", type.getEquals(true)).removeBraces(); addValueComment("@ValueType", "@param <%s> the keyType of elements maintained by this Collection");
addArgumentMapper(fix+"_EQUALS", type.getEquals(false)).removeBraces(); addSimpleMapper("@Java21", getVersion() >= 21 ? "@Override" : "");
addSimpleMapper("FILE_"+fix+"_TYPE", type.getFileType()); addAnnontion("@PrimitiveOverride", "@Override");
addSimpleMapper("@PrimitiveDoc", "");
addArgumentMapper("COMPAREABLE_TO_"+fix, type.isObject() ? "((Comparable<"+type.getKeyType(value)+">)%1$s).compareTo(("+type.getKeyType(value)+")%2$s)" : type.getClassType(value)+".compare(%1$s, %2$s)").removeBraces(); addAnnontion("@Primitive", "@Deprecated");
addArgumentMapper("COMPARE_TO_"+fix, type.isObject() ? "%1$s.compareTo(%2$s)" : type.getClassType(value)+".compare(%1$s, %2$s)").removeBraces(); addValueAnnontion("@ValuePrimitiveOverride", "@Override");
addValueAnnontion("@ValuePrimitive", "@Deprecated");
addInjectMapper(fix+"_TO_OBJ", type.isObject() ? "%s" : type.getClassType(value)+".valueOf(%s)").removeBraces(); }
addInjectMapper("OBJ_TO_"+fix, type.isObject() ? "%s" : "%s."+type.getKeyType(value)+"Value()").removeBraces();
addInjectMapper("CLASS_TO_"+fix, type.isObject() ? "("+type.getKeyType(value)+")%s" : "(("+type.getClassType(value)+")%s)."+type.getKeyType(value)+"Value()").removeBraces(); private void createHelperVars(ClassType type, boolean value, String fix)
{
addInjectMapper(fix+"_TO_HASH", type.isObject() ? "Objects.hashCode(%s)" : type.getClassType(value)+".hashCode(%s)").removeBraces(); addArgumentMapper("EQUALS_"+fix+"_TYPE", "Objects.equals(%2$s, "+(type.isObject() ? "%1$s" : fix+"_TO_OBJ(%1$s)")+")").removeBraces();
addInjectMapper(fix+"_TO_STRING", type.isObject() ? "Objects.toString(%s)" : type.getClassType(value)+".toString(%s)").removeBraces(); addInjectMapper(fix+"_EQUALS_NOT_NULL", type.getComparableValue()+" != "+(type.isPrimitiveBlocking() || type.needsCast() ? type.getEmptyValue() : "0")).removeBraces();
addInjectMapper(fix+"_EQUALS_NULL", type.getComparableValue()+" == "+(type.isPrimitiveBlocking() || type.needsCast() ? type.getEmptyValue() : "0")).removeBraces();
addSimpleMapper("CAST_"+fix+"_ARRAY ", type.isObject() ? "("+fix+"_TYPE[])" : ""); addArgumentMapper(fix+"_EQUALS_NOT", type.getEquals(true)).removeBraces();
addSimpleMapper("EMPTY_"+fix+"_ARRAY", type.isObject() ? "("+fix+"_TYPE[])ARRAYS.EMPTY_ARRAY" : "ARRAYS.EMPTY_ARRAY"); addArgumentMapper(fix+"_EQUALS", type.getEquals(false)).removeBraces();
addInjectMapper("NEW_"+fix+"_ARRAY", type.isObject() ? "("+fix+"_TYPE[])new Object[%s]" : "new "+fix+"_TYPE[%s]").removeBraces(); addSimpleMapper("FILE_"+fix+"_TYPE", type.getFileType());
addInjectMapper("NEW_SPECIAL_"+fix+"_ARRAY", type.isObject() ? "(E[])new Object[%s]" : "new "+fix+"_TYPE[%s]").removeBraces();
if(value) addInjectMapper("NEW_CLASS_VALUE_ARRAY", type.isObject() ? "(CLASS_VALUE_TYPE[])new Object[%s]" : "new CLASS_VALUE_TYPE[%s]").removeBraces(); addArgumentMapper("COMPAREABLE_TO_"+fix, type.isObject() ? "((Comparable<"+type.getKeyType(value)+">)%1$s).compareTo(("+type.getKeyType(value)+")%2$s)" : type.getClassType(value)+".compare(%1$s, %2$s)").removeBraces();
else addInjectMapper("NEW_CLASS_ARRAY", type.isObject() ? "(CLASS_TYPE[])new Object[%s]" : "new CLASS_TYPE[%s]").removeBraces(); addArgumentMapper("COMPARE_TO_"+fix, type.isObject() ? "%1$s.compareTo(%2$s)" : type.getClassType(value)+".compare(%1$s, %2$s)").removeBraces();
}
} addInjectMapper(fix+"_TO_OBJ", type.isObject() ? "%s" : type.getClassType(value)+".valueOf(%s)").removeBraces();
addInjectMapper("OBJ_TO_"+fix, type.isObject() ? "%s" : "%s."+type.getKeyType(value)+"Value()").removeBraces();
addInjectMapper("CLASS_TO_"+fix, type.isObject() ? "("+type.getKeyType(value)+")%s" : "(("+type.getClassType(value)+")%s)."+type.getKeyType(value)+"Value()").removeBraces();
addInjectMapper(fix+"_TO_HASH", type.isObject() ? "Objects.hashCode(%s)" : type.getClassType(value)+".hashCode(%s)").removeBraces();
addInjectMapper(fix+"_TO_STRING", type.isObject() ? "Objects.toString(%s)" : type.getClassType(value)+".toString(%s)").removeBraces();
addSimpleMapper("CAST_"+fix+"_ARRAY ", type.isObject() ? "("+fix+"_TYPE[])" : "");
addSimpleMapper("EMPTY_"+fix+"_ARRAY", type.isObject() ? "("+fix+"_TYPE[])ARRAYS.EMPTY_ARRAY" : "ARRAYS.EMPTY_ARRAY");
addInjectMapper("NEW_"+fix+"_ARRAY", type.isObject() ? "("+fix+"_TYPE[])new Object[%s]" : "new "+fix+"_TYPE[%s]").removeBraces();
addInjectMapper("NEW_SPECIAL_"+fix+"_ARRAY", type.isObject() ? "(E[])new Object[%s]" : "new "+fix+"_TYPE[%s]").removeBraces();
if(value) addInjectMapper("NEW_CLASS_VALUE_ARRAY", type.isObject() ? "(CLASS_VALUE_TYPE[])new Object[%s]" : "new CLASS_VALUE_TYPE[%s]").removeBraces();
else addInjectMapper("NEW_CLASS_ARRAY", type.isObject() ? "(CLASS_TYPE[])new Object[%s]" : "new CLASS_TYPE[%s]").removeBraces();
}
}
@@ -1,55 +1,57 @@
package speiger.src.builder.modules; package speiger.src.builder.modules;
import java.util.Arrays; import java.util.Arrays;
import java.util.Set; import java.util.List;
import java.util.TreeSet;
import speiger.src.builder.ClassType; import speiger.src.builder.ClassType;
import speiger.src.builder.dependencies.FunctionDependency;
import speiger.src.builder.dependencies.IDependency;
import speiger.src.builder.dependencies.ModuleDependency;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class ListModule extends BaseModule public class ListModule extends BaseModule
{ {
public static final BaseModule INSTANCE = new ListModule(); public static final BaseModule INSTANCE = new ListModule();
public static final ModuleDependency MODULE = new ModuleDependency(INSTANCE, false).addKeyDependency(CollectionModule.MODULE).addKeyDependency(CollectionModule.SPLIT_ITERATORS);
public static final FunctionDependency IMPLEMENTATION = MODULE.createDependency("Implementations");
public static final FunctionDependency WRAPPERS = MODULE.createDependency("Wrappers");
public static final FunctionDependency ARRAY_LIST = MODULE.createDependency("ArrayList").addKeyDependency(IMPLEMENTATION);
public static final FunctionDependency LINKED_LIST = MODULE.createDependency("LinkedList").addKeyDependency(IMPLEMENTATION);
public static final FunctionDependency IMMUTABLE_LIST = MODULE.createDependency("ImmutableList").addKeyDependency(IMPLEMENTATION);
public static final FunctionDependency COPY_ON_WRITE_LIST = MODULE.createDependency("CopyOnWriteList").addKeyDependency(IMPLEMENTATION);
@Override @Override
public String getModuleName() { return "List"; } public String getModuleName() { return "List"; }
@Override @Override
public List<IDependency> getDependencies(ClassType keyType, ClassType valueType) { return Arrays.asList(MODULE, IMPLEMENTATION, WRAPPERS, ARRAY_LIST, LINKED_LIST, IMMUTABLE_LIST, COPY_ON_WRITE_LIST); }
@Override
protected void loadVariables() {} protected void loadVariables() {}
@Override @Override
protected void loadFlags() { protected void loadFlags() {
if(isModuleEnabled()) addKeyFlag("LIST_MODULE"); if(MODULE.isEnabled()) addKeyFlag("LIST_MODULE");
if(isModuleEnabled("Wrappers")) addKeyFlag("LISTS_FEATURE"); if(WRAPPERS.isEnabled()) addKeyFlag("LISTS_FEATURE");
boolean implementations = isModuleEnabled("Implementations"); if(ARRAY_LIST.isEnabled()) addKeyFlag("ARRAY_LIST_FEATURE");
if(implementations && isModuleEnabled("ArrayList")) addKeyFlag("ARRAY_LIST_FEATURE"); if(LINKED_LIST.isEnabled()) addKeyFlag("LINKED_LIST_FEATURE");
if(implementations && isModuleEnabled("LinkedList")) addKeyFlag("LINKED_LIST_FEATURE"); if(IMMUTABLE_LIST.isEnabled()) addKeyFlag("IMMUTABLE_LIST_FEATURE");
if(implementations && isModuleEnabled("ImmutableList")) addKeyFlag("IMMUTABLE_LIST_FEATURE"); if(COPY_ON_WRITE_LIST.isEnabled()) addKeyFlag("COPY_ON_WRITE_LIST_FEATURE");
if(implementations && isModuleEnabled("CopyOnWriteList")) addKeyFlag("COPY_ON_WRITE_LIST_FEATURE");
} }
@Override @Override
protected void loadBlockades() protected void loadBlockades()
{ {
if(!isModuleEnabled("Wrappers")) addBlockedFiles("Lists"); if(!WRAPPERS.isEnabled()) addBlockedFiles("Lists");
boolean implementations = !isModuleEnabled("Implementations"); if(!ARRAY_LIST.isEnabled()) addBlockedFiles("ArrayList");
if(implementations || !isModuleEnabled("ArrayList")) addBlockedFiles("ArrayList"); if(!LINKED_LIST.isEnabled()) addBlockedFiles("LinkedList");
if(implementations || !isModuleEnabled("LinkedList")) addBlockedFiles("LinkedList"); if(!IMMUTABLE_LIST.isEnabled()) addBlockedFiles("ImmutableList");
if(implementations || !isModuleEnabled("ImmutableList")) addBlockedFiles("ImmutableList"); if(!COPY_ON_WRITE_LIST.isEnabled()) addBlockedFiles("CopyOnWriteList");
if(implementations || !isModuleEnabled("CopyOnWriteList")) addBlockedFiles("CopyOnWriteList"); if(!MODULE.isEnabled()) addBlockedFiles("List", "AbstractList");
if(!isModuleEnabled()) addBlockedFiles("List", "AbstractList");
if(keyType.isObject()) addBlockedFiles("ListFillBufferTester"); if(keyType.isObject()) addBlockedFiles("ListFillBufferTester");
if(keyType == ClassType.BOOLEAN) addBlockedFiles("ListFillBufferTester", "ListReplaceAllTester"); if(keyType == ClassType.BOOLEAN) addBlockedFiles("ListFillBufferTester", "ListReplaceAllTester");
} }
@Override
public Set<String> getModuleKeys(ClassType keyType, ClassType valueType) {
return new TreeSet<>(Arrays.asList("Implementations", "Wrappers", "ArrayList", "LinkedList", "ImmutableList", "CopyOnWriteList"));
}
@Override
public boolean areDependenciesLoaded() {
return isDependencyLoaded(CollectionModule.INSTANCE);
}
@Override @Override
protected void loadRemappers() protected void loadRemappers()
@@ -69,7 +71,10 @@ public class ListModule extends BaseModule
protected void loadFunctions() protected void loadFunctions()
{ {
addFunctionMapper("GET_KEY", "get"); addFunctionMapper("GET_KEY", "get");
addFunctionMapper("REMOVE_LAST", "removeLast"); addFunctionMapper("GET_FIRST_KEY", "getFirst");
addFunctionMapper("GET_LAST_KEY", "getLast");
addFunctionMapper("REMOVE_FIRST_KEY", "removeFirst");
addFunctionMapper("REMOVE_LAST_KEY", "removeLast");
addFunctionMapper("REMOVE_SWAP", "swapRemove"); addFunctionMapper("REMOVE_SWAP", "swapRemove");
addFunctionMappers("REPLACE", keyType.isObject() ? "replaceObjects" : "replace%ss"); addFunctionMappers("REPLACE", keyType.isObject() ? "replaceObjects" : "replace%ss");
addFunctionMappers("SORT", "sort%ss"); addFunctionMappers("SORT", "sort%ss");
@@ -1,281 +1,308 @@
package speiger.src.builder.modules; package speiger.src.builder.modules;
import java.util.Arrays; import java.util.ArrayList;
import java.util.Set; import java.util.Arrays;
import java.util.TreeSet; import java.util.List;
import speiger.src.builder.ClassType; import speiger.src.builder.ClassType;
import speiger.src.builder.dependencies.FunctionDependency;
@SuppressWarnings("javadoc") import speiger.src.builder.dependencies.IDependency;
public class MapModule extends BaseModule import speiger.src.builder.dependencies.ModuleDependency;
{
public static final BaseModule INSTANCE = new MapModule(); @SuppressWarnings("javadoc")
public class MapModule extends BaseModule
@Override {
public String getModuleName() { return "Map"; } public static final BaseModule INSTANCE = new MapModule();
@Override public static final ModuleDependency MODULE = new ModuleDependency(INSTANCE, true)
public boolean isBiModule() { return true; } .addKeyDependency(SetModule.MODULE)
@Override .addValueDependency(CollectionModule.MODULE)
protected void loadVariables() {} .addEntryDependency(SetModule.MODULE)
@Override .addTypeDependency(SetModule.MODULE, ClassType.OBJECT);
public boolean isModuleValid(ClassType keyType, ClassType valueType) { return keyType != ClassType.BOOLEAN; } public static final FunctionDependency IMPLEMENTATION = MODULE.createDependency("Implementations");
@Override public static final FunctionDependency WRAPPERS = MODULE.createDependency("Wrappers").addKeyDependency(SetModule.WRAPPERS).addOptionalTypeDependency(SetModule.WRAPPERS, ClassType.OBJECT, true);
public boolean areDependenciesLoaded() { return isDependencyLoaded(SetModule.INSTANCE) && isDependencyLoaded(CollectionModule.INSTANCE, false); }
public static final FunctionDependency ORDERED_MAP = MODULE.createDependency("OrderedMap").addKeyDependency(SetModule.ORDERED_SET).addOptionalTypeDependency(SetModule.ORDERED_SET, ClassType.OBJECT, true);
@Override public static final FunctionDependency SORTED_MAP = MODULE.createDependency("SortedMap").addKeyDependency(SetModule.SORTED_SET).addOptionalTypeDependency(SetModule.SORTED_SET, ClassType.OBJECT, true);
public Set<String> getModuleKeys(ClassType keyType, ClassType valueType) {
Set<String> sets = new TreeSet<>(); public static final FunctionDependency ARRAY_MAP = MODULE.createDependency("ArrayMap").addEntryDependency(ORDERED_MAP).addEntryDependency(IMPLEMENTATION);
sets.addAll(Arrays.asList("Wrappers", "Implementations")); public static final FunctionDependency IMMUTABLE_MAP = MODULE.createDependency("ImmutableMap").addEntryDependency(IMPLEMENTATION);
sets.addAll(Arrays.asList("OrderedMap", "SortedMap"));
sets.addAll(Arrays.asList("ArrayMap", "ConcurrentMap", "ImmutableMap")); public static final FunctionDependency HASH_MAP = MODULE.createDependency("HashMap").addEntryDependency(IMPLEMENTATION);
sets.addAll(Arrays.asList("HashMap", "LinkedHashMap")); public static final FunctionDependency LINKED_MAP = MODULE.createDependency("LinkedHashMap").addEntryDependency(HASH_MAP).addEntryDependency(ORDERED_MAP);
sets.addAll(Arrays.asList("CustomHashMap", "LinkedCustomHashMap"));
sets.addAll(Arrays.asList("EnumMap", "LinkedEnumMap")); public static final FunctionDependency CUSTOM_MAP = MODULE.createDependency("CustomHashMap").addEntryDependency(IMPLEMENTATION).addKeyDependency(CollectionModule.STRATEGY);
sets.addAll(Arrays.asList("AVLTreeMap", "RBTreeMap")); public static final FunctionDependency LINKED_CUSTOM_MAP = MODULE.createDependency("LinkedCustomHashMap").addEntryDependency(CUSTOM_MAP).addEntryDependency(ORDERED_MAP);
return sets;
} public static final FunctionDependency ENUM_MAP = MODULE.createDependency("EnumMap").addEntryDependency(IMPLEMENTATION);
public static final FunctionDependency LINKED_ENUM_MAP = MODULE.createDependency("LinkedEnumMap").addEntryDependency(ENUM_MAP).addEntryDependency(ORDERED_MAP);
@Override
protected void loadFlags() public static final FunctionDependency REF_MAP = MODULE.createDependency("ReferenceHashMap").addEntryDependency(IMPLEMENTATION);
{ public static final FunctionDependency LINKED_REF_MAP = MODULE.createDependency("LinkedReferenceMap").addEntryDependency(REF_MAP).addEntryDependency(ORDERED_MAP);
if(isModuleEnabled()) addFlag("MAP_MODULE");
if(isModuleEnabled("Wrappers")) addFlag("MAPS_FEATURE");
boolean implementations = isModuleEnabled("Implementations"); public static final FunctionDependency CONCURRENT_MAP = MODULE.createDependency("ConcurrentMap").addEntryDependency(IMPLEMENTATION);
boolean hashMap = implementations && isModuleEnabled("HashMap"); public static final FunctionDependency AVL_TREE_MAP = MODULE.createDependency("AVLTreeMap").addEntryDependency(SORTED_MAP).addEntryDependency(IMPLEMENTATION);
boolean customHashMap = implementations && isModuleEnabled("CustomHashMap"); public static final FunctionDependency RB_TREE_MAP = MODULE.createDependency("RBTreeMap").addEntryDependency(SORTED_MAP).addEntryDependency(IMPLEMENTATION);
boolean enumMap = implementations && isModuleEnabled("EnumMap");
@Override
if(isModuleEnabled("OrderedMap")) { public String getModuleName() { return "Map"; }
addFlag("ORDERED_MAP_FEATURE"); @Override
if(isModuleEnabled("ArrayMap")) addFlag("ARRAY_MAP_FEATURE"); public boolean isBiModule() { return true; }
if(hashMap && isModuleEnabled("LinkedHashMap")) addFlag("LINKED_MAP_FEATURE"); @Override
if(customHashMap && isModuleEnabled("LinkedCustomHashMap")) addFlag("LINKED_CUSTOM_MAP_FEATURE"); protected void loadVariables() {}
if(enumMap && isModuleEnabled("LinkedEnumMap")) addFlag("LINKED_ENUM_MAP_FEATURE"); @Override
} public boolean isModuleValid(ClassType keyType, ClassType valueType) { return keyType != ClassType.BOOLEAN; }
if(isModuleEnabled("SortedMap")) { @Override
addFlag("SORTED_MAP_FEATURE"); public List<IDependency> getDependencies(ClassType keyType, ClassType valueType) {
if(implementations && isModuleEnabled("AVLTreeMap")) addFlag("AVL_TREE_MAP_FEATURE"); List<IDependency> dependencies = new ArrayList<>(Arrays.asList(MODULE, ORDERED_MAP, SORTED_MAP, IMPLEMENTATION, WRAPPERS, ARRAY_MAP, IMMUTABLE_MAP, HASH_MAP, LINKED_MAP, CUSTOM_MAP, LINKED_CUSTOM_MAP, CONCURRENT_MAP, AVL_TREE_MAP, RB_TREE_MAP));
if(implementations && isModuleEnabled("RBTreeMap")) addFlag("RB_TREE_MAP_FEATURE"); if(keyType == ClassType.OBJECT) dependencies.addAll(Arrays.asList(ENUM_MAP, LINKED_ENUM_MAP, REF_MAP, LINKED_REF_MAP));
} return dependencies;
if(implementations && isModuleEnabled("ConcurrentMap")) addFlag("CONCURRENT_MAP_FEATURE"); }
if(implementations && isModuleEnabled("ImmutableMap")) addFlag("IMMUTABLE_MAP_FEATURE");
if(hashMap) addFlag("MAP_FEATURE"); @Override
if(customHashMap) addFlag("CUSTOM_MAP_FEATURE"); protected void loadFlags()
if(enumMap) addFlag("ENUM_MAP_FEATURE"); {
} if(MODULE.isEnabled()) addFlag("MAP_MODULE");
if(WRAPPERS.isEnabled()) addFlag("MAPS_FEATURE");
@Override if(ORDERED_MAP.isEnabled()) addFlag("ORDERED_MAP_FEATURE");
protected void loadBlockades() if(ARRAY_MAP.isEnabled()) addFlag("ARRAY_MAP_FEATURE");
{ if(LINKED_MAP.isEnabled()) addFlag("LINKED_MAP_FEATURE");
if(!isModuleEnabled()) addBlockedFiles("Map", "AbstractMap"); if(LINKED_CUSTOM_MAP.isEnabled()) addFlag("LINKED_CUSTOM_MAP_FEATURE");
if(!isModuleEnabled("Wrappers")) addBlockedFiles("Maps"); if(LINKED_ENUM_MAP.isEnabled()) addFlag("LINKED_ENUM_MAP_FEATURE");
boolean implementations = !isModuleEnabled("Implementations");
if(implementations || !isModuleEnabled("ImmutableMap")) addBlockedFiles("ImmutableOpenHashMap"); if(SORTED_MAP.isEnabled()) addFlag("SORTED_MAP_FEATURE");
if(implementations || !isModuleEnabled("ConcurrentMap")) addBlockedFiles("ConcurrentMap", "ConcurrentOpenHashMap"); if(AVL_TREE_MAP.isEnabled()) addFlag("AVL_TREE_MAP_FEATURE");
if(RB_TREE_MAP.isEnabled()) addFlag("RB_TREE_MAP_FEATURE");
boolean ordered = !isModuleEnabled("OrderedMap");
if(ordered) addBlockedFiles("OrderedMap"); if(REF_MAP.isEnabled()) addFlag("REF_MAP_FEATURE");
boolean hashMap = implementations || !isModuleEnabled("HashMap"); if(LINKED_REF_MAP.isEnabled()) addFlag("LINKED_REF_MAP_FEATURE");
if(hashMap) addBlockedFiles("OpenHashMap");
if(hashMap || ordered || !isModuleEnabled("LinkedHashMap")) addBlockedFiles("LinkedOpenHashMap");
if(CONCURRENT_MAP.isEnabled()) addFlag("CONCURRENT_MAP_FEATURE");
boolean customHashMap = implementations || !isModuleEnabled("CustomHashMap"); if(IMMUTABLE_MAP.isEnabled()) addFlag("IMMUTABLE_MAP_FEATURE");
if(customHashMap) addBlockedFiles("OpenCustomHashMap"); if(HASH_MAP.isEnabled()) addFlag("MAP_FEATURE");
if(customHashMap || ordered || !isModuleEnabled("LinkedCustomHashMap")) addBlockedFiles("LinkedOpenCustomHashMap"); if(CUSTOM_MAP.isEnabled()) addFlag("CUSTOM_MAP_FEATURE");
if(ENUM_MAP.isEnabled()) addFlag("ENUM_MAP_FEATURE");
boolean enumMap = implementations || !isModuleEnabled("EnumMap"); }
if(enumMap) addBlockedFiles("EnumMap");
if(enumMap || ordered || !isModuleEnabled("LinkedEnumMap")) addBlockedFiles("LinkedEnumMap"); @Override
protected void loadBlockades()
if(ordered || !isModuleEnabled("ArrayMap")) addBlockedFiles("ArrayMap"); {
if(!MODULE.isEnabled()) addBlockedFiles("Map", "AbstractMap");
boolean sorted = !isModuleEnabled("SortedMap"); if(!WRAPPERS.isEnabled()) addBlockedFiles("Maps");
if(sorted) addBlockedFiles("SortedMap", "NavigableMap"); if(!IMMUTABLE_MAP.isEnabled()) addBlockedFiles("ImmutableOpenHashMap");
if(implementations || sorted || !isModuleEnabled("AVLTreeMap")) addBlockedFiles("AVLTreeMap"); if(!CONCURRENT_MAP.isEnabled()) addBlockedFiles("ConcurrentMap", "ConcurrentOpenHashMap");
if(implementations || sorted || !isModuleEnabled("RBTreeMap")) addBlockedFiles("RBTreeMap"); if(!ORDERED_MAP.isEnabled()) addBlockedFiles("OrderedMap");
if(!REF_MAP.isEnabled()) addBlockedFiles("ReferenceHashMap");
if(keyType == ClassType.BOOLEAN) if(!LINKED_REF_MAP.isEnabled()) addBlockedFiles("LinkedReferenceHashMap");
{ if(!HASH_MAP.isEnabled()) addBlockedFiles("OpenHashMap");
//Main Classes if(!LINKED_MAP.isEnabled()) addBlockedFiles("LinkedOpenHashMap");
addBlockedFiles("SortedMap", "NavigableMap", "RBTreeMap", "AVLTreeMap"); if(!CUSTOM_MAP.isEnabled()) addBlockedFiles("OpenCustomHashMap");
addBlockedFiles("OrderedMap", "ArrayMap", "LinkedOpenHashMap", "LinkedOpenCustomHashMap"); if(!LINKED_CUSTOM_MAP.isEnabled()) addBlockedFiles("LinkedOpenCustomHashMap");
addBlockedFiles("ConcurrentMap", "ConcurrentOpenHashMap"); if(!ENUM_MAP.isEnabled()) addBlockedFiles("EnumMap");
addBlockedFiles("Map", "Maps", "AbstractMap", "ImmutableOpenHashMap", "OpenHashMap", "OpenCustomHashMap"); if(!LINKED_ENUM_MAP.isEnabled()) addBlockedFiles("LinkedEnumMap");
if(!ARRAY_MAP.isEnabled()) addBlockedFiles("ArrayMap");
//Test Classes if(!SORTED_MAP.isEnabled()) addBlockedFiles("SortedMap", "NavigableMap");
addBlockedFiles("TestMap", "MapTests", "MapTestSuiteBuilder", "MapConstructorTests", "TestMapGenerator", "SimpleMapTestGenerator", "DerivedMapGenerators", "AbstractMapTester"); if(!AVL_TREE_MAP.isEnabled()) addBlockedFiles("AVLTreeMap");
addBlockedFiles("TestSortedMapGenerator", "OrderedMapTestSuiteBuilder", "NavigableMapTestSuiteBuilder", "SortedMapTestSuiteBuilder"); if(!RB_TREE_MAP.isEnabled()) addBlockedFiles("RBTreeMap");
addBlockedFiles("TestOrderedMapGenerator");
addBlockedFilter(T -> T.endsWith("Tester") && (T.startsWith("Map") || T.startsWith("OrderedMap") || T.startsWith("SortedMap") || T.startsWith("NavigableMap"))); if(keyType == ClassType.BOOLEAN)
} {
} //Main Classes
addBlockedFiles("SortedMap", "NavigableMap", "RBTreeMap", "AVLTreeMap");
@Override addBlockedFiles("OrderedMap", "ArrayMap", "LinkedOpenHashMap", "LinkedOpenCustomHashMap");
protected void loadRemappers() addBlockedFiles("ConcurrentMap", "ConcurrentOpenHashMap");
{ addBlockedFiles("Map", "Maps", "AbstractMap", "ImmutableOpenHashMap", "OpenHashMap", "OpenCustomHashMap");
//Main Classes
addBiRequirement("Map"); //Test Classes
addBiRequirement("SortedMap"); addBlockedFiles("TestMap", "MapTests", "MapTestSuiteBuilder", "MapConstructorTests", "TestMapGenerator", "SimpleMapTestGenerator", "DerivedMapGenerators", "AbstractMapTester");
addBiRequirement("OrderedMap"); addBlockedFiles("TestSortedMapGenerator", "OrderedMapTestSuiteBuilder", "NavigableMapTestSuiteBuilder", "SortedMapTestSuiteBuilder");
addBiRequirement("NavigableMap"); addBlockedFiles("TestOrderedMapGenerator");
addBiRequirement("ConcurrentMap"); addBlockedFilter(T -> T.endsWith("Tester") && (T.startsWith("Map") || T.startsWith("OrderedMap") || T.startsWith("SortedMap") || T.startsWith("NavigableMap")));
addBiRequirement("AbstractMap"); }
addEnumRequirement("EnumMap"); if(valueType == ClassType.OBJECT) {
addEnumRequirement("LinkedEnumMap"); addBlockedFiles("MapComputeIfAbsentNonDefaultTester", "MapComputeIfPresentNonDefaultTester", "MapComputeNonDefaultTester", "MapSupplyIfAbsentNonDefaultTester");
addBiRequirement("ConcurrentOpenHashMap"); }
addBiRequirement("ImmutableOpenHashMap"); }
addBiRequirement("OpenHashMap");
addBiRequirement("LinkedOpenHashMap"); @Override
addBiRequirement("OpenCustomHashMap"); protected void loadRemappers()
addBiRequirement("LinkedOpenCustomHashMap"); {
addBiRequirement("ArrayMap"); //Main Classes
addBiRequirement("RBTreeMap"); addBiRequirement("Map");
addBiRequirement("AVLTreeMap"); addBiRequirement("SortedMap");
addBiRequirement("Maps"); addBiRequirement("OrderedMap");
addBiRequirement("NavigableMap");
addRemapper("AbstractMap", "Abstract%sMap"); addBiRequirement("ConcurrentMap");
addRemapper("EnumMap", "Enum2%sMap"); addBiRequirement("AbstractMap");
addRemapper("LinkedEnumMap", "LinkedEnum2%sMap"); addEnumRequirement("EnumMap");
addRemapper("ImmutableOpenHashMap", "Immutable%sOpenHashMap"); addEnumRequirement("LinkedEnumMap");
addEnumRequirement("ReferenceHashMap");
//Test Classes addEnumRequirement("LinkedReferenceHashMap");
addBiRequirement("TestMapGenerator"); addBiRequirement("ConcurrentOpenHashMap");
addBiRequirement("TestSortedMapGenerator"); addBiRequirement("ImmutableOpenHashMap");
addBiRequirement("TestOrderedMapGenerator"); addBiRequirement("OpenHashMap");
addBiRequirement("SimpleMapTestGenerator"); addBiRequirement("LinkedOpenHashMap");
addBiRequirement("DerivedMapGenerators"); addBiRequirement("OpenCustomHashMap");
addBiRequirement("AbstractMapTester"); addBiRequirement("LinkedOpenCustomHashMap");
addBiRequirement("MapTestSuiteBuilder"); addBiRequirement("ArrayMap");
addBiRequirement("SortedMapTestSuiteBuilder"); addBiRequirement("RBTreeMap");
addBiRequirement("NavigableMapTestSuiteBuilder"); addBiRequirement("AVLTreeMap");
addBiRequirement("OrderedMapTestSuiteBuilder"); addBiRequirement("Maps");
addBiRequirement("MapTests");
addBiRequirement("MapConstructorTests"); addRemapper("AbstractMap", "Abstract%sMap");
addBiRequirement("TestMap"); addRemapper("EnumMap", "Enum2%sMap");
addBiRequirement("MapAddToTester"); addRemapper("LinkedEnumMap", "LinkedEnum2%sMap");
addBiRequirement("MapSubFromTester"); addRemapper("ReferenceHashMap", "Reference2%sHashMap");
addBiRequirement("MapClearTester"); addRemapper("LinkedReferenceHashMap", "Reference2%sLinkedHashMap");
addBiRequirement("MapComputeIfAbsentTester"); addRemapper("ImmutableOpenHashMap", "Immutable%sOpenHashMap");
addBiRequirement("MapComputeIfPresentTester");
addBiRequirement("MapComputeTester"); //Test Classes
addBiRequirement("MapCopyTester"); addBiRequirement("TestMapGenerator");
addBiRequirement("MapContainsTester"); addBiRequirement("TestSortedMapGenerator");
addBiRequirement("MapContainsKeyTester"); addBiRequirement("TestOrderedMapGenerator");
addBiRequirement("MapContainsValueTester"); addBiRequirement("SimpleMapTestGenerator");
addBiRequirement("MapCreatorTester"); addBiRequirement("DerivedMapGenerators");
addBiRequirement("MapEntrySetTester"); addBiRequirement("AbstractMapTester");
addBiRequirement("MapEqualsTester"); addBiRequirement("MapTestSuiteBuilder");
addBiRequirement("MapForEachTester"); addBiRequirement("SortedMapTestSuiteBuilder");
addBiRequirement("MapGetOrDefaultTester"); addBiRequirement("NavigableMapTestSuiteBuilder");
addBiRequirement("MapGetTester"); addBiRequirement("OrderedMapTestSuiteBuilder");
addBiRequirement("MapHashCodeTester"); addBiRequirement("MapTests");
addBiRequirement("MapIsEmptyTester"); addBiRequirement("MapConstructorTests");
addBiRequirement("MapMergeTester"); addBiRequirement("TestMap");
addBiRequirement("MapMergeBulkTester"); addBiRequirement("MapAddToTester");
addBiRequirement("MapPutAllArrayTester"); addBiRequirement("MapSubFromTester");
addBiRequirement("MapPutAllTester"); addBiRequirement("MapClearTester");
addBiRequirement("MapPutIfAbsentTester"); addBiRequirement("MapComputeIfAbsentTester");
addBiRequirement("MapPutTester"); addBiRequirement("MapComputeIfPresentTester");
addBiRequirement("MapRemoveEntryTester"); addBiRequirement("MapComputeTester");
addBiRequirement("MapRemoveOrDefaultTester"); addBiRequirement("MapComputeIfAbsentNonDefaultTester");
addBiRequirement("MapRemoveTester"); addBiRequirement("MapComputeIfPresentNonDefaultTester");
addBiRequirement("MapReplaceAllTester"); addBiRequirement("MapComputeNonDefaultTester");
addBiRequirement("MapReplaceEntryTester"); addBiRequirement("MapCopyTester");
addBiRequirement("MapReplaceTester"); addBiRequirement("MapContainsTester");
addBiRequirement("MapSizeTester"); addBiRequirement("MapContainsKeyTester");
addBiRequirement("MapSupplyIfAbsentTester"); addBiRequirement("MapContainsValueTester");
addBiRequirement("MapToStringTester"); addBiRequirement("MapCreatorTester");
addBiRequirement("NavigableMapNavigationTester"); addBiRequirement("MapEntrySetTester");
addBiRequirement("SortedMapNavigationTester"); addBiRequirement("MapEqualsTester");
addBiRequirement("OrderedMapNavigationTester"); addBiRequirement("MapForEachTester");
addBiRequirement("OrderedMapMoveTester"); addBiRequirement("MapGetOrDefaultTester");
addBiRequirement("MapConstructorTester"); addBiRequirement("MapGetTester");
addBiRequirement("MapHashCodeTester");
addRemapper("TestMapGenerator", "Test%sMapGenerator"); addBiRequirement("MapIsEmptyTester");
addRemapper("TestSortedMapGenerator", "Test%sSortedMapGenerator"); addBiRequirement("MapMergeTester");
addRemapper("TestOrderedMapGenerator", "Test%sOrderedMapGenerator"); addBiRequirement("MapMergeBulkTester");
addRemapper("SimpleMapTestGenerator", "Simple%sMapTestGenerator"); addBiRequirement("MapPutAllArrayTester");
addRemapper("DerivedMapGenerators", "Derived%sMapGenerators"); addBiRequirement("MapPutAllTester");
addRemapper("AbstractMapTester", "Abstract%sMapTester"); addBiRequirement("MapPutIfAbsentTester");
addRemapper("TestMap", "Test%sMap"); addBiRequirement("MapPutTester");
} addBiRequirement("MapRemoveEntryTester");
addBiRequirement("MapRemoveOrDefaultTester");
@Override addBiRequirement("MapRemoveTester");
protected void loadFunctions() addBiRequirement("MapReplaceAllTester");
{ addBiRequirement("MapReplaceEntryTester");
addFunctionValueMapper("BULK_MERGE", "mergeAll"); addBiRequirement("MapReplaceTester");
addFunctionValueMappers("COMPUTE_IF_ABSENT", "compute%sIfAbsent"); addBiRequirement("MapSizeTester");
addFunctionValueMappers("COMPUTE_IF_PRESENT", "compute%sIfPresent"); addBiRequirement("MapSupplyIfAbsentTester");
addFunctionValueMapper("COMPUTE", "compute"); addBiRequirement("MapSupplyIfAbsentNonDefaultTester");
addFunctionMapper("DEQUEUE_LAST", "dequeueLast"); addBiRequirement("MapToStringTester");
addFunctionMapper("DEQUEUE", "dequeue"); addBiRequirement("NavigableMapNavigationTester");
addSimpleMapper("ENTRY_SET", keyType.getFileType().toLowerCase()+"2"+valueType.getFileType()+"EntrySet"); addBiRequirement("SortedMapNavigationTester");
addFunctionMappers("FIRST_ENTRY_KEY", "first%sKey"); addBiRequirement("OrderedMapNavigationTester");
addFunctionValueMappers("FIRST_ENTRY_VALUE", "first%sValue"); addBiRequirement("OrderedMapMoveTester");
if(keyType.isObject()) addFunctionValueMapper("GET_VALUE", valueType.isObject() ? "getObject" : "get"); addBiRequirement("OrderedMapPutTester");
else addSimpleMapper("GET_VALUE", "get"); addBiRequirement("MapConstructorTester");
addFunctionMappers("LAST_ENTRY_KEY", "last%sKey");
addFunctionValueMappers("LAST_ENTRY_VALUE", "last%sValue"); addRemapper("TestMapGenerator", "Test%sMapGenerator");
addFunctionValueMapper("MERGE", "merge"); addRemapper("TestSortedMapGenerator", "Test%sSortedMapGenerator");
addFunctionMappers("POLL_FIRST_ENTRY_KEY", "pollFirst%sKey"); addRemapper("TestOrderedMapGenerator", "Test%sOrderedMapGenerator");
addFunctionMappers("POLL_LAST_ENTRY_KEY", "pollLast%sKey"); addRemapper("SimpleMapTestGenerator", "Simple%sMapTestGenerator");
if(keyType.isObject()) addFunctionMapper("REMOVE_VALUE", "rem"); addRemapper("DerivedMapGenerators", "Derived%sMapGenerators");
else addSimpleMapper("REMOVE_VALUE", "remove"); addRemapper("AbstractMapTester", "Abstract%sMapTester");
addFunctionMapper("REMOVE", "remove"); addRemapper("TestMap", "Test%sMap");
addFunctionValueMappers("REPLACE_VALUES", valueType.isObject() ? "replaceObjects" : "replace%ss"); }
addFunctionValueMappers("SUPPLY_IF_ABSENT", "supply%sIfAbsent");
} @Override
protected void loadFunctions()
@Override {
protected void loadClasses() addFunctionValueMapper("BULK_MERGE", "mergeAll");
{ addFunctionValueMappers("COMPUTE_IF_ABSENT", "compute%sIfAbsent");
//Implementation Classes addFunctionValueMappers("COMPUTE_IF_PRESENT", "compute%sIfPresent");
addAbstractBiMapper("IMMUTABLE_HASH_MAP", "Immutable%sOpenHashMap", "2"); addFunctionValueMapper("COMPUTE", "compute");
addBiClassMapper("LINKED_CUSTOM_HASH_MAP", "LinkedOpenCustomHashMap", "2"); addFunctionMapper("DEQUEUE_LAST", "dequeueLast");
addBiClassMapper("LINKED_HASH_MAP", "LinkedOpenHashMap", "2"); addFunctionMapper("DEQUEUE", "dequeue");
addBiClassMapper("CUSTOM_HASH_MAP", "OpenCustomHashMap", "2"); addSimpleMapper("ENTRY_SET", keyType.getFileType().toLowerCase()+"2"+valueType.getFileType()+"EntrySet");
addBiClassMapper("CONCURRENT_HASH_MAP", "ConcurrentOpenHashMap", "2"); addFunctionMappers("FIRST_ENTRY_KEY", "first%sKey");
addBiClassMapper("AVL_TREE_MAP", "AVLTreeMap", "2"); addFunctionValueMappers("FIRST_ENTRY_VALUE", "first%sValue");
addBiClassMapper("RB_TREE_MAP", "RBTreeMap", "2"); if(keyType.isObject()) addFunctionValueMapper("GET_VALUE", valueType.isObject() ? "getObject" : "get");
addFunctionValueMappers("LINKED_ENUM_MAP", valueType.isObject() ? "LinkedEnum2ObjectMap" : "LinkedEnum2%sMap"); else addSimpleMapper("GET_VALUE", "get");
addFunctionValueMappers("ENUM_MAP", valueType.isObject() ? "Enum2ObjectMap" : "Enum2%sMap"); addFunctionMappers("LAST_ENTRY_KEY", "last%sKey");
addBiClassMapper("HASH_MAP", "OpenHashMap", "2"); addFunctionValueMappers("LAST_ENTRY_VALUE", "last%sValue");
addBiClassMapper("ARRAY_MAP", "ArrayMap", "2"); addFunctionValueMapper("MERGE", "merge");
addFunctionMappers("POLL_FIRST_ENTRY_KEY", "pollFirst%sKey");
//Abstract Classes addFunctionMappers("POLL_LAST_ENTRY_KEY", "pollLast%sKey");
addAbstractBiMapper("ABSTRACT_MAP", "Abstract%sMap", "2"); if(keyType.isObject()) addFunctionMapper("REMOVE_VALUE", "rem");
else addSimpleMapper("REMOVE_VALUE", "remove");
//Helper Classes addFunctionMapper("REMOVE", "remove");
addBiClassMapper("MAPS", "Maps", "2"); addFunctionValueMappers("REPLACE_VALUES", valueType.isObject() ? "replaceObjects" : "replace%ss");
addFunctionValueMappers("SUPPLY_IF_ABSENT", "supply%sIfAbsent");
//Interfaces }
addBiClassMapper("NAVIGABLE_MAP", "NavigableMap", "2");
addBiClassMapper("ORDERED_MAP", "OrderedMap", "2"); @Override
addBiClassMapper("SORTED_MAP", "SortedMap", "2"); protected void loadClasses()
addBiClassMapper("CONCURRENT_MAP", "ConcurrentMap", "2"); {
addBiClassMapper("MAP", "Map", "2"); //Implementation Classes
} addAbstractBiMapper("IMMUTABLE_HASH_MAP", "Immutable%sOpenHashMap", "2");
addBiClassMapper("LINKED_CUSTOM_HASH_MAP", "LinkedOpenCustomHashMap", "2");
@Override addBiClassMapper("LINKED_HASH_MAP", "LinkedOpenHashMap", "2");
protected void loadTestClasses() addBiClassMapper("CUSTOM_HASH_MAP", "OpenCustomHashMap", "2");
{ addBiClassMapper("CONCURRENT_HASH_MAP", "ConcurrentOpenHashMap", "2");
//Implementation Classes addBiClassMapper("AVL_TREE_MAP", "AVLTreeMap", "2");
addAbstractBiMapper("SIMPLE_TEST_MAP", "Test%sMap", "2"); addBiClassMapper("RB_TREE_MAP", "RBTreeMap", "2");
addBiClassMapper("MAP_TESTS", "MapTests", "2"); addFunctionValueMappers("LINKED_ENUM_MAP", valueType.isObject() ? "LinkedEnum2ObjectMap" : "LinkedEnum2%sMap");
addAbstractBiMapper("NAVIGABLE_MAP_TEST_BUILDER", "%sNavigableMapTestSuiteBuilder", "2"); addFunctionValueMappers("ENUM_MAP", valueType.isObject() ? "Enum2ObjectMap" : "Enum2%sMap");
addAbstractBiMapper("SORTED_MAP_TEST_BUILDER", "%sSortedMapTestSuiteBuilder", "2"); addFunctionValueMappers("REF_MAP", valueType.isObject() ? "Reference2ObjectHashMap" : "Reference2%sHashMap");
addAbstractBiMapper("ORDERED_MAP_TEST_BUILDER", "%sOrderedMapTestSuiteBuilder", "2"); addFunctionValueMappers("LINKED_REF_MAP", valueType.isObject() ? "Reference2ObjectLinkedHashMap" : "Reference2%sLinkedHashMap");
addAbstractBiMapper("MAP_TEST_BUILDER", "%sMapTestSuiteBuilder", "2"); addBiClassMapper("HASH_MAP", "OpenHashMap", "2");
addBiClassMapper("ARRAY_MAP", "ArrayMap", "2");
//Abstract Classes
addAbstractBiMapper("ABSTRACT_MAP_TESTER", "Abstract%sMapTester", "2"); //Abstract Classes
addAbstractBiMapper("ABSTRACT_MAP", "Abstract%sMap", "2");
//Helper Classes addAbstractBiMapper("REVERSED_ORDERED_MAP", "Reversed%sOrderedMap", "2");
addAbstractBiMapper("MAP_CONSTRUCTOR_TESTS", "%sMapConstructorTests", "2");
addAbstractBiMapper("SIMPLE_MAP_TEST_GENERATOR", "Simple%sMapTestGenerator", "2"); //Helper Classes
addAbstractBiMapper("DERIVED_MAP_GENERATORS", "Derived%sMapGenerators", "2"); addBiClassMapper("MAPS", "Maps", "2");
addAbstractBiMapper("TEST_ORDERED_MAP_GENERATOR", "Test%sOrderedMapGenerator", "2");
addAbstractBiMapper("TEST_SORTED_MAP_GENERATOR", "Test%sSortedMapGenerator", "2"); //Interfaces
addAbstractBiMapper("TEST_MAP_GENERATOR", "Test%sMapGenerator", "2"); 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");
}
} }
@@ -1,15 +1,26 @@
package speiger.src.builder.modules; package speiger.src.builder.modules;
import java.util.Arrays; import java.util.Arrays;
import java.util.Set; import java.util.List;
import java.util.TreeSet;
import speiger.src.builder.ClassType; import speiger.src.builder.ClassType;
import speiger.src.builder.dependencies.FunctionDependency;
import speiger.src.builder.dependencies.IDependency;
import speiger.src.builder.dependencies.ModuleDependency;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class PairModule extends BaseModule public class PairModule extends BaseModule
{ {
public static final BaseModule INSTANCE = new PairModule(); public static final BaseModule INSTANCE = new PairModule();
public static final ModuleDependency MODULE = new ModuleDependency(INSTANCE, true).addKeyDependency(JavaModule.MODULE);
public static final FunctionDependency IMMUTABLE = MODULE.createDependency("Immutable");
public static final FunctionDependency MUTABLE = MODULE.createDependency("Mutable");
// public static final DependencyModule MODULE = new BiTypeModule(INSTANCE);
// public static final DependencyFunction IMMUTABLE = MODULE.createFunction("Immutable");
// public static final DependencyFunction MUTABLE = MODULE.createFunction("Mutable");
@Override @Override
public String getModuleName() { return "Pair"; } public String getModuleName() { return "Pair"; }
@Override @Override
@@ -21,20 +32,20 @@ public class PairModule extends BaseModule
@Override @Override
protected void loadTestClasses() {} protected void loadTestClasses() {}
@Override @Override
public Set<String> getModuleKeys(ClassType keyType, ClassType valueType) { return new TreeSet<>(Arrays.asList("Mutable", "Immutable")); } public List<IDependency> getDependencies(ClassType keyType, ClassType valueType) { return Arrays.asList(MODULE, IMMUTABLE, MUTABLE); }
@Override @Override
protected void loadFlags() { protected void loadFlags() {
if(isModuleEnabled()) addFlag("PAIR_MODULE"); if(MODULE.isEnabled()) addFlag("PAIR_MODULE");
if(isModuleEnabled("Mutable")) addFlag("MUTABLE_PAIR"); if(MUTABLE.isEnabled()) addFlag("MUTABLE_PAIR");
if(isModuleEnabled("Immutable")) addFlag("IMMUTABLE_PAIR"); if(IMMUTABLE.isEnabled()) addFlag("IMMUTABLE_PAIR");
} }
@Override @Override
protected void loadBlockades() { protected void loadBlockades() {
if(!isModuleEnabled()) addBlockedFiles("Pair"); if(!MODULE.isEnabled()) addBlockedFiles("Pair");
if(!isModuleEnabled("Mutable")) addBlockedFiles("MutablePair"); if(!MUTABLE.isEnabled()) addBlockedFiles("MutablePair");
if(!isModuleEnabled("Immutable")) addBlockedFiles("ImmutablePair"); if(!IMMUTABLE.isEnabled()) addBlockedFiles("ImmutablePair");
} }
@Override @Override
@@ -1,15 +1,26 @@
package speiger.src.builder.modules; package speiger.src.builder.modules;
import java.util.Arrays; import java.util.Arrays;
import java.util.Set; import java.util.List;
import java.util.TreeSet;
import speiger.src.builder.ClassType; import speiger.src.builder.ClassType;
import speiger.src.builder.dependencies.FunctionDependency;
import speiger.src.builder.dependencies.IDependency;
import speiger.src.builder.dependencies.ModuleDependency;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class PrioQueueModule extends BaseModule public class PrioQueueModule extends BaseModule
{ {
public static final BaseModule INSTANCE = new PrioQueueModule(); public static final BaseModule INSTANCE = new PrioQueueModule();
public static final ModuleDependency MODULE = new ModuleDependency(INSTANCE, false).addKeyDependency(CollectionModule.MODULE);
public static final FunctionDependency IMPLEMENTATION = MODULE.createDependency("Implementations");
public static final FunctionDependency WRAPPERS = MODULE.createDependency("Wrappers");
public static final FunctionDependency DEQUEUE = MODULE.createDependency("Dequeue");
public static final FunctionDependency FIFO_QUEUE = MODULE.createDependency("FiFoQueue").addKeyDependency(DEQUEUE).addKeyDependency(IMPLEMENTATION);
public static final FunctionDependency HEAP_QUEUE = MODULE.createDependency("HeapQueue").addKeyDependency(IMPLEMENTATION);
public static final FunctionDependency ARRAY_PRIO_QUEUE = MODULE.createDependency("ArrayPrioQueue").addKeyDependency(IMPLEMENTATION);
@Override @Override
public String getModuleName() { return "PriorityQueue"; } public String getModuleName() { return "PriorityQueue"; }
@@ -18,36 +29,26 @@ public class PrioQueueModule extends BaseModule
@Override @Override
protected void loadFunctions() {} protected void loadFunctions() {}
@Override @Override
public boolean areDependenciesLoaded() { return isDependencyLoaded(CollectionModule.INSTANCE); } public List<IDependency> getDependencies(ClassType keyType, ClassType valueType) { return Arrays.asList(MODULE, WRAPPERS, IMPLEMENTATION, DEQUEUE, FIFO_QUEUE, HEAP_QUEUE, ARRAY_PRIO_QUEUE); }
@Override
public Set<String> getModuleKeys(ClassType keyType, ClassType valueType) {
return new TreeSet<>(Arrays.asList("Wrappers", "Implementations", "Dequeue", "FiFoQueue", "HeapQueue", "ArrayPrioQueue"));
}
@Override @Override
protected void loadFlags() { protected void loadFlags() {
if(isModuleEnabled()) addFlag("QUEUE_MODULE"); if(MODULE.isEnabled()) addFlag("QUEUE_MODULE");
if(isModuleEnabled("Wrappers")) addKeyFlag("QUEUES_FEATURE"); if(WRAPPERS.isEnabled()) addKeyFlag("QUEUES_FEATURE");
boolean implementations = isModuleEnabled("Implementations"); if(DEQUEUE.isEnabled()) addKeyFlag("DEQUEUE_FEATURE");
if(isModuleEnabled("Dequeue")) { if(FIFO_QUEUE.isEnabled()) addKeyFlag("FIFO_QUEUE_FEATURE");
addKeyFlag("DEQUEUE_FEATURE"); if(HEAP_QUEUE.isEnabled()) addKeyFlag("HEAP_QUEUE_FEATURE");
if(implementations && isModuleEnabled("FiFoQueue")) addKeyFlag("FIFO_QUEUE_FEATURE"); if(ARRAY_PRIO_QUEUE.isEnabled()) addKeyFlag("ARRAY_QUEUE_FEATURE");
}
if(implementations && isModuleEnabled("HeapQueue")) addKeyFlag("HEAP_QUEUE_FEATURE");
if(implementations && isModuleEnabled("ArrayPrioQueue")) addKeyFlag("ARRAY_QUEUE_FEATURE");
} }
@Override @Override
protected void loadBlockades() { protected void loadBlockades() {
if(!isModuleEnabled()) addBlockedFiles("PriorityQueue", "AbstractPriorityQueue"); if(!MODULE.isEnabled()) addBlockedFiles("PriorityQueue", "AbstractPriorityQueue");
if(!isModuleEnabled("Wrappers")) addBlockedFiles("PriorityQueues"); if(!WRAPPERS.isEnabled()) addBlockedFiles("PriorityQueues");
boolean implementations = !isModuleEnabled("Implementations"); if(!DEQUEUE.isEnabled()) addBlockedFiles("PriorityDequeue");
boolean dequeue = !isModuleEnabled("Dequeue"); if(!FIFO_QUEUE.isEnabled()) addBlockedFiles("ArrayFIFOQueue");
if(dequeue) addBlockedFiles("PriorityDequeue"); if(!HEAP_QUEUE.isEnabled()) addBlockedFiles("HeapPriorityQueue");
if(dequeue || implementations || !isModuleEnabled("FiFoQueue")) addBlockedFiles("ArrayFIFOQueue"); if(!ARRAY_PRIO_QUEUE.isEnabled()) addBlockedFiles("ArrayPriorityQueue");
if(implementations || !isModuleEnabled("HeapQueue")) addBlockedFiles("HeapPriorityQueue");
if(implementations || !isModuleEnabled("ArrayPrioQueue")) addBlockedFiles("ArrayPriorityQueue");
if(keyType == ClassType.BOOLEAN) { if(keyType == ClassType.BOOLEAN) {
addBlockedFiles("QueueTests"); addBlockedFiles("QueueTests");
@@ -1,15 +1,30 @@
package speiger.src.builder.modules; package speiger.src.builder.modules;
import java.util.Arrays; import java.util.Arrays;
import java.util.Set; import java.util.List;
import java.util.TreeSet;
import speiger.src.builder.ClassType; import speiger.src.builder.ClassType;
import speiger.src.builder.dependencies.FunctionDependency;
import speiger.src.builder.dependencies.IDependency;
import speiger.src.builder.dependencies.ModuleDependency;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class SetModule extends BaseModule public class SetModule extends BaseModule
{ {
public static final BaseModule INSTANCE = new SetModule(); public static final BaseModule INSTANCE = new SetModule();
public static final ModuleDependency MODULE = new ModuleDependency(INSTANCE, false).addKeyDependency(CollectionModule.MODULE).addKeyDependency(CollectionModule.SPLIT_ITERATORS);
public static final FunctionDependency IMPLEMENTATION = MODULE.createDependency("Implementations");
public static final FunctionDependency WRAPPERS = MODULE.createDependency("Wrappers");
public static final FunctionDependency ORDERED_SET = MODULE.createDependency("OrderedSet");
public static final FunctionDependency SORTED_SET = MODULE.createDependency("SortedSet");
public static final FunctionDependency ARRAY_SET = MODULE.createDependency("ArraySet").addKeyDependency(ORDERED_SET).addKeyDependency(IMPLEMENTATION);
public static final FunctionDependency IMMUTABLE_SET = MODULE.createDependency("ImmutableSet").addKeyDependency(ORDERED_SET).addKeyDependency(IMPLEMENTATION);
public static final FunctionDependency HASH_SET = MODULE.createDependency("HashSet").addKeyDependency(IMPLEMENTATION);
public static final FunctionDependency LINKED_SET = MODULE.createDependency("LinkedHashSet").addKeyDependency(ORDERED_SET).addKeyDependency(HASH_SET);
public static final FunctionDependency CUSTOM_SET = MODULE.createDependency("CustomHashSet").addKeyDependency(IMPLEMENTATION).addKeyDependency(CollectionModule.STRATEGY);
public static final FunctionDependency LINKED_CUSTOM_SET = MODULE.createDependency("LinkedCustomHashSet").addKeyDependency(ORDERED_SET).addKeyDependency(CUSTOM_SET);
public static final FunctionDependency AVL_TREE_SET = MODULE.createDependency("AVLTreeSet").addKeyDependency(SORTED_SET).addKeyDependency(IMPLEMENTATION);
public static final FunctionDependency RB_TREE_SET = MODULE.createDependency("RBTreeSet").addKeyDependency(SORTED_SET).addKeyDependency(IMPLEMENTATION);
@Override @Override
public String getModuleName() { return "Set"; } public String getModuleName() { return "Set"; }
@@ -19,68 +34,40 @@ public class SetModule extends BaseModule
@Override @Override
public boolean isModuleValid(ClassType keyType, ClassType valueType) { return keyType != ClassType.BOOLEAN; } public boolean isModuleValid(ClassType keyType, ClassType valueType) { return keyType != ClassType.BOOLEAN; }
@Override @Override
public boolean areDependenciesLoaded() { return isDependencyLoaded(CollectionModule.INSTANCE); } public List<IDependency> getDependencies(ClassType keyType, ClassType valueType) { return Arrays.asList(MODULE, WRAPPERS, ORDERED_SET, SORTED_SET, IMPLEMENTATION, ARRAY_SET, IMMUTABLE_SET, HASH_SET, LINKED_SET, CUSTOM_SET, LINKED_CUSTOM_SET, AVL_TREE_SET, RB_TREE_SET); }
@Override
public Set<String> getModuleKeys(ClassType keyType, ClassType valueType) {
Set<String> sets = new TreeSet<>();
sets.addAll(Arrays.asList("Wrappers", "Implementations"));
sets.addAll(Arrays.asList("OrderedSet", "SortedSet"));
sets.addAll(Arrays.asList("ArraySet", "ImmutableSet"));
sets.addAll(Arrays.asList("HashSet", "LinkedHashSet"));
sets.addAll(Arrays.asList("CustomHashSet", "LinkedCustomHashSet"));
sets.addAll(Arrays.asList("AVLTreeSet", "RBTreeSet"));
return sets;
}
@Override @Override
protected void loadFlags() protected void loadFlags()
{ {
if(isModuleEnabled()) addFlag("SET_MODULE"); if(MODULE.isEnabled()) addFlag("SET_MODULE");
if(isModuleEnabled("Wrappers")) addFlag("SETS_FEATURE"); if(WRAPPERS.isEnabled()) addFlag("SETS_FEATURE");
boolean implementations = isModuleEnabled("Implementations"); if(ORDERED_SET.isEnabled()) addFlag("ORDERED_SET_FEATURE");
boolean hashSet = implementations && isModuleEnabled("HashSet"); if(SORTED_SET.isEnabled()) addFlag("SORTED_SET_FEATURE");
boolean customHashSet = implementations && isModuleEnabled("CustomHashSet"); if(IMMUTABLE_SET.isEnabled()) addFlag("IMMUTABLE_SET_FEATURE");
if(ARRAY_SET.isEnabled()) addFlag("ARRAY_SET_FEATURE");
if(isModuleEnabled("OrderedSet")) { if(HASH_SET.isEnabled()) addFlag("HASH_SET_FEATURE");
addFlag("ORDERED_SET_FEATURE"); if(LINKED_SET.isEnabled()) addFlag("LINKED_SET_FEATURE");
if(implementations && isModuleEnabled("ArraySet")) addFlag("ARRAY_SET_FEATURE"); if(CUSTOM_SET.isEnabled()) addFlag("CUSTOM_HASH_SET_FEATURE");
if(hashSet && isModuleEnabled("LinkedHashSet")) addFlag("LINKED_SET_FEATURE"); if(LINKED_CUSTOM_SET.isEnabled()) addFlag("LINKED_CUSTOM_SET_FEATURE");
if(customHashSet && isModuleEnabled("LinkedCustomHashSet")) addFlag("LINKED_CUSTOM_SET_FEATURE"); if(AVL_TREE_SET.isEnabled()) addFlag("AVL_TREE_SET_FEATURE");
} if(RB_TREE_SET.isEnabled()) addFlag("RB_TREE_SET_FEATURE");
if(isModuleEnabled("SortedSet")) {
addFlag("SORTED_SET_FEATURE");
if(implementations && isModuleEnabled("AVLTreeSet")) addFlag("AVL_TREE_SET_FEATURE");
if(implementations && isModuleEnabled("RBTreeSet")) addFlag("RB_TREE_SET_FEATURE");
}
if(implementations && isModuleEnabled("ImmutableSet")) addFlag("IMMUTABLE_SET_FEATURE");
if(hashSet) addFlag("HASH_SET_FEATURE");
if(customHashSet) addFlag("CUSTOM_HASH_SET_FEATURE");
} }
@Override @Override
protected void loadBlockades() protected void loadBlockades()
{ {
if(!isModuleEnabled()) addBlockedFiles("Set", "AbstractSet"); if(!MODULE.isEnabled()) addBlockedFiles("Set", "AbstractSet");
if(!isModuleEnabled("Wrappers")) addBlockedFiles("Sets"); if(!WRAPPERS.isEnabled()) addBlockedFiles("Sets");
boolean implementations = !isModuleEnabled("Implementations"); if(!IMMUTABLE_SET.isEnabled()) addBlockedFiles("ImmutableOpenHashSet");
if(implementations || !isModuleEnabled("ImmutableSet")) addBlockedFiles("ImmutableOpenHashSet"); if(!ORDERED_SET.isEnabled()) addBlockedFiles("OrderedSet");
if(!HASH_SET.isEnabled()) addBlockedFiles("OpenHashSet");
boolean ordered = !isModuleEnabled("OrderedSet"); if(!LINKED_SET.isEnabled()) addBlockedFiles("LinkedOpenHashSet");
if(ordered) addBlockedFiles("OrderedSet"); if(!CUSTOM_SET.isEnabled()) addBlockedFiles("OpenCustomHashSet");
boolean hashSet = implementations || !isModuleEnabled("HashSet"); if(!LINKED_CUSTOM_SET.isEnabled()) addBlockedFiles("LinkedOpenCustomHashSet");
if(hashSet) addBlockedFiles("OpenHashSet"); if(!ARRAY_SET.isEnabled()) addBlockedFiles("ArraySet");
if(hashSet || ordered || !isModuleEnabled("LinkedHashSet")) addBlockedFiles("LinkedOpenHashSet"); if(!SORTED_SET.isEnabled()) addBlockedFiles("SortedSet", "NavigableSet");
if(!AVL_TREE_SET.isEnabled()) addBlockedFiles("AVLTreeSet");
boolean customHashSet = implementations || !isModuleEnabled("CustomHashSet"); if(!RB_TREE_SET.isEnabled()) addBlockedFiles("RBTreeSet");
if(customHashSet) addBlockedFiles("OpenCustomHashSet");
if(customHashSet || ordered || !isModuleEnabled("LinkedCustomHashSet")) addBlockedFiles("LinkedOpenCustomHashSet");
if(implementations || ordered || !isModuleEnabled("ArraySet")) addBlockedFiles("ArraySet");
boolean sorted = !isModuleEnabled("SortedSet");
if(sorted) addBlockedFiles("SortedSet", "NavigableSet");
if(implementations || sorted || !isModuleEnabled("AVLTreeSet")) addBlockedFiles("AVLTreeSet");
if(implementations || sorted || !isModuleEnabled("RBTreeSet")) addBlockedFiles("RBTreeSet");
if(keyType == ClassType.BOOLEAN) if(keyType == ClassType.BOOLEAN)
{ {
@@ -120,7 +107,7 @@ public class SetModule extends BaseModule
addFunctionMapper("POLL_FIRST_KEY", "pollFirst"); addFunctionMapper("POLL_FIRST_KEY", "pollFirst");
addFunctionMapper("POLL_LAST_KEY", "pollLast"); addFunctionMapper("POLL_LAST_KEY", "pollLast");
addFunctionMapper("FIRST_KEY", "first"); addFunctionMapper("FIRST_KEY", "first");
addFunctionMapper("LAST_KEY", "last"); addFunctionMapper("LAST_KEY", "last");
} }
@Override @Override
@@ -161,6 +148,7 @@ public class SetModule extends BaseModule
//Abstract Classes //Abstract Classes
addAbstractMapper("ABSTRACT_SET", "Abstract%sSet"); addAbstractMapper("ABSTRACT_SET", "Abstract%sSet");
addAbstractMapper("REVERSED_ORDERED_SET", "Reversed%sOrderedSet");
//Helper Classes //Helper Classes
addClassMapper("SETS", "Sets"); addClassMapper("SETS", "Sets");
@@ -1,266 +1,346 @@
package speiger.src.collections.PACKAGE.collections; package speiger.src.collections.PACKAGE.collections;
import java.util.Collection; import java.util.Collection;
import java.util.Objects; #if ORDERED_MAP_FEATURE
import java.util.AbstractCollection; import java.util.function.Supplier;
#if TYPE_OBJECT #endif
import java.util.function.Consumer; import java.util.Objects;
#endif import java.util.AbstractCollection;
#if TYPE_OBJECT
#if !TYPE_OBJECT import java.util.function.Consumer;
import speiger.src.collections.PACKAGE.functions.CONSUMER; #endif
import speiger.src.collections.PACKAGE.utils.ITERATORS;
#endif #if ORDERED_MAP_FEATURE
import speiger.src.collections.PACKAGE.utils.ARRAYS; import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
#endif
/** #if !TYPE_OBJECT
* Abstract Type Specific Collection that reduces boxing/unboxing import speiger.src.collections.PACKAGE.functions.CONSUMER;
* @Type(T) import speiger.src.collections.PACKAGE.utils.ITERATORS;
*/ import speiger.src.collections.PACKAGE.utils.ARRAYS;
public abstract class ABSTRACT_COLLECTION KEY_GENERIC_TYPE extends AbstractCollection<CLASS_TYPE> implements COLLECTION KEY_GENERIC_TYPE #endif
{
@Override /**
public abstract ITERATOR KEY_GENERIC_TYPE iterator(); * Abstract Type Specific Collection that reduces boxing/unboxing
* @Type(T)
#if !TYPE_OBJECT */
/** {@inheritDoc} public abstract class ABSTRACT_COLLECTION KEY_GENERIC_TYPE extends AbstractCollection<CLASS_TYPE> implements COLLECTION KEY_GENERIC_TYPE
* <p>This default implementation delegates to the corresponding type-specific function. {
* @deprecated Please use the corresponding type-specific function instead. @Override
*/ public abstract ITERATOR KEY_GENERIC_TYPE iterator();
@Override
@Deprecated #if !TYPE_OBJECT
public boolean add(CLASS_TYPE e) { return COLLECTION.super.add(e); } /** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
#endif * @deprecated Please use the corresponding type-specific function instead.
@Override */
public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) { @Override
boolean modified = false; @Deprecated
for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();modified |= add(iter.NEXT())); public boolean add(CLASS_TYPE e) { return COLLECTION.super.add(e); }
return modified;
} #endif
@Override
@Override public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) {
public COLLECTION KEY_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); } boolean modified = false;
for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();modified |= add(iter.NEXT()));
#if !TYPE_OBJECT return modified;
/** {@inheritDoc} }
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead. @Override
*/ public COLLECTION KEY_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); }
@Override
@Deprecated #if !TYPE_OBJECT
public boolean contains(Object e) { return COLLECTION.super.contains(e); } /** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
/** * @deprecated Please use the corresponding type-specific function instead.
* 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. @Override
* @return true if the value was found. @Deprecated
*/ public boolean contains(Object e) { return COLLECTION.super.contains(e); }
@Override
public boolean contains(KEY_TYPE e) { /**
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { if(KEY_EQUALS(iter.NEXT(), e)) return true; } * A Type-Specific implementation of contains. This implementation iterates over the elements and returns true if the value match.
return false; * @param e the element that should be searched for.
} * @return true if the value was found.
*/
/** {@inheritDoc} @Override
* <p>This default implementation delegates to the corresponding type-specific function. public boolean contains(KEY_TYPE e) {
* @deprecated Please use the corresponding type-specific function instead. for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { if(KEY_EQUALS(iter.NEXT(), e)) return true; }
*/ return false;
@Override }
@Deprecated
public boolean addAll(Collection<? extends CLASS_TYPE> c) /** {@inheritDoc}
{ * <p>This default implementation delegates to the corresponding type-specific function.
return c instanceof COLLECTION ? addAll((COLLECTION KEY_GENERIC_TYPE)c) : super.addAll(c); * @deprecated Please use the corresponding type-specific function instead.
} */
#endif @Override
@Deprecated
/** public boolean addAll(Collection<? extends CLASS_TYPE> c)
* 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 c instanceof COLLECTION ? addAll((COLLECTION KEY_GENERIC_TYPE)c) : super.addAll(c);
* @return true if all elements were found in the collection }
* @throws java.lang.NullPointerException if the collection is null #endif
*/
@Override /**
public boolean containsAll(COLLECTION KEY_GENERIC_TYPE c) { * A Type-Specific implementation of containsAll. This implementation iterates over all elements and checks all elements are present in the other collection.
Objects.requireNonNull(c); * @param c the collection that should be checked if it contains all elements.
if(c.isEmpty()) return true; * @return true if all elements were found in the collection
for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();) * @throws java.lang.NullPointerException if the collection is null
if(!contains(iter.NEXT())) */
return false; @Override
return true; public boolean containsAll(COLLECTION KEY_GENERIC_TYPE c) {
} Objects.requireNonNull(c);
if(c.isEmpty()) return true;
@Override for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();)
public boolean containsAll(Collection<?> c) { if(!contains(iter.NEXT()))
Objects.requireNonNull(c); return false;
return c instanceof COLLECTION ? containsAll((COLLECTION KEY_GENERIC_TYPE)c) : super.containsAll(c); return true;
} }
/** @Override
* This implementation iterates over the elements of the collection and checks if they are stored in this collection public boolean containsAll(Collection<?> c) {
* @param c the elements that should be checked for Objects.requireNonNull(c);
* @return true if any element is in this collection return c instanceof COLLECTION ? containsAll((COLLECTION KEY_GENERIC_TYPE)c) : super.containsAll(c);
* @throws java.lang.NullPointerException if the collection is null }
*/
@Override /**
@Primitive * This implementation iterates over the elements of the collection and checks if they are stored in this collection
public boolean containsAny(Collection<?> c) { * @param c the elements that should be checked for
Objects.requireNonNull(c); * @return true if any element is in this collection
if(c.isEmpty()) return false; * @throws java.lang.NullPointerException if the collection is null
for(Object e : c) */
if(contains(e)) @Override
return true; @Primitive
return false; public boolean containsAny(Collection<?> c) {
} Objects.requireNonNull(c);
if(c.isEmpty()) return false;
/** for(Object e : c)
* This implementation iterates over the elements of the collection and checks if they are stored in this collection. if(contains(e))
* @param c the elements that should be checked for return true;
* @return true if any element is in this collection return false;
* @throws java.lang.NullPointerException if the collection is null }
*/
@Override /**
public boolean containsAny(COLLECTION KEY_GENERIC_TYPE c) { * This implementation iterates over the elements of the collection and checks if they are stored in this collection.
Objects.requireNonNull(c); * @param c the elements that should be checked for
if(c.isEmpty()) return false; * @return true if any element is in this collection
for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();) * @throws java.lang.NullPointerException if the collection is null
if(contains(iter.NEXT())) */
return true; @Override
return false; public boolean containsAny(COLLECTION KEY_GENERIC_TYPE c) {
} Objects.requireNonNull(c);
if(c.isEmpty()) return false;
#if !TYPE_OBJECT for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();)
/** {@inheritDoc} if(contains(iter.NEXT()))
* <p>This default implementation delegates to the corresponding type-specific function. return true;
* @deprecated Please use the corresponding type-specific function instead. return false;
*/ }
@Override
@Deprecated #if !TYPE_OBJECT
public boolean remove(Object e) { return COLLECTION.super.remove(e); } /** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
/** * @deprecated Please use the corresponding type-specific function instead.
* 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 @Override
* @param e the element that is searched for @Deprecated
* @return true if the element was found and removed. public boolean remove(Object e) { return COLLECTION.super.remove(e); }
*/
@Override /**
public boolean REMOVE_KEY(KEY_TYPE 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.
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { * It stops after finding the first element
if(KEY_EQUALS(iter.NEXT(), e)) { * @param e the element that is searched for
iter.remove(); * @return true if the element was found and removed.
return true; */
} @Override
} public boolean REMOVE_KEY(KEY_TYPE e) {
return false; for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
} if(KEY_EQUALS(iter.NEXT(), e)) {
iter.remove();
#endif return true;
/** }
* 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 false;
* @return true if the collection was modified. }
* @throws java.lang.NullPointerException if the collection is null
*/ #endif
@Override /**
public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) { * A Type-Specific implementation of removeAll. This Implementation iterates over all elements and removes them as they were found in the other collection.
Objects.requireNonNull(c); * @param c the elements that should be deleted
if(c.isEmpty()) return false; * @return true if the collection was modified.
boolean modified = false; * @throws java.lang.NullPointerException if the collection is null
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { */
if(c.contains(iter.NEXT())) { @Override
iter.remove(); public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) {
modified = true; Objects.requireNonNull(c);
} if(c.isEmpty()) return false;
} boolean modified = false;
return modified; for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
} if(c.contains(iter.NEXT())) {
iter.remove();
@Override modified = true;
public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { }
Objects.requireNonNull(c); }
if(c.isEmpty()) return false; return modified;
Objects.requireNonNull(r); }
boolean modified = false;
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { @Override
KEY_TYPE e = iter.NEXT(); public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) {
if(c.contains(e)) { Objects.requireNonNull(c);
r.accept(e); if(c.isEmpty()) return false;
iter.remove(); Objects.requireNonNull(r);
modified = true; boolean modified = false;
} for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
} KEY_TYPE e = iter.NEXT();
return modified; if(c.contains(e)) {
} r.accept(e);
iter.remove();
/** modified = true;
* 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. return modified;
* @throws java.lang.NullPointerException if the collection is null }
*/
@Override /**
public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) { * A Type-Specific implementation of retainAll. This Implementation iterates over all elements and removes them as they were not found in the other collection.
Objects.requireNonNull(c); * @param c the elements that should be kept
if(c.isEmpty()) { * @return true if the collection was modified.
boolean modified = !isEmpty(); * @throws java.lang.NullPointerException if the collection is null
clear(); */
return modified; @Override
} public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) {
boolean modified = false; Objects.requireNonNull(c);
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { if(c.isEmpty()) {
if(!c.contains(iter.NEXT())) { boolean modified = !isEmpty();
iter.remove(); clear();
modified = true; return modified;
} }
} boolean modified = false;
return modified; for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
} if(!c.contains(iter.NEXT())) {
iter.remove();
@Override modified = true;
public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { }
Objects.requireNonNull(c); }
Objects.requireNonNull(r); return modified;
if(c.isEmpty()) { }
boolean modified = !isEmpty();
forEach(r); @Override
clear(); public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) {
return modified; Objects.requireNonNull(c);
} Objects.requireNonNull(r);
boolean modified = false; if(c.isEmpty()) {
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { boolean modified = !isEmpty();
KEY_TYPE e = iter.NEXT(); forEach(r);
if(!c.contains(e)) { clear();
r.accept(e); return modified;
iter.remove(); }
modified = true; boolean modified = false;
} for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
} KEY_TYPE e = iter.NEXT();
return modified; if(!c.contains(e)) {
} r.accept(e);
iter.remove();
#if !TYPE_OBJECT modified = true;
/** }
* 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 return modified;
*/ }
@Override
public KEY_TYPE[] TO_ARRAY() { #if !TYPE_OBJECT
if(isEmpty()) return ARRAYS.EMPTY_ARRAY; /**
return TO_ARRAY(new KEY_TYPE[size()]); * 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
* A Type-Specific implementation of toArray. This implementation iterates over all elements and unwraps them into primitive type. public KEY_TYPE[] TO_ARRAY() {
* @param a array that the elements should be injected to. If null or to small a new array with the right size is created if(isEmpty()) return ARRAYS.EMPTY_ARRAY;
* @return an array containing all of the elements in this collection return TO_ARRAY(new KEY_TYPE[size()]);
*/ }
@Override
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) { /**
if(a == null || a.length < size()) a = new KEY_TYPE[size()]; * A Type-Specific implementation of toArray. This implementation iterates over all elements and unwraps them into primitive type.
ITERATORS.unwrap(a, iterator()); * @param a array that the elements should be injected to. If null or to small a new array with the right size is created
if (a.length > size()) a[size()] = EMPTY_KEY_VALUE; * @return an array containing all of the elements in this collection
return a; */
} @Override
#endif 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
#if ORDERED_MAP_FEATURE
public static class REVERSED_ORDERED_COLLECTION KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION KEY_GENERIC_TYPE implements ORDERED_COLLECTION KEY_GENERIC_TYPE {
ORDERED_COLLECTION KEY_GENERIC_TYPE collection;
Supplier<ITERATOR KEY_GENERIC_TYPE> reverseIterator;
public REVERSED_ORDERED_COLLECTION(ORDERED_COLLECTION KEY_GENERIC_TYPE collection, Supplier<ITERATOR KEY_GENERIC_TYPE> reverseIterator) {
this.collection = collection;
this.reverseIterator = reverseIterator;
}
@Override
public boolean add(KEY_TYPE o) { return collection.add(o); }
@Override
public ORDERED_COLLECTION KEY_GENERIC_TYPE reversed() { return collection; }
@Override
public void addFirst(KEY_TYPE e) { collection.addLast(e); }
@Override
public void addLast(KEY_TYPE e) { collection.addFirst(e); }
@Override
#if !TYPE_OBJECT
public boolean contains(KEY_TYPE e) { return collection.contains(e); }
#else
public boolean contains(Object e) { return collection.contains(e); }
#endif
@Override
#if !TYPE_OBJECT
public boolean REMOVE_KEY(KEY_TYPE e) { return collection.REMOVE_KEY(e); }
#else
public boolean remove(Object e) { return collection.remove(e); }
#endif
@Override
public void clear() { collection.clear(); }
@Override
public KEY_TYPE GET_FIRST_KEY() { return collection.GET_LAST_KEY(); }
@Override
public KEY_TYPE REMOVE_FIRST_KEY() { return collection.REMOVE_LAST_KEY(); }
@Override
public KEY_TYPE GET_LAST_KEY() { return collection.GET_FIRST_KEY(); }
@Override
public KEY_TYPE REMOVE_LAST_KEY() { return collection.REMOVE_FIRST_KEY(); }
@Override
public ITERATOR KEY_GENERIC_TYPE iterator() { return reverseIterator.get(); }
@Override
public int size() { return collection.size(); }
}
public static class ReverseBiIterator KEY_GENERIC_TYPE implements LIST_ITERATOR KEY_GENERIC_TYPE {
LIST_ITERATOR KEY_GENERIC_TYPE it;
public ReverseBiIterator(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); }
}
#endif
} }
@@ -1,19 +1,11 @@
package speiger.src.collections.PACKAGE.collections; package speiger.src.collections.PACKAGE.collections;
#if !TYPE_OBJECT
import speiger.src.collections.objects.collections.ObjectBidirectionalIterator;
/**
* A Type-Specific {@link ObjectBidirectionalIterator} to reduce (un)boxing
*/
public interface BI_ITERATOR KEY_GENERIC_TYPE extends ITERATOR KEY_GENERIC_TYPE, ObjectBidirectionalIterator<CLASS_TYPE>
#else
/** /**
* This is a basically a {@link java.util.ListIterator} without the index functions. * This is a basically a {@link java.util.ListIterator} without the index functions.
* Allowing to have a simple Bidirectional Iterator without having to keep track of the Iteration index. * Allowing to have a simple Bidirectional Iterator without having to keep track of the Iteration index.
* @Type(T) * @Type(T)
*/ */
public interface BI_ITERATOR KEY_GENERIC_TYPE extends ITERATOR KEY_GENERIC_TYPE public interface BI_ITERATOR KEY_GENERIC_TYPE extends ITERATOR KEY_GENERIC_TYPE
#endif
{ {
/** /**
* Returns true if the Iterator has a Previous element * Returns true if the Iterator has a Previous element
@@ -29,11 +21,11 @@ public interface BI_ITERATOR KEY_GENERIC_TYPE extends ITERATOR KEY_GENERIC_TYPE
public KEY_TYPE PREVIOUS(); public KEY_TYPE PREVIOUS();
#if !TYPE_OBJECT #if !TYPE_OBJECT
/** {@inheritDoc} /**
* <p>This default implementation delegates to the corresponding type-specific function. * <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead. * @deprecated Please use the corresponding type-specific function instead.
* @return the Previous element of the iterator.+
*/ */
@Override
@Deprecated @Deprecated
public default CLASS_TYPE previous() { public default CLASS_TYPE previous() {
return KEY_TO_OBJ(PREVIOUS()); return KEY_TO_OBJ(PREVIOUS());
@@ -1,322 +1,323 @@
package speiger.src.collections.PACKAGE.collections; package speiger.src.collections.PACKAGE.collections;
import java.util.Collection; import java.util.Collection;
#if PRIMITIVES #if PRIMITIVES
import java.util.Objects; import java.util.Objects;
import java.util.function.JAVA_PREDICATE; import java.util.function.JAVA_PREDICATE;
import java.util.function.Predicate; import java.util.function.Predicate;
#if SPLIT_ITERATOR_FEATURE && STREAM_FEATURE #if SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
import java.util.stream.JAVA_STREAM; import java.util.stream.JAVA_STREAM;
import java.util.stream.StreamSupport; import java.util.stream.StreamSupport;
#endif #endif
#endif #endif
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.IntFunction; import java.util.function.IntFunction;
#else #else
import speiger.src.collections.PACKAGE.functions.CONSUMER; import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif #endif
#if SPLIT_ITERATOR_FEATURE #if SPLIT_ITERATOR_FEATURE
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS; import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
#endif #endif
import speiger.src.collections.PACKAGE.utils.COLLECTIONS; import speiger.src.collections.PACKAGE.utils.COLLECTIONS;
import speiger.src.collections.utils.ISizeProvider; import speiger.src.collections.utils.ISizeProvider;
import speiger.src.collections.utils.SanityChecks; import speiger.src.collections.utils.SanityChecks;
/** /**
* A Type-Specific {@link Collection} that reduces (un)boxing * A Type-Specific {@link Collection} that reduces (un)boxing
* @Type(T) * @Type(T)
*/ */
public interface COLLECTION KEY_GENERIC_TYPE extends Collection<CLASS_TYPE>, ITERABLE KEY_GENERIC_TYPE, ISizeProvider public interface COLLECTION KEY_GENERIC_TYPE extends Collection<CLASS_TYPE>, ITERABLE KEY_GENERIC_TYPE, ISizeProvider
{ {
#if !TYPE_OBJECT #if !TYPE_OBJECT
/** /**
* A Type-Specific add function to reduce (un)boxing * A Type-Specific add function to reduce (un)boxing
* @param o the element that should be added * @param o the element that should be added
* @return true if the element was added to the collection * @return true if the element was added to the collection
*/ */
public boolean add(KEY_TYPE o); public boolean add(KEY_TYPE o);
#endif #endif
/** /**
* A Type-Specific addAll function to reduce (un)boxing * A Type-Specific addAll function to reduce (un)boxing
* @param c the collection of elements that should be added * @param c the collection of elements that should be added
* @return true if elements were added into the collection * @return true if elements were added into the collection
*/ */
public boolean addAll(COLLECTION KEY_GENERIC_TYPE c); public boolean addAll(COLLECTION KEY_GENERIC_TYPE c);
/** /**
* A Type-Specific Array based addAll method to reduce the amount of Wrapping * A Type-Specific Array based addAll method to reduce the amount of Wrapping
* @param e the elements that should be added * @param e the elements that should be added
* @return if the collection was modified * @return if the collection was modified
*/ */
public default boolean addAll(KEY_TYPE... e) { return addAll(e, 0, e.length); } 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 * A Type-Specific Array based addAll method to reduce the amount of Wrapping
* @param e the elements that should be added * @param e the elements that should be added
* @param length how many elements of the array should be added * @param length how many elements of the array should be added
* @return if the collection was modified * @return if the collection was modified
*/ */
public default boolean addAll(KEY_TYPE[] e, int length) { return addAll(e, 0, length); } 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 * A Type-Specific Array based addAll method to reduce the amount of Wrapping
* @param e the elements that should be added * @param e the elements that should be added
* @param offset where to start within the array * @param offset where to start within the array
* @param length how many elements of the array should be added * @param length how many elements of the array should be added
* @return if the collection was modified * @return if the collection was modified
*/ */
public default boolean addAll(KEY_TYPE[] e, int offset, int length) { public default boolean addAll(KEY_TYPE[] e, int offset, int length) {
if(length <= 0) return false; if(length <= 0) return false;
SanityChecks.checkArrayCapacity(e.length, offset, length); SanityChecks.checkArrayCapacity(e.length, offset, length);
boolean added = false; boolean added = false;
for(int i = 0;i<length;i++) { for(int i = 0;i<length;i++) {
if(add(e[offset+i])) added = true; if(add(e[offset+i])) added = true;
} }
return added; return added;
} }
#if !TYPE_OBJECT #if !TYPE_OBJECT
/** /**
* A Type-Specific contains function to reduce (un)boxing * A Type-Specific contains function to reduce (un)boxing
* @param o the element that is checked for * @param o the element that is checked for
* @return true if the element is found in the collection * @return true if the element is found in the collection
*/ */
public boolean contains(KEY_TYPE o); public boolean contains(KEY_TYPE o);
#endif #endif
/** /**
* A Type-Specific containsAll function to reduce (un)boxing * A Type-Specific containsAll function to reduce (un)boxing
* @param c the collection of elements that should be tested for * @param c the collection of elements that should be tested for
* @return true if all the element is found in the collection * @return true if all the element is found in the collection
*/ */
public boolean containsAll(COLLECTION KEY_GENERIC_TYPE c); public boolean containsAll(COLLECTION KEY_GENERIC_TYPE c);
/** /**
* A Type-Specific containsAny function to reduce (un)boxing * A Type-Specific containsAny function to reduce (un)boxing
* @param c the collection of elements that should be tested for * @param c the collection of elements that should be tested for
* @return true if any element was found * @return true if any element was found
*/ */
public boolean containsAny(COLLECTION KEY_GENERIC_TYPE c); public boolean containsAny(COLLECTION KEY_GENERIC_TYPE c);
/** /**
* Returns true if any element of the Collection is found in the provided collection. * Returns true if any element of the Collection is found in the provided collection.
* A Small Optimization function to find out of any element is present when comparing collections and not all of them. * A Small Optimization function to find out of any element is present when comparing collections and not all of them.
* @param c the collection of elements that should be tested for * @param c the collection of elements that should be tested for
* @return true if any element was found. * @return true if any element was found.
*/ */
@Primitive @Primitive
public boolean containsAny(Collection<?> c); public boolean containsAny(Collection<?> c);
#if !TYPE_OBJECT #if !TYPE_OBJECT
/** /**
* A Type-Specific remove function that reduces (un)boxing. * A Type-Specific remove function that reduces (un)boxing.
* @param o the element that should be removed * @param o the element that should be removed
* @return true if the element was removed * @return true if the element was removed
* @see Collection#remove(Object) * @see Collection#remove(Object)
*/ */
public boolean REMOVE_KEY(KEY_TYPE o); public boolean REMOVE_KEY(KEY_TYPE o);
#endif #endif
/** /**
* A Type-Specific removeAll function that reduces (un)boxing. * A Type-Specific removeAll function that reduces (un)boxing.
* @param c the collection of elements that should be removed * @param c the collection of elements that should be removed
* @return true if any element was removed * @return true if any element was removed
* @see Collection#removeAll(Collection) * @see Collection#removeAll(Collection)
*/ */
public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c); public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c);
/** /**
* A Type-Specific removeAll function that reduces (un)boxing. * A Type-Specific removeAll function that reduces (un)boxing.
* It also notifies the remover of which exact element is going to be removed. * 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 c the collection of elements that should be removed
* @param r elements that got removed * @param r elements that got removed
* @return true if any element was removed * @return true if any element was removed
* @see Collection#removeAll(Collection) * @see Collection#removeAll(Collection)
*/ */
public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r); public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r);
/** /**
* A Type-Specific retainAll function that reduces (un)boxing. * A Type-Specific retainAll function that reduces (un)boxing.
* @param c the collection of elements that should be kept * @param c the collection of elements that should be kept
* @return true if any element was removed * @return true if any element was removed
* @see Collection#retainAll(Collection) * @see Collection#retainAll(Collection)
*/ */
public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c); public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c);
/** /**
* A Type-Specific retainAll function that reduces (un)boxing. * A Type-Specific retainAll function that reduces (un)boxing.
* It also notifies the remover of which exact element is going to be removed. * 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 c the collection of elements that should be kept
* @param r elements that got removed * @param r elements that got removed
* @return true if any element was removed * @return true if any element was removed
* @see Collection#retainAll(Collection) * @see Collection#retainAll(Collection)
*/ */
public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r); 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 * 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 collection that the elements should be inserted to
* @param <E> the collection type * @param <E> the collection type
* @return the input with the desired elements * @return the input with the desired elements
*/ */
default <E extends COLLECTION KEY_GENERIC_TYPE> E pour(E collection) { default <E extends COLLECTION KEY_GENERIC_TYPE> E pour(E collection) {
collection.addAll(this); collection.addAll(this);
return collection; return collection;
} }
/** /**
* A Function that does a shallow clone of the Collection itself. * 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. * 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 * It can be compared to Cloneable but with less exception risk
* @return a Shallow Copy of the collection * @return a Shallow Copy of the collection
* @note Wrappers and view collections will not support this feature * @note Wrappers and view collections will not support this feature
*/ */
public COLLECTION KEY_GENERIC_TYPE copy(); public COLLECTION KEY_GENERIC_TYPE copy();
#if TYPE_OBJECT #if TYPE_OBJECT
/** /**
* A Helper function that simplifies the process of creating a new Array. * A Helper function that simplifies the process of creating a new Array.
* @param action the array creation function * @param action the array creation function
* @return an array containing all of the elements in this collection * @param <E> the returning arrayType
* @see Collection#toArray(Object[]) * @return an array containing all of the elements in this collection
*/ * @see Collection#toArray(Object[])
default <E> E[] TO_ARRAY(IntFunction<E[]> action) { */
return TO_ARRAY(action.apply(size())); default <E> E[] TO_ARRAY(IntFunction<E[]> action) {
} return TO_ARRAY(action.apply(size()));
}
#else
/** #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 * A Type-Specific toArray function that delegates to {@link #TO_ARRAY(KEY_TYPE[])} with a newly created array.
* @see Collection#toArray() * @return an array containing all of the elements in this collection
*/ * @see Collection#toArray()
public KEY_TYPE[] TO_ARRAY(); */
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 * A Type-Specific toArray function that reduces (un)boxing.
* @return an array containing all of the elements in this collection * @param a array that the elements should be injected to. If null or to small a new array with the right size is created
* @see Collection#toArray(Object[]) * @return an array containing all of the elements in this collection
*/ * @see Collection#toArray(Object[])
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a); */
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a);
#if PRIMITIVES
/** {@inheritDoc} #if PRIMITIVES
* <p>This default implementation delegates to the corresponding type-specific function. /** {@inheritDoc}
* @deprecated Please use the corresponding type-specific function instead. * <p>This default implementation delegates to the corresponding type-specific function.
*/ * @deprecated Please use the corresponding type-specific function instead.
@Override */
@Deprecated @Override
public default boolean removeIf(Predicate<? super CLASS_TYPE> filter) { @Deprecated
Objects.requireNonNull(filter); public default boolean removeIf(Predicate<? super CLASS_TYPE> filter) {
#if TYPE_BYTE || TYPE_SHORT || TYPE_CHAR || TYPE_FLOAT Objects.requireNonNull(filter);
return remIf(v -> filter.test(KEY_TO_OBJ(SanityChecks.SANITY_CAST(v)))); #if TYPE_BYTE || TYPE_SHORT || TYPE_CHAR || TYPE_FLOAT
#else return remIf(v -> filter.test(KEY_TO_OBJ(SanityChecks.SANITY_CAST(v))));
return remIf(v -> filter.test(KEY_TO_OBJ(v))); #else
#endif return remIf(v -> filter.test(KEY_TO_OBJ(v)));
} #endif
}
/**
* A Type-Specific removeIf function to reduce (un)boxing. /**
* <p>Removes elements that were selected by the filter * A Type-Specific removeIf function to reduce (un)boxing.
* @see Collection#removeIf(Predicate) * <p>Removes elements that were selected by the filter
* @param filter Filters the elements that should be removed * @see Collection#removeIf(Predicate)
* @return true if the collection was modified * @param filter Filters the elements that should be removed
* @throws java.lang.NullPointerException if filter is null * @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); public default boolean remIf(JAVA_PREDICATE filter) {
boolean removed = false; Objects.requireNonNull(filter);
final ITERATOR each = iterator(); boolean removed = false;
while (each.hasNext()) { final ITERATOR each = iterator();
if (filter.test(each.NEXT())) { while (each.hasNext()) {
each.remove(); if (filter.test(each.NEXT())) {
removed = true; each.remove();
} removed = true;
} }
return removed; }
} return removed;
}
#endif
/** {@inheritDoc} #endif
* <p>This default implementation delegates to the corresponding type-specific function. /** {@inheritDoc}
* @deprecated Please use the corresponding type-specific function instead. * <p>This default implementation delegates to the corresponding type-specific function.
*/ * @deprecated Please use the corresponding type-specific function instead.
@Override */
@Deprecated @Override
public default boolean add(CLASS_TYPE o) { return add(OBJ_TO_KEY(o)); } @Deprecated
public default boolean add(CLASS_TYPE o) { return add(OBJ_TO_KEY(o)); }
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function. /** {@inheritDoc}
* @deprecated Please use the corresponding type-specific function instead. * <p>This default implementation delegates to the corresponding type-specific function.
*/ * @deprecated Please use the corresponding type-specific function instead.
@Override */
@Deprecated @Override
public default boolean contains(Object o) { return o != null && contains(CLASS_TO_KEY(o)); } @Deprecated
public default boolean contains(Object o) { return o != null && contains(CLASS_TO_KEY(o)); }
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function. /** {@inheritDoc}
* @deprecated Please use the corresponding type-specific function instead. * <p>This default implementation delegates to the corresponding type-specific function.
*/ * @deprecated Please use the corresponding type-specific function instead.
@Override */
@Deprecated @Override
public default boolean remove(Object o) { return o != null && REMOVE_KEY(CLASS_TO_KEY(o)); } @Deprecated
public default boolean remove(Object o) { return o != null && REMOVE_KEY(CLASS_TO_KEY(o)); }
#endif
/** #endif
* Returns a Type-Specific Iterator to reduce (un)boxing /**
* @return a iterator of the collection * Returns a Type-Specific Iterator to reduce (un)boxing
* @see Collection#iterator() * @return a iterator of the collection
*/ * @see Collection#iterator()
@Override */
public ITERATOR KEY_GENERIC_TYPE iterator(); @Override
public ITERATOR KEY_GENERIC_TYPE iterator();
/**
* Creates a Wrapped Collection that is Synchronized /**
* @return a new Collection that is synchronized * Creates a Wrapped Collection that is Synchronized
* @see COLLECTIONS#synchronize * @return a new Collection that is synchronized
*/ * @see COLLECTIONS#synchronize
public default COLLECTION KEY_GENERIC_TYPE synchronize() { return COLLECTIONS.synchronize(this); } */
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 * Creates a Wrapped Collection that is Synchronized
* @return a new Collection Wrapper that is synchronized * @param mutex is the controller of the synchronization block
* @see COLLECTIONS#synchronize * @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); } */
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 * Creates a Wrapped Collection that is unmodifiable
* @see COLLECTIONS#unmodifiable * @return a new Collection Wrapper that is unmodifiable
*/ * @see COLLECTIONS#unmodifiable
public default COLLECTION KEY_GENERIC_TYPE unmodifiable() { return COLLECTIONS.unmodifiable(this); } */
public default COLLECTION KEY_GENERIC_TYPE unmodifiable() { return COLLECTIONS.unmodifiable(this); }
#if SPLIT_ITERATOR_FEATURE
#if PRIMITIVES #if SPLIT_ITERATOR_FEATURE
/** #if PRIMITIVES
* Returns a Java-Type-Specific Stream to reduce boxing/unboxing. /**
* @return a Stream of the closest java type * 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); } */
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 * 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); } */
default JAVA_STREAM parallelPrimitiveStream() { return StreamSupport.NEW_STREAM(SPLIT_ITERATORS.createJavaSplititerator(this, 0), true); }
#endif
#if STREAM_FEATURE #endif
/** #if STREAM_FEATURE
* A Type Specific Type Splititerator to reduce boxing/unboxing /**
* @return type specific splititerator * 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); } @Override
#endif default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createSplititerator(this, 0); }
#endif #endif
#endif
} }
@@ -1,457 +1,496 @@
package speiger.src.collections.PACKAGE.collections; package speiger.src.collections.PACKAGE.collections;
import java.util.Objects; import java.util.Objects;
import java.util.function.Consumer; import java.util.function.Consumer;
#if JDK_FUNCTION #if JDK_FUNCTION
import java.util.function.PREDICATE; import java.util.function.PREDICATE;
#endif #endif
#if JDK_TYPE
#if !TYPE_OBJECT import java.util.OPTIONAL;
#endif
import speiger.src.collections.PACKAGE.functions.CONSUMER;
import speiger.src.collections.PACKAGE.functions.COMPARATOR; #if !TYPE_OBJECT
import speiger.src.collections.objects.collections.ObjectIterable;
#else import speiger.src.collections.PACKAGE.functions.CONSUMER;
import java.util.function.BiFunction; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import java.util.function.IntFunction; import speiger.src.collections.objects.collections.ObjectIterable;
import java.util.Comparator; #else
import java.util.function.BiFunction;
#endif import java.util.function.IntFunction;
import speiger.src.collections.PACKAGE.functions.function.TO_OBJECT_FUNCTION; import java.util.Comparator;
import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER;
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; #if BOOLEAN_COLLECTION_MODULE
#if !JDK_FUNCTION import speiger.src.collections.booleans.collections.BooleanIterable;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE; #endif
#endif #iterate
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; #argument OUTPUT_ITERABLE ByteIterable ShortIterable IntIterable LongIterable FloatIterable DoubleIterable
#if ARRAY_LIST_FEATURE || LINKED_LIST_FEATURE #argument MAPPER ToByteFunction ToShortFunction ToIntFunction ToLongFunction ToFloatFunction ToDoubleFunction
import speiger.src.collections.PACKAGE.lists.LIST; #argument PACKAGE bytes shorts ints longs floats doubles
#if ARRAY_LIST_FEATURE #argument FILTER_TYPE BYTE_COLLECTION_MODULE SHORT_COLLECTION_MODULE INT_COLLECTION_MODULE LONG_COLLECTION_MODULE FLOAT_COLLECTION_MODULE DOUBLE_COLLECTION_MODULE
import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; #if FILTER_TYPE
#else import speiger.src.collections.objects.functions.function.MAPPER;
import speiger.src.collections.PACKAGE.lists.LINKED_LIST; import speiger.src.collections.PACKAGE.collections.OUTPUT_ITERABLE;
#endif #endif
#endif #enditerate
#if SET_MODULE && !TYPE_BOOLEAN #endif
#if LINKED_SET_FEATURE || LINKED_CUSTOM_SET_FEATURE || SET_FEATURE || CUSTOM_SET_FEATURE || RB_TREE_SET_FEATURE || AVL_TREE_SET_FEATURE || ARRAY_SET_FEATURE #if !JDK_TYPE
import speiger.src.collections.PACKAGE.sets.SET; import speiger.src.collections.PACKAGE.functions.OPTIONAL;
#if LINKED_SET_FEATURE #endif
import speiger.src.collections.PACKAGE.sets.LINKED_HASH_SET; import speiger.src.collections.PACKAGE.functions.function.TO_OBJECT_FUNCTION;
#else if LINKED_CUSTOM_SET_FEATURE import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER;
import speiger.src.collections.PACKAGE.sets.LINKED_CUSTOM_HASH_SET; import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
#else if SET_FEATURE #if !JDK_FUNCTION
import speiger.src.collections.PACKAGE.sets.HASH_SET; import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
#else if CUSTOM_SET_FEATURE #endif
import speiger.src.collections.PACKAGE.sets.CUSTOM_HASH_SET; import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
#else if RB_TREE_SET_FEATURE #if ARRAY_LIST_FEATURE || LINKED_LIST_FEATURE
import speiger.src.collections.PACKAGE.sets.RB_TREE_SET; import speiger.src.collections.PACKAGE.lists.LIST;
#else if AVL_TREE_SET_FEATURE #if ARRAY_LIST_FEATURE
import speiger.src.collections.PACKAGE.sets.AVL_TREE_SET; import speiger.src.collections.PACKAGE.lists.ARRAY_LIST;
#else if ARRAY_SET_FEATURE #else
import speiger.src.collections.PACKAGE.sets.ARRAY_SET; import speiger.src.collections.PACKAGE.lists.LINKED_LIST;
#endif #endif
#endif #endif
#endif #if SET_MODULE && !TYPE_BOOLEAN
import speiger.src.collections.PACKAGE.utils.ARRAYS; #if LINKED_SET_FEATURE || LINKED_CUSTOM_SET_FEATURE || SET_FEATURE || CUSTOM_SET_FEATURE || RB_TREE_SET_FEATURE || AVL_TREE_SET_FEATURE || ARRAY_SET_FEATURE
#if ASYNC_MODULE import speiger.src.collections.PACKAGE.sets.SET;
import speiger.src.collections.PACKAGE.utils.ASYNC_BUILDER; #if LINKED_SET_FEATURE
#endif import speiger.src.collections.PACKAGE.sets.LINKED_HASH_SET;
#if SPLIT_ITERATOR_FEATURE #else if LINKED_CUSTOM_SET_FEATURE
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS; import speiger.src.collections.PACKAGE.sets.LINKED_CUSTOM_HASH_SET;
#endif #else if SET_FEATURE
import speiger.src.collections.PACKAGE.utils.ITERABLES; import speiger.src.collections.PACKAGE.sets.HASH_SET;
import speiger.src.collections.PACKAGE.utils.ITERATORS; #else if CUSTOM_SET_FEATURE
#if !LINKED_HASH_SET_FEATURE && LINKED_CUSTOM_HASH_SET_FEATURE import speiger.src.collections.PACKAGE.sets.CUSTOM_HASH_SET;
import speiger.src.collections.PACKAGE.utils.STRATEGY; #else if RB_TREE_SET_FEATURE
#endif import speiger.src.collections.PACKAGE.sets.RB_TREE_SET;
import speiger.src.collections.utils.ISizeProvider; #else if AVL_TREE_SET_FEATURE
import speiger.src.collections.PACKAGE.sets.AVL_TREE_SET;
/** #else if ARRAY_SET_FEATURE
* A Type-Specific {@link Iterable} that reduces (un)boxing import speiger.src.collections.PACKAGE.sets.ARRAY_SET;
* @Type(T) #endif
*/ #endif
public interface ITERABLE KEY_GENERIC_TYPE extends Iterable<CLASS_TYPE> #endif
{ import speiger.src.collections.PACKAGE.utils.ARRAYS;
/** #if ASYNC_MODULE
* Returns an iterator over elements of type {@code T}. import speiger.src.collections.PACKAGE.utils.ASYNC_BUILDER;
* #endif
* @return an Iterator. #if SPLIT_ITERATOR_FEATURE
*/ import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
@Override #endif
ITERATOR KEY_GENERIC_TYPE iterator(); import speiger.src.collections.PACKAGE.utils.ITERABLES;
import speiger.src.collections.PACKAGE.utils.ITERATORS;
#if !TYPE_OBJECT #if !LINKED_HASH_SET_FEATURE && LINKED_CUSTOM_HASH_SET_FEATURE
/** import speiger.src.collections.PACKAGE.utils.STRATEGY;
* A Type Specific foreach function that reduces (un)boxing #endif
* import speiger.src.collections.utils.ISizeProvider;
* @implSpec
* <p>The default implementation behaves as if: /**
* <pre>{@code * A Type-Specific {@link Iterable} that reduces (un)boxing
* iterator().forEachRemaining(action); * @Type(T)
* }</pre> */
* public interface ITERABLE KEY_GENERIC_TYPE extends Iterable<CLASS_TYPE>
* @param action The action to be performed for each element {
* @throws NullPointerException if the specified action is null /**
* @see Iterable#forEach(Consumer) * Returns an iterator over elements of type {@code T}.
*/ *
default void forEach(CONSUMER action) { * @return an Iterator.
Objects.requireNonNull(action); */
iterator().forEachRemaining(action); @Override
} ITERATOR KEY_GENERIC_TYPE iterator();
/** {@inheritDoc} #if !TYPE_OBJECT
* <p>This default implementation delegates to the corresponding type-specific function. /**
* @deprecated Please use the corresponding type-specific function instead. * A Type Specific foreach function that reduces (un)boxing
*/ *
@Deprecated * @implSpec
@Override * <p>The default implementation behaves as if:
default void forEach(Consumer<? super CLASS_TYPE> action) { * <pre>{@code
Objects.requireNonNull(action); * iterator().forEachRemaining(action);
iterator().forEachRemaining(action); * }</pre>
} *
* @param action The action to be performed for each element
#endif * @throws NullPointerException if the specified action is null
/** * @see Iterable#forEach(Consumer)
* 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 default void forEach(CONSUMER action) {
* @throws java.lang.NullPointerException if the specified action is null Objects.requireNonNull(action);
*/ iterator().forEachRemaining(action);
public default void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) { }
Objects.requireNonNull(action);
int index = 0; /** {@inheritDoc}
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();action.accept(index++, iter.NEXT())); * <p>This default implementation delegates to the corresponding type-specific function.
} * @deprecated Please use the corresponding type-specific function instead.
*/
/** @Deprecated
* Helper function to reduce Lambda usage and allow for more method references, since these are faster/cleaner. @Override
* @param input the object that should be included default void forEach(Consumer<? super CLASS_TYPE> action) {
* @param action The action to be performed for each element Objects.requireNonNull(action);
* @param <E> the generic type of the Object iterator().forEachRemaining(action);
* @throws java.lang.NullPointerException if the specified action is null }
*/
default <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) { #endif
Objects.requireNonNull(action); /**
iterator().forEachRemaining(input, action); * 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
#if SPLIT_ITERATOR_FEATURE */
/** public default void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) {
* A Type Specific Type Splititerator to reduce boxing/unboxing Objects.requireNonNull(action);
* @return type specific splititerator int index = 0;
*/ for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();action.accept(index++, iter.NEXT()));
@Override }
default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createUnknownSplititerator(iterator(), 0); }
/**
#endif * Helper function to reduce Lambda usage and allow for more method references, since these are faster/cleaner.
#if ASYNC_MODULE * @param input the object that should be included
/** * @param action The action to be performed for each element
* Creates a Async Builder for moving work of the thread. * @param <E> the generic type of the Object
* 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. * @throws java.lang.NullPointerException if the specified action is null
* @see ASYNC_BUILDER */
* @return a AsyncBuilder default <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
*/ Objects.requireNonNull(action);
default ASYNC_BUILDER KEY_GENERIC_TYPE asAsync() { iterator().forEachRemaining(input, action);
return new ASYNC_BUILDERBRACES(this); }
}
#if SPLIT_ITERATOR_FEATURE
#endif /**
/** * A Type Specific Type Splititerator to reduce boxing/unboxing
* A Helper function to reduce the usage of Streams and allows to convert a Iterable to something else. * @return type specific splititerator
* @param mapper the mapping function */
* @param <E> The return type. @Override
* @return a new Iterable that returns the desired result default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createUnknownSplititerator(iterator(), 0); }
*/
default <E> ObjectIterable<E> map(TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<E> mapper) { #endif
return ITERABLES.map(this, mapper); #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.
* A Helper function to reduce the usage of Streams and allows to convert a Iterable to something else. * @see ASYNC_BUILDER
* @param mapper the flatMapping function * @return a AsyncBuilder
* @param <V> The return type supplier. */
* @param <E> The return type. default ASYNC_BUILDER KEY_GENERIC_TYPE asAsync() {
* @return a new Iterable that returns the desired result return new ASYNC_BUILDERBRACES(this);
* @note does not support TO_ARRAY optimizations. }
*/
default <E, V extends Iterable<E>> ObjectIterable<E> flatMap(TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<V> mapper) { #endif
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 mapping function
/** * @param <E> The return type.
* A Helper function to reduce the usage of Streams and allows to convert a Iterable to something else. * @return a new Iterable that returns the desired result
* @param mapper the flatMapping function */
* @param <E> The return type. default <E> ObjectIterable<E> map(TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<E> mapper) {
* @return a new Iterable that returns the desired result return ITERABLES.map(this, mapper);
* @note does not support TO_ARRAY optimizations. }
*/
default <E> ObjectIterable<E> arrayflatMap(TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<E[]> mapper) { #if TYPE_OBJECT
return ITERABLES.arrayFlatMap(this, mapper); #iterate
} #argument OUTPUT_ITERABLE BooleanIterable ByteIterable ShortIterable IntIterable LongIterable FloatIterable DoubleIterable
#argument MAPPER Predicate ToByteFunction ToShortFunction ToIntFunction ToLongFunction ToFloatFunction ToDoubleFunction
/** #argument DATA_TYPE Boolean Byte Short Int Long Float Double
* A Helper function to reduce the usage of Streams and allows to filter out unwanted elements #argument FILTER_TYPE BOOLEAN_COLLECTION_MODULE BYTE_COLLECTION_MODULE SHORT_COLLECTION_MODULE INT_COLLECTION_MODULE LONG_COLLECTION_MODULE FLOAT_COLLECTION_MODULE DOUBLE_COLLECTION_MODULE
* @param filter the elements that should be kept. #if FILTER_TYPE
* @return a Iterable that filtered out all unwanted elements /**
* @note does not support TO_ARRAY optimizations. * A Helper function to reduce the usage of Streams and allows to convert a Iterable to something else.
*/ * @param mapper the mapping function
default ITERABLE KEY_GENERIC_TYPE filter(PREDICATE KEY_GENERIC_TYPE filter) { * @return a new Iterable that returns the desired result
return ITERABLES.filter(this, filter); */
} default OUTPUT_ITERABLE mapToDATA_TYPE(MAPPER<T> mapper) {
return ITERABLES.mapToDATA_TYPE(this, mapper);
/** }
* 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 #endif
* @note does not support TO_ARRAY optimizations. #enditerate
*/ #endif
default ITERABLE KEY_GENERIC_TYPE distinct() { /**
return ITERABLES.distinct(this); * A Helper function to reduce the usage of Streams and allows to convert a Iterable to something else.
} * @param mapper the flatMapping function
* @param <V> The return type supplier.
/** * @param <E> The return type.
* A Helper function to reduce the usage of Streams and allows to repeat elements a desired amount of times * @return a new Iterable that returns the desired result
* @param repeats how many times the elements should be repeated * @note does not support TO_ARRAY optimizations.
* @return a Iterable that is repeating multiple times */
*/ default <E, V extends Iterable<E>> ObjectIterable<E> flatMap(TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<V> mapper) {
default ITERABLE KEY_GENERIC_TYPE repeat(int repeats) { return ITERABLES.flatMap(this, mapper);
return ITERABLES.repeat(this, repeats); }
}
/**
/** * A Helper function to reduce the usage of Streams and allows to convert a Iterable to something else.
* A Helper function to reduce the usage of Streams and allows to limit the amount of elements * @param mapper the flatMapping function
* @param limit the amount of elements it should be limited to * @param <E> The return type.
* @return a Iterable that is limited in length * @return a new Iterable that returns the desired result
*/ * @note does not support TO_ARRAY optimizations.
default ITERABLE KEY_GENERIC_TYPE limit(long limit) { */
return ITERABLES.limit(this, limit); default <E> ObjectIterable<E> arrayflatMap(TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<E[]> mapper) {
} return ITERABLES.arrayFlatMap(this, mapper);
}
/**
* A Helper function to reduce the usage of Streams and allows to sort the elements /**
* @param sorter that sorts the elements. * A Helper function to reduce the usage of Streams and allows to filter out unwanted elements
* @return a Iterable that is sorted * @param filter the elements that should be kept.
*/ * @return a Iterable that filtered out all unwanted elements
default ITERABLE KEY_GENERIC_TYPE sorted(COMPARATOR KEY_GENERIC_TYPE sorter) { * @note does not support TO_ARRAY optimizations.
return ITERABLES.sorted(this, sorter); */
} 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 preview elements before they are iterated through
* @param action the action that should be applied /**
* @return a Peeked Iterable * 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
default ITERABLE KEY_GENERIC_TYPE peek(CONSUMER KEY_GENERIC_TYPE action) { * @note does not support TO_ARRAY optimizations.
return ITERABLES.peek(this, action); */
} default ITERABLE KEY_GENERIC_TYPE distinct() {
return ITERABLES.distinct(this);
/** }
* 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 <E> the collection type * A Helper function to reduce the usage of Streams and allows to repeat elements a desired amount of times
* @return the input with the desired elements * @param repeats how many times the elements should be repeated
*/ * @return a Iterable that is repeating multiple times
default <E extends COLLECTION KEY_GENERIC_TYPE> E pour(E collection) { */
ITERATORS.pour(iterator(), collection); default ITERABLE KEY_GENERIC_TYPE repeat(int repeats) {
return collection; return ITERABLES.repeat(this, repeats);
} }
#if ARRAY_LIST_FEATURE || LINKED_LIST_FEATURE /**
/** * A Helper function to reduce the usage of Streams and allows to limit the amount of elements
* A Helper function that reduces the usage of streams and allows to collect all elements as a ArrayList * @param limit the amount of elements it should be limited to
* @return a new ArrayList of all elements * @return a Iterable that is limited in length
*/ */
default LIST KEY_GENERIC_TYPE pourAsList() { default ITERABLE KEY_GENERIC_TYPE limit(long limit) {
#if ARRAY_LIST_FEATURE return ITERABLES.limit(this, limit);
return pour(new ARRAY_LISTBRACES()); }
#else
return pour(new LINKED_LISTBRACES()); /**
#endif * 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
#endif */
#if !TYPE_BOOLEAN && SET_MODULE default ITERABLE KEY_GENERIC_TYPE sorted(COMPARATOR KEY_GENERIC_TYPE sorter) {
#if LINKED_SET_FEATURE || LINKED_CUSTOM_SET_FEATURE || SET_FEATURE || CUSTOM_SET_FEATURE || RB_TREE_SET_FEATURE || AVL_TREE_SET_FEATURE || ARRAY_SET_FEATURE return ITERABLES.sorted(this, sorter);
/** }
* 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 /**
*/ * A Helper function to reduce the usage of Streams and allows to preview elements before they are iterated through
default SET KEY_GENERIC_TYPE pourAsSet() { * @param action the action that should be applied
#if LINKED_SET_FEATURE * @return a Peeked Iterable
return pour(new LINKED_HASH_SETBRACES()); */
#else if LINKED_CUSTOM_SET_FEATURE default ITERABLE KEY_GENERIC_TYPE peek(CONSUMER KEY_GENERIC_TYPE action) {
return pour(new LINKED_CUSTOM_HASH_SETBRACES(STRATEGY.normalStrategy())); return ITERABLES.peek(this, action);
#else if SET_FEATURE }
return pour(new HASH_SETBRACES());
#else if CUSTOM_SET_FEATURE /**
return pour(new CUSTOM_HASH_SETBRACES(STRATEGY.normalStrategy())); * A Helper function to reduce the usage of Streams and allows to collect all elements
#else if RB_TREE_SET_FEATURE * @param collection that the elements should be inserted to
return pour(new RB_Tree_SETBRACES()); * @param <E> the collection type
#else if AVL_TREE_SET_FEATURE * @return the input with the desired elements
return pour(new AVL_Tree_SETBRACES()); */
#else if ARRAY_SET_FEATURE default <E extends COLLECTION KEY_GENERIC_TYPE> E pour(E collection) {
return pour(new ARRAY_SETBRACES()); ITERATORS.pour(iterator(), collection);
#endif return collection;
} }
#endif #if ARRAY_LIST_FEATURE || LINKED_LIST_FEATURE
#endif /**
#if TYPE_OBJECT * 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
* 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. default LIST KEY_GENERIC_TYPE pourAsList() {
* @return a new Array of all elements #if ARRAY_LIST_FEATURE
*/ return pour(new ARRAY_LISTBRACES());
default <E> E[] TO_ARRAY(IntFunction<E[]> action) { #else
ISizeProvider prov = ISizeProvider.of(this); return pour(new LINKED_LISTBRACES());
if(prov != null) { #endif
int size = prov.size(); }
if(size >= 0) {
E[] array = action.apply(size); #endif
ITERATORS.unwrap(array, iterator()); #if !TYPE_BOOLEAN && SET_MODULE
return array; #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 ARRAYS.pour(iterator(), action); * @return a new LinkedHashSet of all elements
} */
#else default SET KEY_GENERIC_TYPE pourAsSet() {
/** #if LINKED_SET_FEATURE
* A Helper function that reduces the usage of streams and allows to collect all elements as a Array return pour(new LINKED_HASH_SETBRACES());
* @return a new Array of all elements #else if LINKED_CUSTOM_SET_FEATURE
*/ return pour(new LINKED_CUSTOM_HASH_SETBRACES(STRATEGY.normalStrategy()));
default KEY_TYPE[] TO_ARRAY() { #else if SET_FEATURE
ISizeProvider prov = ISizeProvider.of(this); return pour(new HASH_SETBRACES());
if(prov != null) { #else if CUSTOM_SET_FEATURE
int size = prov.size(); return pour(new CUSTOM_HASH_SETBRACES(STRATEGY.normalStrategy()));
if(size >= 0) { #else if RB_TREE_SET_FEATURE
KEY_TYPE[] array = NEW_KEY_ARRAY(size); return pour(new RB_Tree_SETBRACES());
ITERATORS.unwrap(array, iterator()); #else if AVL_TREE_SET_FEATURE
return array; return pour(new AVL_Tree_SETBRACES());
} #else if ARRAY_SET_FEATURE
} return pour(new ARRAY_SETBRACES());
return ARRAYS.pour(iterator()); #endif
} }
#endif #endif
/** #endif
* Helper function to reduce stream usage that allows to filter for any matches. #if TYPE_OBJECT
* @param filter that should be applied /**
* @return true if any matches were found * 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.
default boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { * @param <E> the returning arrayType
Objects.requireNonNull(filter); * @return a new Array of all elements
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { */
if(filter.test(iter.NEXT())) return true; default <E> E[] TO_ARRAY(IntFunction<E[]> action) {
} ISizeProvider prov = ISizeProvider.of(this);
return false; if(prov != null) {
} int size = prov.size();
if(size >= 0) {
/** E[] array = action.apply(size);
* Helper function to reduce stream usage that allows to filter for no matches. ITERATORS.unwrap(array, iterator());
* @param filter that should be applied return array;
* @return true if no matches were found }
*/ }
default boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { return ARRAYS.pour(iterator(), action);
Objects.requireNonNull(filter); }
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { #else
if(filter.test(iter.NEXT())) return false; /**
} * A Helper function that reduces the usage of streams and allows to collect all elements as a Array
return true; * @return a new Array of all elements
} */
default KEY_TYPE[] TO_ARRAY() {
/** ISizeProvider prov = ISizeProvider.of(this);
* Helper function to reduce stream usage that allows to filter for all matches. if(prov != null) {
* @param filter that should be applied int size = prov.size();
* @return true if all matches. if(size >= 0) {
*/ KEY_TYPE[] array = NEW_KEY_ARRAY(size);
default boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { ITERATORS.unwrap(array, iterator());
Objects.requireNonNull(filter); return array;
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { }
if(!filter.test(iter.NEXT())) return false; }
} return ARRAYS.pour(iterator());
return true; }
}
#endif
/** /**
* Helper function to reduce stream usage that allows to filter for the first match. * Helper function to reduce stream usage that allows to filter for any matches.
* @param filter that should be applied * @param filter that should be applied
* @return the found value or the null equivalent variant. * @return true if any matches were found
*/ */
default KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { default boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter); Objects.requireNonNull(filter);
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
KEY_TYPE entry = iter.NEXT(); if(filter.test(iter.NEXT())) return true;
if(filter.test(entry)) return entry; }
} return false;
return EMPTY_VALUE; }
}
/**
#if !TYPE_OBJECT * Helper function to reduce stream usage that allows to filter for no matches.
/** * @param filter that should be applied
* Performs a <a href="package-summary.html#Reduction">reduction</a> on the * @return true if no matches were found
* elements of this Iterable */
* @param operator the operation that should be applied default boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
* @param identity the start value Objects.requireNonNull(filter);
* @return the reduction result, returns identity if nothing was found for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
*/ if(filter.test(iter.NEXT())) return false;
default KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { }
Objects.requireNonNull(operator); return true;
KEY_TYPE state = identity; }
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
state = operator.APPLY_VALUE(state, iter.NEXT()); /**
} * Helper function to reduce stream usage that allows to filter for all matches.
return state; * @param filter that should be applied
} * @return true if all matches.
*/
#else default boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
/** Objects.requireNonNull(filter);
* Performs a <a href="package-summary.html#Reduction">reduction</a> on the for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
* elements of this Iterable if(!filter.test(iter.NEXT())) return false;
* @param operator the operation that should be applied }
* @param identity the start value return true;
* @Type(E) }
* @return the reduction result, returns identity if nothing was found
*/ /**
default <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) { * Helper function to reduce stream usage that allows to filter for the first match.
Objects.requireNonNull(operator); * @param filter that should be applied
KEY_SPECIAL_TYPE state = identity; * @return the found value or the null equivalent variant.
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { */
state = operator.APPLY_VALUE(state, iter.NEXT()); default OPTIONAL KEY_GENERIC_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
} Objects.requireNonNull(filter);
return state; for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
} KEY_TYPE entry = iter.NEXT();
if(filter.test(entry)) return OPTIONAL.GET_OPTIONAL(entry);
#endif }
/** return OPTIONAL.empty();
* Performs a <a href="package-summary.html#Reduction">reduction</a> on the }
* elements of this Iterable
* @param operator the operation that should be applied #if !TYPE_OBJECT
* @return the reduction result, returns null value if nothing was found /**
*/ * Performs a <a href="package-summary.html#Reduction">reduction</a> on the
default KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { * elements of this Iterable
Objects.requireNonNull(operator); * @param operator the operation that should be applied
KEY_TYPE state = EMPTY_VALUE; * @param identity the start value
boolean empty = true; * @return the reduction result, returns identity if nothing was found
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { */
if(empty) { default KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
empty = false; Objects.requireNonNull(operator);
state = iter.NEXT(); KEY_TYPE state = identity;
continue; for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
} state = operator.APPLY_VALUE(state, iter.NEXT());
state = operator.APPLY_VALUE(state, iter.NEXT()); }
} return state;
return state; }
}
#else
/** /**
* Helper function to reduce stream usage that allows to count the valid elements. * Performs a <a href="package-summary.html#Reduction">reduction</a> on the
* @param filter that should be applied * elements of this Iterable
* @return the amount of Valid Elements * @param operator the operation that should be applied
*/ * @param identity the start value
default int count(PREDICATE KEY_GENERIC_TYPE filter) { * @Type(E)
Objects.requireNonNull(filter); * @return the reduction result, returns identity if nothing was found
int result = 0; */
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { default <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
if(filter.test(iter.NEXT())) result++; Objects.requireNonNull(operator);
} KEY_SPECIAL_TYPE state = identity;
return result; for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
} state = operator.APPLY_VALUE(state, iter.NEXT());
}
return state;
}
#endif
/**
* Performs a <a href="package-summary.html#Reduction">reduction</a> 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 OPTIONAL KEY_GENERIC_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 empty ? OPTIONAL.empty() : OPTIONAL.GET_OPTIONAL(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;
}
} }
@@ -0,0 +1,83 @@
package speiger.src.collections.PACKAGE.collections;
#if JAVA_VERSION>=21
import java.util.SequencedCollection;
public interface ORDERED_COLLECTION KEY_GENERIC_TYPE extends COLLECTION KEY_GENERIC_TYPE, SequencedCollection<CLASS_TYPE> {
#else
public interface ORDERED_COLLECTION KEY_GENERIC_TYPE extends COLLECTION KEY_GENERIC_TYPE {
#endif
@Java21
ORDERED_COLLECTION KEY_GENERIC_TYPE reversed();
/**
* A method to add an element to the start of a collection
* @param e that should be added at the start.
*/
public void addFirst(KEY_TYPE e);
/**
* A method to add an element to the end of a collection
* @param e that should be added at the end.
*/
public void addLast(KEY_TYPE e);
/**
* A method to get the first element in the collection
* @return first element in the collection
*/
public KEY_TYPE GET_FIRST_KEY();
/**
* A method to get and remove the first element in the collection
* @return first element in the collection
*/
public KEY_TYPE REMOVE_FIRST_KEY();
/**
* A method to get the last element in the collection
* @return last element in the collection
*/
public KEY_TYPE GET_LAST_KEY();
/**
* A method to get and remove the last element in the collection
* @return last element in the collection
*/
public KEY_TYPE REMOVE_LAST_KEY();
#if JAVA_VERSION>=21 && !TYPE_OBJECT
@Override
@Deprecated
default void addFirst(CLASS_TYPE e) {
addFirst(OBJ_TO_KEY(e));
}
@Override
@Deprecated
default void addLast(CLASS_TYPE e) {
addLast(OBJ_TO_KEY(e));
}
@Override
@Deprecated
default CLASS_TYPE getFirst() {
return KEY_TO_OBJ(GET_FIRST_KEY());
}
@Override
@Deprecated
default CLASS_TYPE getLast() {
return KEY_TO_OBJ(GET_LAST_KEY());
}
@Override
@Deprecated
default CLASS_TYPE removeFirst() {
return KEY_TO_OBJ(REMOVE_FIRST_KEY());
}
@Override
@Deprecated
default CLASS_TYPE removeLast() {
return KEY_TO_OBJ(REMOVE_LAST_KEY());
}
#endif
}
@@ -1,5 +1,7 @@
package speiger.src.collections.PACKAGE.collections; package speiger.src.collections.PACKAGE.collections;
import java.util.NoSuchElementException;
import speiger.src.collections.utils.Stack; import speiger.src.collections.utils.Stack;
/** /**
@@ -14,6 +16,14 @@ public interface STACK
*/ */
public void push(KEY_TYPE e); public void push(KEY_TYPE e);
/**
* Helper function that pushes the top element on top of the stack again.
* @throws NoSuchElementException if the stack is empty
*/
public default void pushTop() {
push(top());
}
/** /**
* Removes the Object on top of the stack. * Removes the Object on top of the stack.
* @return the element that is on top of the stack * @return the element that is on top of the stack
@@ -59,4 +69,19 @@ public interface STACK
public default boolean isEmpty() { public default boolean isEmpty() {
return size() == 0; return size() == 0;
} }
/**
* A method to drop the contents of the Stack without clearing the stack
* @Type(E)
* @return the contents of the stack into a seperate array.
*/
public default GENERIC_SPECIAL_KEY_BRACES<E> KEY_SPECIAL_TYPE[] TO_ARRAY() { return TO_ARRAY(NEW_SPECIAL_KEY_ARRAY(size())); }
/**
* A method to drop the contents of the Stack without clearing the stack
* @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 stack 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<E> KEY_SPECIAL_TYPE[] TO_ARRAY(KEY_SPECIAL_TYPE[] input);
} }
@@ -1,70 +1,70 @@
package speiger.src.collections.PACKAGE.functions; package speiger.src.collections.PACKAGE.functions;
import java.util.Comparator; import java.util.Comparator;
import java.util.Objects; import java.util.Objects;
/** /**
* Type-Specific Class for Comparator to reduce (un)boxing * Type-Specific Class for Comparator to reduce (un)boxing
*/ */
public interface COMPARATOR extends Comparator<CLASS_TYPE> public interface COMPARATOR extends Comparator<CLASS_TYPE>
{ {
/** /**
* Type-Specific compare function to reduce (un)boxing * Type-Specific compare function to reduce (un)boxing
* @param o1 the first object to be compared. * @param o1 the first object to be compared.
* @param o2 the second 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. * @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) * @see Comparator#compare(Object, Object)
*/ */
int compare(KEY_TYPE o1, KEY_TYPE o2); int compare(KEY_TYPE o1, KEY_TYPE o2);
/** {@inheritDoc} /** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function. * <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead. * @deprecated Please use the corresponding type-specific function instead.
*/ */
@Override @Override
@Deprecated @Deprecated
default int compare(CLASS_TYPE o1, CLASS_TYPE o2) { default int compare(CLASS_TYPE o1, CLASS_TYPE o2) {
return compare(OBJ_TO_KEY(o1), OBJ_TO_KEY(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 * A Wrapper function to convert a Non-Type-Specific Comparator to a Type-Specific-Comparator
* @param c comparator to convert * @param c comparator to convert
* @return the wrapper of the comparator * @return the wrapper of the comparator
* @throws NullPointerException if the comparator is null * @throws NullPointerException if the comparator is null
*/ */
public static COMPARATOR of(Comparator<CLASS_TYPE> c) { public static COMPARATOR of(Comparator<CLASS_TYPE> c) {
Objects.requireNonNull(c); Objects.requireNonNull(c);
return (K, V) -> c.compare(KEY_TO_OBJ(K), KEY_TO_OBJ(V)); return (K, V) -> c.compare(KEY_TO_OBJ(K), KEY_TO_OBJ(V));
} }
@Override @Override
public default COMPARATOR reversed() { public default COMPARATOR reversed() {
return new Reversed(this); return new Reversed(this);
} }
/** /**
* A Type Specific Reversed Comparator to reduce boxing/unboxing * A Type Specific Reversed Comparator to reduce boxing/unboxing
*/ */
static class Reversed implements COMPARATOR static class Reversed implements COMPARATOR
{ {
COMPARATOR original; COMPARATOR original;
/** /**
* default constructor * default constructor
* @param original that is going to be reversed * @param original that is going to be reversed
*/ */
public Reversed(COMPARATOR original) { public Reversed(COMPARATOR original) {
this.original = original; this.original = original;
} }
public int compare(KEY_TYPE o1, KEY_TYPE o2) { public int compare(KEY_TYPE o1, KEY_TYPE o2) {
return original.compare(o2, o1); return original.compare(o2, o1);
} }
@Override @Override
public COMPARATOR reversed() { public COMPARATOR reversed() {
return original; return original;
} }
} }
} }
@@ -0,0 +1,89 @@
package speiger.src.collections.PACKAGE.functions;
import java.util.NoSuchElementException;
import java.util.function.Supplier;
public final class OPTIONAL KEY_GENERIC_TYPE {
private static final OPTIONAL NO_GENERIC_TYPE EMPTY = new OPTIONALBRACES();
private final boolean isPresent;
private final KEY_TYPE value;
private OPTIONAL() {
this.isPresent = false;
this.value = EMPTY_VALUE;
}
private OPTIONAL(KEY_TYPE value) {
this.isPresent = true;
this.value = value;
}
public static OPTIONAL KEY_GENERIC_TYPE empty() {
return EMPTY;
}
public static OPTIONAL KEY_GENERIC_TYPE of(KEY_TYPE value) {
return new OPTIONALBRACES(value);
}
public KEY_TYPE SUPPLY_GET() {
if(!isPresent) throw new NoSuchElementException("No value present");
return value;
}
public boolean isPresent() {
return isPresent;
}
public boolean isEmpty() {
return !isPresent;
}
public void ifPresent(CONSUMER KEY_GENERIC_TYPE consumer) {
if(isPresent) consumer.accept(value);
}
public void ifPresentOrElse(CONSUMER KEY_GENERIC_TYPE action, Runnable emptyAction) {
if (isPresent) action.accept(value);
else emptyAction.run();
}
public KEY_TYPE orElse(KEY_TYPE other) {
return isPresent ? value : other;
}
public KEY_TYPE orElseGet(SUPPLIER KEY_GENERIC_TYPE other) {
return isPresent ? value : other.SUPPLY_GET();
}
public KEY_TYPE orElseThrow() {
if (!isPresent) throw new NoSuchElementException("No value present");
return value;
}
public <X extends Throwable> KEY_TYPE orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
if(isPresent) return value;
else throw exceptionSupplier.get();
}
@Override
public boolean equals(Object obj) {
if(obj == this) return true;
if(obj instanceof OPTIONAL) {
OPTIONAL KEY_GENERIC_TYPE other = (OPTIONAL KEY_GENERIC_TYPE)obj;
return (isPresent && other.isPresent ? KEY_EQUALS(value, other.value) : isPresent == other.isPresent);
}
return false;
}
@Override
public int hashCode() {
return isPresent ? KEY_TO_HASH(value) : 0;
}
@Override
public String toString() {
return isPresent ? "OPTIONAL["+value+"]" : "OPTIONAL.empty";
}
}
@@ -1,19 +1,19 @@
package speiger.src.collections.PACKAGE.functions; 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-Specific Supplier interface that reduces (un)boxing and allows to merge other consumer types into this interface
* @Type(T) * @Type(T)
*/ */
#if TYPE_OBJECT #if TYPE_OBJECT
public interface SUPPLIER KEY_GENERIC_TYPE extends java.util.function.Supplier<KEY_TYPE> public interface SUPPLIER KEY_GENERIC_TYPE extends java.util.function.Supplier<KEY_TYPE>
#else if JDK_TYPE && !TYPE_BOOLEAN #else if JDK_TYPE && !TYPE_BOOLEAN
public interface SUPPLIER KEY_GENERIC_TYPE extends JAVA_SUPPLIER public interface SUPPLIER KEY_GENERIC_TYPE extends JAVA_SUPPLIER
#else #else
public interface SUPPLIER KEY_GENERIC_TYPE public interface SUPPLIER KEY_GENERIC_TYPE
#endif #endif
{ {
/** /**
* @return the supplied value * @return the supplied value
*/ */
public KEY_TYPE SUPPLY_GET(); public KEY_TYPE SUPPLY_GET();
} }
@@ -1,92 +1,92 @@
package speiger.src.collections.PACKAGE.functions; package speiger.src.collections.PACKAGE.functions;
import java.util.concurrent.RunnableFuture; import java.util.concurrent.RunnableFuture;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import java.util.concurrent.CancellationException; import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
#endif #endif
/** /**
* *
* A Type Specific Task interface that allows you to keep track of the task that is currently running.<br> * A Type Specific Task interface that allows you to keep track of the task that is currently running.<br>
* It extends Runnable future and supports said functions but also provides quality of life functions like:<br> * It extends Runnable future and supports said functions but also provides quality of life functions like:<br>
* *
* - isSuccesfull: which allows to detect if the task was completed properly and not interrupted or crashed. * - 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. * - pause/resume: which allows to pause/resume the task at any moment, making it easier to create thread-safe actions.
* @Type(T) * @Type(T)
*/ */
public interface TASK KEY_GENERIC_TYPE extends RunnableFuture<CLASS_TYPE> { public interface TASK KEY_GENERIC_TYPE extends RunnableFuture<CLASS_TYPE> {
/** /**
* Helper function to detect if the task is currently paused. * Helper function to detect if the task is currently paused.
* @return true if paused * @return true if paused
*/ */
public boolean isPaused(); public boolean isPaused();
/** /**
* Pauses the task, which lets the thread finish without completing the task. * 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. * 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. * 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. * So make sure it had the time to pause.
*/ */
public void pause(); public void pause();
/** /**
* Pauses the task, which lets the thread finish without completing the task. * 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. * Tasks are written in the way where they can pause without any issues.
* This won't be instant, as this function is applied asynchronous. * This won't be instant, as this function is applied asynchronous.
* It will await the pausing of the task. * It will await the pausing of the task.
*/ */
public void awaitPausing(); public void awaitPausing();
/** /**
* Continues the task if it wasn't already completed. * Continues the task if it wasn't already completed.
* This is done by resubmitting the task to the executor provided. * This is done by resubmitting the task to the executor provided.
*/ */
public void resume(); 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. * 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 * @return true if it was properly completed
*/ */
public boolean isSuccessful(); public boolean isSuccessful();
#if !TYPE_OBJECT #if !TYPE_OBJECT
/** /**
* A Type Specific get method that allows to reduce (un)boxing of primtives. * A Type Specific get method that allows to reduce (un)boxing of primtives.
* *
* Waits if necessary for the computation to complete, and then * Waits if necessary for the computation to complete, and then
* retrieves its result. * retrieves its result.
* *
* @return the computed result as primitive * @return the computed result as primitive
* @throws CancellationException if the computation was cancelled * @throws CancellationException if the computation was cancelled
* @throws ExecutionException if the computation threw an exception * @throws ExecutionException if the computation threw an exception
* @throws InterruptedException if the current thread was interrupted * @throws InterruptedException if the current thread was interrupted
* while waiting * while waiting
*/ */
public KEY_TYPE GET_KEY() throws InterruptedException, ExecutionException; public KEY_TYPE GET_KEY() throws InterruptedException, ExecutionException;
/** /**
* Waits if necessary for at most the given time for the computation * Waits if necessary for at most the given time for the computation
* to complete, and then retrieves its result, if available. * to complete, and then retrieves its result, if available.
* *
* @param timeout the maximum time to wait * @param timeout the maximum time to wait
* @param unit the time unit of the timeout argument * @param unit the time unit of the timeout argument
* @return the computed result as primitive * @return the computed result as primitive
* @throws CancellationException if the computation was cancelled * @throws CancellationException if the computation was cancelled
* @throws ExecutionException if the computation threw an exception * @throws ExecutionException if the computation threw an exception
* @throws InterruptedException if the current thread was interrupted while waiting * @throws InterruptedException if the current thread was interrupted while waiting
* @throws TimeoutException if the wait timed out * @throws TimeoutException if the wait timed out
*/ */
public KEY_TYPE GET_KEY(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; public KEY_TYPE GET_KEY(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
@Override @Override
@Deprecated @Deprecated
public default CLASS_TYPE get() throws InterruptedException, ExecutionException { return KEY_TO_OBJ(GET_KEY()); } public default CLASS_TYPE get() throws InterruptedException, ExecutionException { return KEY_TO_OBJ(GET_KEY()); }
@Override @Override
@Deprecated @Deprecated
public default CLASS_TYPE get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return KEY_TO_OBJ(GET_KEY(timeout, unit)); } public default CLASS_TYPE get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return KEY_TO_OBJ(GET_KEY(timeout, unit)); }
#endif #endif
} }
@@ -1,134 +1,134 @@
package speiger.src.collections.PACKAGE.functions.function; package speiger.src.collections.PACKAGE.functions.function;
#if VALUE_BOOLEAN || SAME_TYPE #if VALUE_BOOLEAN || SAME_TYPE
import java.util.Objects; import java.util.Objects;
#endif #endif
/** /**
* A Type Specific Function interface that reduces boxing/unboxing and fills the gaps of interfaces that are missing. * A Type Specific Function interface that reduces boxing/unboxing and fills the gaps of interfaces that are missing.
* @Type(T) * @Type(T)
* @ValueType(V) * @ValueType(V)
*/ */
@FunctionalInterface @FunctionalInterface
#if JDK_FUNCTION #if JDK_FUNCTION
public interface FUNCTION KEY_VALUE_GENERIC_TYPE extends JAVA_FUNCTION KEY_VALUE_GENERIC_TYPE public interface FUNCTION KEY_VALUE_GENERIC_TYPE extends JAVA_FUNCTION KEY_VALUE_GENERIC_TYPE
#else #else
public interface FUNCTION KEY_VALUE_GENERIC_TYPE public interface FUNCTION KEY_VALUE_GENERIC_TYPE
#endif #endif
{ {
/** /**
* Type Specific get function to reduce boxing/unboxing * Type Specific get function to reduce boxing/unboxing
* @param k the value that should be processed * @param k the value that should be processed
* @return the result of the function * @return the result of the function
*/ */
public VALUE_TYPE APPLY(KEY_TYPE k); public VALUE_TYPE APPLY(KEY_TYPE k);
#if SAME_TYPE #if SAME_TYPE
/** /**
* Creates a Default function that returns the input provided. * Creates a Default function that returns the input provided.
* @Type(T) * @Type(T)
* @return a input returning function * @return a input returning function
*/ */
public static GENERIC_KEY_BRACES FUNCTION KEY_SAME_GENERIC_TYPE identity() { public static GENERIC_KEY_BRACES FUNCTION KEY_SAME_GENERIC_TYPE identity() {
return T -> T; return T -> T;
} }
/** /**
* Returns a composed function that first applies the {@code before} * Returns a composed function that first applies the {@code before}
* function to its input, and then applies this function to the result. * function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to * If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function. * the caller of the composed function.
* *
* @Type(I) * @Type(I)
* @param before the function that should be used first * @param before the function that should be used first
* @return a composed function with a different starting function. * @return a composed function with a different starting function.
*/ */
public default GENERIC_SPECIAL_VALUE_BRACES<I> FUNCTION SV_GENERIC_TYPE<I> compose(FUNCTION SK_GENERIC_TYPE<I> before) { public default GENERIC_SPECIAL_VALUE_BRACES<I> FUNCTION SV_GENERIC_TYPE<I> compose(FUNCTION SK_GENERIC_TYPE<I> before) {
Objects.requireNonNull(before); Objects.requireNonNull(before);
return T -> APPLY(before.APPLY(T)); return T -> APPLY(before.APPLY(T));
} }
/** /**
* Returns a composed function that first applies this function to * Returns a composed function that first applies this function to
* its input, and then applies the {@code after} function to the result. * its input, and then applies the {@code after} function to the result.
* If evaluation of either function throws an exception, it is relayed to * If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function. * the caller of the composed function.
* *
* @Type(I) * @Type(I)
* @param after the function that should be used last * @param after the function that should be used last
* @return a composed function with a different starting function. * @return a composed function with a different starting function.
*/ */
public default GENERIC_SPECIAL_VALUE_BRACES<I> FUNCTION KS_GENERIC_TYPE<I> andThen(FUNCTION VS_GENERIC_TYPE<I> after) { public default GENERIC_SPECIAL_VALUE_BRACES<I> FUNCTION KS_GENERIC_TYPE<I> andThen(FUNCTION VS_GENERIC_TYPE<I> after) {
Objects.requireNonNull(after); Objects.requireNonNull(after);
return T -> after.APPLY(APPLY(T)); return T -> after.APPLY(APPLY(T));
} }
#endif #endif
#if VALUE_BOOLEAN #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. * Creates a Always true function that may be useful if you don't need to process information or just want a default.
* @Type(T) * @Type(T)
* @return a default returning function * @return a default returning function
*/ */
public static GENERIC_KEY_BRACES FUNCTION KEY_GENERIC_TYPE alwaysTrue() { public static GENERIC_KEY_BRACES FUNCTION KEY_GENERIC_TYPE alwaysTrue() {
return T -> true; 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. * Creates a Always false function that may be useful if you don't need to process information or just want a default.
* @Type(T) * @Type(T)
* @return a default returning function * @return a default returning function
*/ */
public static GENERIC_KEY_BRACES FUNCTION KEY_GENERIC_TYPE alwaysFalse() { public static GENERIC_KEY_BRACES FUNCTION KEY_GENERIC_TYPE alwaysFalse() {
return T -> false; return T -> false;
} }
/** /**
* A Type specific and-function helper function that reduces boxing/unboxing * A Type specific and-function helper function that reduces boxing/unboxing
* @param other the other function that should be merged with. * @param other the other function that should be merged with.
* @return a function that compares values in a and comparason * @return a function that compares values in a and comparason
*/ */
public default FUNCTION KEY_VALUE_GENERIC_TYPE andType(FUNCTION KEY_VALUE_GENERIC_TYPE other) { public default FUNCTION KEY_VALUE_GENERIC_TYPE andType(FUNCTION KEY_VALUE_GENERIC_TYPE other) {
Objects.requireNonNull(other); Objects.requireNonNull(other);
return T -> APPLY(T) && other.APPLY(T); return T -> APPLY(T) && other.APPLY(T);
} }
#if JDK_FUNCTION #if JDK_FUNCTION
@Override @Override
@Deprecated @Deprecated
public default FUNCTION KEY_VALUE_GENERIC_TYPE and(JAVA_FUNCTION KEY_VALUE_SUPER_GENERIC_TYPE other) { public default FUNCTION KEY_VALUE_GENERIC_TYPE and(JAVA_FUNCTION KEY_VALUE_SUPER_GENERIC_TYPE other) {
Objects.requireNonNull(other); Objects.requireNonNull(other);
return T -> APPLY(T) && other.APPLY(T); return T -> APPLY(T) && other.APPLY(T);
} }
@Override @Override
#else #else
/** /**
* A type specific inverter function * A type specific inverter function
* @return the same function but inverts the result * @return the same function but inverts the result
*/ */
#endif #endif
public default FUNCTION KEY_VALUE_GENERIC_TYPE negate() { public default FUNCTION KEY_VALUE_GENERIC_TYPE negate() {
return T -> !APPLY(T); return T -> !APPLY(T);
} }
/** /**
* A Type specific or-function helper function that reduces boxing/unboxing * A Type specific or-function helper function that reduces boxing/unboxing
* @param other the other function that should be merged with. * @param other the other function that should be merged with.
* @return a function that compares values in a or comparason * @return a function that compares values in a or comparason
*/ */
public default FUNCTION KEY_VALUE_GENERIC_TYPE orType(FUNCTION KEY_VALUE_GENERIC_TYPE other) { public default FUNCTION KEY_VALUE_GENERIC_TYPE orType(FUNCTION KEY_VALUE_GENERIC_TYPE other) {
Objects.requireNonNull(other); Objects.requireNonNull(other);
return T -> APPLY(T) || other.APPLY(T); return T -> APPLY(T) || other.APPLY(T);
} }
#if JDK_FUNCTION #if JDK_FUNCTION
@Override @Override
@Deprecated @Deprecated
public default FUNCTION KEY_VALUE_GENERIC_TYPE or(JAVA_FUNCTION KEY_VALUE_SUPER_GENERIC_TYPE other) { public default FUNCTION KEY_VALUE_GENERIC_TYPE or(JAVA_FUNCTION KEY_VALUE_SUPER_GENERIC_TYPE other) {
Objects.requireNonNull(other); Objects.requireNonNull(other);
return T -> APPLY(T) || other.APPLY(T); return T -> APPLY(T) || other.APPLY(T);
} }
#endif #endif
#endif #endif
} }
@@ -1,16 +1,25 @@
package speiger.src.collections.PACKAGE.lists; package speiger.src.collections.PACKAGE.lists;
import java.util.Collection; import java.util.Collection;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.ListIterator; import java.util.ListIterator;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Objects; import java.util.Objects;
import java.util.RandomAccess;
import speiger.src.collections.PACKAGE.collections.ABSTRACT_COLLECTION; import speiger.src.collections.PACKAGE.collections.ABSTRACT_COLLECTION;
import speiger.src.collections.PACKAGE.collections.COLLECTION; import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ITERATOR;
#if SPLIT_ITERATOR_FEATURE
import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR; import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR;
#endif
#if INT_LIST_MODULE && !TYPE_INT
import speiger.src.collections.ints.lists.IntList;
#endif
#if SPLIT_ITERATOR_FEATURE
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS; import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
#endif
import speiger.src.collections.utils.SanityChecks; import speiger.src.collections.utils.SanityChecks;
/** /**
@@ -66,8 +75,7 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
*/ */
@Override @Override
@Deprecated @Deprecated
public boolean addAll(Collection<? extends CLASS_TYPE> c) public boolean addAll(Collection<? extends CLASS_TYPE> c) {
{
return c instanceof COLLECTION ? addAll((COLLECTION KEY_GENERIC_TYPE)c) : addAll(size(), c); return c instanceof COLLECTION ? addAll((COLLECTION KEY_GENERIC_TYPE)c) : addAll(size(), c);
} }
@@ -221,6 +229,11 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
return new SubList(this, 0, fromIndex, toIndex); return new SubList(this, 0, fromIndex, toIndex);
} }
@Override
public LIST KEY_GENERIC_TYPE reversed() {
return new ReversedList(this);
}
@Override @Override
public ITERATOR KEY_GENERIC_TYPE iterator() { public ITERATOR KEY_GENERIC_TYPE iterator() {
return listIterator(0); return listIterator(0);
@@ -230,13 +243,25 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
public LIST_ITERATOR KEY_GENERIC_TYPE listIterator() { public LIST_ITERATOR KEY_GENERIC_TYPE listIterator() {
return listIterator(0); return listIterator(0);
} }
@Override @Override
public LIST_ITERATOR KEY_GENERIC_TYPE listIterator(int index) { public LIST_ITERATOR KEY_GENERIC_TYPE listIterator(int index) {
if(index < 0 || index > size()) throw new IndexOutOfBoundsException(); if(index < 0 || index > size()) throw new IndexOutOfBoundsException();
return new LIST_ITER(index); return new LIST_ITER(index);
} }
@Override
public LIST_ITERATOR KEY_GENERIC_TYPE indexedIterator(int...indecies) {
return new IndexedIterator(indecies);
}
#if INT_LIST_MODULE
@Override
public LIST_ITERATOR KEY_GENERIC_TYPE indexedIterator(IntList indecies) {
return new ListIndexedIterator(indecies);
}
#endif
@Override @Override
public void size(int size) { public void size(int size) {
while(size > size()) add(EMPTY_KEY_VALUE); while(size > size()) add(EMPTY_KEY_VALUE);
@@ -245,6 +270,138 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
public ABSTRACT_LIST KEY_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); } public ABSTRACT_LIST KEY_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); }
private class ReversedList extends ABSTRACT_LIST KEY_GENERIC_TYPE
{
final ABSTRACT_LIST KEY_GENERIC_TYPE list;
public ReversedList(ABSTRACT_LIST KEY_GENERIC_TYPE list) {
this.list = list;
}
@Override
public void add(int index, KEY_TYPE e) {
list.add(list.size() - index - 1, e);
}
@Override
public boolean addAll(int index, COLLECTION KEY_GENERIC_TYPE c) {
return addCollection(index, c);
}
@Override
public boolean addAll(int index, LIST KEY_GENERIC_TYPE c) {
if(c instanceof RandomAccess) {
for(int i = 0,m=c.size();i<m;i++) {
list.add(list.size() - index - i - 1, c.GET_KEY(i));
}
return true;
}
return addCollection(index, c);
}
private boolean addCollection(int index, COLLECTION KEY_GENERIC_TYPE c) {
int i = 0;
for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();i++) {
list.add(list.size() - index - i - 1, iter.NEXT());
}
return true;
}
@Override
public boolean addAll(int index, Collection<? extends CLASS_TYPE> c) {
int i = 0;
for(Iterator<? extends CLASS_TYPE> iter = c.iterator();iter.hasNext();i++) {
list.add(list.size() - index - i - 1, iter.next());
}
return true;
}
@Override
public KEY_TYPE GET_KEY(int index) {
return list.GET_KEY(list.size() - index - 1);
}
@Override
public KEY_TYPE set(int index, KEY_TYPE e) {
return list.set(list.size() - index - 1, e);
}
@Override
public KEY_TYPE REMOVE(int index) {
return list.REMOVE(list.size() - index - 1);
}
@Override
public void addElements(int from, KEY_TYPE[] a, int offset, int length) {
for(int i = 0,m=length;i<m;i++) {
list.add(list.size() - from - i - 1, a[i+offset]);
}
}
@Override
public KEY_TYPE[] getElements(int from, KEY_TYPE[] a, int offset, int length) {
return reverse(list.getElements(list.size() - from - 1, a, offset, length));
}
@Override
public void removeElements(int from, int to) {
list.removeElements(list.size() - to - 1, list.size() - from - 1);
}
@Override
public KEY_TYPE swapRemove(int index) {
return list.swapRemove(list.size() - index - 1);
}
#if TYPE_OBJECT
@Override
public <K> K[] extractElements(int from, int to, Class<K> type) {
return reverse(list.extractElements(list.size() - to - 1, list.size() - from - 1, type));
}
#else
@Override
public KEY_TYPE[] extractElements(int from, int to) {
return reverse(list.extractElements(list.size() - to - 1, list.size() - from - 1));
}
#endif
@Override
public int size() {
return list.size();
}
@Override
public void clear() {
list.clear();
}
@Override
public LIST KEY_GENERIC_TYPE reversed() {
return list;
}
#if TYPE_OBJECT
private <K> K[] reverse(K[] data) {
for (int i = 0, mid = data.length >> 1, j = data.length - 1; i < mid; i++, j--) {
K t = data[i];
data[i] = data[j];
data[j] = t;
}
return data;
}
#else
private KEY_TYPE[] reverse(KEY_TYPE[] data) {
for (int i = 0, mid = data.length >> 1, j = data.length - 1; i < mid; i++, j--) {
KEY_TYPE t = data[i];
data[i] = data[j];
data[j] = t;
}
return data;
}
#endif
}
private class SubList extends ABSTRACT_LIST KEY_GENERIC_TYPE private class SubList extends ABSTRACT_LIST KEY_GENERIC_TYPE
{ {
final ABSTRACT_LIST KEY_GENERIC_TYPE list; final ABSTRACT_LIST KEY_GENERIC_TYPE list;
@@ -379,9 +536,10 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
public int size() { public int size() {
return size; return size;
} }
#if SPLIT_ITERATOR_FEATURE
@Override @Override
public SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createSplititerator(this, 16464); } public SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createSplititerator(this, 16464); }
#endif
@Override @Override
public LIST_ITERATOR KEY_GENERIC_TYPE listIterator(int index) { public LIST_ITERATOR KEY_GENERIC_TYPE listIterator(int index) {
@@ -490,7 +648,155 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
} }
} }
} }
#if INT_LIST_MODULE
private class ListIndexedIterator implements LIST_ITERATOR KEY_GENERIC_TYPE {
IntList indecies;
int index;
int lastReturned = -1;
ListIndexedIterator(IntList indecies) {
this.indecies = indecies;
}
@Override
public boolean hasNext() {
return index < indecies.size();
}
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
int i = index++;
return GET_KEY((lastReturned = indecies.getInt(i)));
}
@Override
public boolean hasPrevious() {
return index > 0;
}
@Override
public KEY_TYPE PREVIOUS() {
if(!hasPrevious()) throw new NoSuchElementException();
index--;
return GET_KEY((lastReturned = indecies.getInt(index)));
}
@Override
public int nextIndex() {
return index;
}
@Override
public int previousIndex() {
return index-1;
}
@Override
public void remove() { throw new UnsupportedOperationException(); }
@Override
public void add(KEY_TYPE e) { throw new UnsupportedOperationException(); }
@Override
public void set(KEY_TYPE e) {
if(lastReturned == -1) throw new IllegalStateException();
ABSTRACT_LIST.this.set(lastReturned, e);
}
@Override
public int skip(int amount) {
if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
int steps = Math.min(amount, indecies.size() - index);
index += steps;
if(steps > 0) lastReturned = Math.min(index-1, indecies.size()-1);
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;
if(steps > 0) lastReturned = Math.max(index, 0);
return steps;
}
}
#endif
private class IndexedIterator implements LIST_ITERATOR KEY_GENERIC_TYPE {
int[] indecies;
int index;
int lastReturned = -1;
IndexedIterator(int[] indecies) {
this.indecies = indecies;
}
@Override
public boolean hasNext() {
return index < indecies.length;
}
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
int i = index++;
return GET_KEY((lastReturned = indecies[i]));
}
@Override
public boolean hasPrevious() {
return index > 0;
}
@Override
public KEY_TYPE PREVIOUS() {
if(!hasPrevious()) throw new NoSuchElementException();
index--;
return GET_KEY((lastReturned = indecies[index]));
}
@Override
public int nextIndex() {
return index;
}
@Override
public int previousIndex() {
return index-1;
}
@Override
public void remove() { throw new UnsupportedOperationException(); }
@Override
public void add(KEY_TYPE e) { throw new UnsupportedOperationException(); }
@Override
public void set(KEY_TYPE e) {
if(lastReturned == -1) throw new IllegalStateException();
ABSTRACT_LIST.this.set(lastReturned, e);
}
@Override
public int skip(int amount) {
if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
int steps = Math.min(amount, indecies.length - index);
index += steps;
if(steps > 0) lastReturned = Math.min(index-1, indecies.length-1);
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;
if(steps > 0) lastReturned = Math.max(index, 0);
return steps;
}
}
private class LIST_ITER implements LIST_ITERATOR KEY_GENERIC_TYPE { private class LIST_ITER implements LIST_ITERATOR KEY_GENERIC_TYPE {
int index; int index;
int lastReturned = -1; int lastReturned = -1;
@@ -568,7 +874,7 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed"); if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
int steps = Math.min(amount, index); int steps = Math.min(amount, index);
index -= steps; index -= steps;
if(steps > 0) lastReturned = Math.min(index, size()-1); if(steps > 0) lastReturned = Math.max(index, 0);
return steps; return steps;
} }
} }
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -3,10 +3,26 @@ package speiger.src.collections.PACKAGE.lists;
import java.util.Arrays; import java.util.Arrays;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Comparator; import java.util.Comparator;
#else if !TYPE_BOOLEAN
import java.util.stream.JAVA_STREAM;
import java.util.stream.StreamSupport;
#endif #endif
import java.util.Collection; import java.util.Collection;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Objects; import java.util.Objects;
#if JDK_TYPE
import java.util.OPTIONAL;
#if SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#if PRIMITIVES
import java.util.function.Supplier;
#else
import java.util.stream.Stream;
import java.util.stream.Collector;
#endif
import speiger.src.collections.PACKAGE.utils.COLLECTIONS;
#endif
#endif
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.function.BiFunction; import java.util.function.BiFunction;
import java.util.function.Consumer; import java.util.function.Consumer;
@@ -20,6 +36,7 @@ import java.util.function.PREDICATE;
#if !JDK_FUNCTION #if !JDK_FUNCTION
import java.util.function.JAVA_PREDICATE; import java.util.function.JAVA_PREDICATE;
#endif #endif
import java.util.function.JAVA_UNARY_OPERATOR; import java.util.function.JAVA_UNARY_OPERATOR;
#endif #endif
@@ -27,6 +44,9 @@ import speiger.src.collections.PACKAGE.collections.COLLECTION;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER; import speiger.src.collections.PACKAGE.functions.CONSUMER;
#if !JDK_TYPE
import speiger.src.collections.PACKAGE.functions.OPTIONAL;
#endif
import speiger.src.collections.PACKAGE.utils.ARRAYS; import speiger.src.collections.PACKAGE.utils.ARRAYS;
#endif #endif
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
@@ -36,10 +56,6 @@ import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.objects.utils.ObjectArrays; import speiger.src.collections.objects.utils.ObjectArrays;
import speiger.src.collections.PACKAGE.utils.ITERATORS; import speiger.src.collections.PACKAGE.utils.ITERATORS;
#if PRIMITIVES && SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
import java.util.stream.JAVA_STREAM;
import java.util.stream.StreamSupport;
#endif
#if SPLIT_ITERATOR_FEATURE #if SPLIT_ITERATOR_FEATURE
import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR; import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR;
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS; import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
@@ -120,6 +136,42 @@ public class IMMUTABLE_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_T
data = Arrays.copyOfRange(a, offset, offset+length); data = Arrays.copyOfRange(a, offset, offset+length);
} }
#if JDK_TYPE && SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#if TYPE_OBJECT
/**
* Creates a Collector for a ImmutableList
* @Type(T)
* @return a collector
*/
public static <T> Collector<T, COLLECTION<T>, ImmutableObjectList<T>> toList() {
return Collector.of(COLLECTIONS::wrapper, COLLECTION::add, ImmutableObjectList::merge, E -> new IMMUTABLE_LIST<>(E.toArray((T[])new Object[E.size()])));
}
/**
* Collects a Stream to a ImmutableList
* @Type(T)
* @return a list with the contents of the Stream
*/
public static <T> ImmutableObjectList KEY_GENERIC_TYPE toList(Stream<T> stream) {
return stream.collect(toList());
}
private static <T> COLLECTION<T> merge(COLLECTION<T> a, COLLECTION<T> b) {
a.addAll(b);
return a;
}
#else
/**
* Collects a Stream to a ImmutableList
* @return a list with the contents of the Stream
*/
public static IMMUTABLE_LIST toList(JAVA_STREAM stream) {
return new IMMUTABLE_LIST(stream.collect((Supplier<COLLECTION>)COLLECTIONS::wrapper, COLLECTION::add, COLLECTION::addAll).TO_ARRAY());
}
#endif
#endif
@Override @Override
public boolean add(KEY_TYPE e) { throw new UnsupportedOperationException(); } public boolean add(KEY_TYPE e) { throw new UnsupportedOperationException(); }
@Override @Override
@@ -335,12 +387,12 @@ public class IMMUTABLE_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_T
} }
@Override @Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { public OPTIONAL KEY_GENERIC_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter); Objects.requireNonNull(filter);
for(int i = 0,m=data.length;i<m;i++) { for(int i = 0,m=data.length;i<m;i++) {
if(filter.test(data[i])) return data[i]; if(filter.test(data[i])) return OPTIONAL.GET_OPTIONAL(data[i]);
} }
return EMPTY_VALUE; return OPTIONAL.empty();
} }
#if !TYPE_OBJECT #if !TYPE_OBJECT
@@ -367,7 +419,7 @@ public class IMMUTABLE_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_T
#endif #endif
@Override @Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { public OPTIONAL KEY_GENERIC_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator); Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_VALUE; KEY_TYPE state = EMPTY_VALUE;
boolean empty = true; boolean empty = true;
@@ -379,7 +431,7 @@ public class IMMUTABLE_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_T
} }
state = operator.APPLY_VALUE(state, data[i]); state = operator.APPLY_VALUE(state, data[i]);
} }
return state; return empty ? OPTIONAL.empty() : OPTIONAL.GET_OPTIONAL(state);
} }
@Override @Override
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -14,6 +14,15 @@ import speiger.src.collections.PACKAGE.functions.function.FUNCTION;
#endif #endif
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.PACKAGE.maps.interfaces.MAP; import speiger.src.collections.PACKAGE.maps.interfaces.MAP;
#if ORDERED_MAP_FEATURE
import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP;
import speiger.src.collections.PACKAGE.sets.ORDERED_SET;
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ORDERED_COLLECTION;
#if !TYPE_OBJECT
import speiger.src.collections.objects.sets.AbstractObjectSet;
import speiger.src.collections.objects.sets.ObjectOrderedSet;
#endif
#endif
import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET; import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET;
import speiger.src.collections.PACKAGE.sets.SET; import speiger.src.collections.PACKAGE.sets.SET;
#if MAPS_FEATURE #if MAPS_FEATURE
@@ -42,7 +51,7 @@ import speiger.src.collections.utils.SanityChecks;
*/ */
public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CLASS_TYPE, CLASS_VALUE_TYPE> implements MAP KEY_VALUE_GENERIC_TYPE public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CLASS_TYPE, CLASS_VALUE_TYPE> implements MAP KEY_VALUE_GENERIC_TYPE
{ {
protected VALUE_TYPE defaultReturnValue = EMPTY_VALUE; protected VALUE_TYPE defaultReturnValue = INVALID_VALUE;
@Override @Override
public VALUE_TYPE getDefaultReturnValue() { public VALUE_TYPE getDefaultReturnValue() {
@@ -119,7 +128,7 @@ public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CL
public void putAll(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, int offset, int size) { public void putAll(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, int offset, int size) {
SanityChecks.checkArrayCapacity(keys.length, offset, size); SanityChecks.checkArrayCapacity(keys.length, offset, size);
SanityChecks.checkArrayCapacity(values.length, offset, size); SanityChecks.checkArrayCapacity(values.length, offset, size);
for(int i = 0;i<size;i++) put(keys[i], values[i]); for(int i = 0;i<size;i++) put(OBJ_TO_KEY(keys[i]), OBJ_TO_VALUE(values[i]));
} }
#endif #endif
@@ -201,6 +210,96 @@ public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CL
@Override @Override
public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction); Objects.requireNonNull(mappingFunction);
#if !VALUE_OBJECT
VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, GET_VALUE(key));
#else
VALUE_TYPE value = GET_VALUE(key);
VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, value);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
if(VALUE_EQUALS_NOT(value, getDefaultReturnValue()) || containsKey(key)) {
remove(key);
return getDefaultReturnValue();
}
return getDefaultReturnValue();
}
#endif
put(key, newValue);
return newValue;
}
@Override
public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction);
#if VALUE_OBJECT
VALUE_TYPE value;
if((value = GET_VALUE(key)) == getDefaultReturnValue() || !containsKey(key)) {
VALUE_TYPE newValue = mappingFunction.APPLY(key);
if(VALUE_EQUALS_NOT(newValue, getDefaultReturnValue())) {
put(key, newValue);
return newValue;
}
}
return value;
#else
if(!containsKey(key)) {
VALUE_TYPE newValue = mappingFunction.APPLY(key);
put(key, newValue);
return newValue;
}
return get(key);
#endif
}
@Override
public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) {
Objects.requireNonNull(valueProvider);
#if VALUE_OBJECT
VALUE_TYPE value;
if((value = GET_VALUE(key)) == getDefaultReturnValue() || !containsKey(key)) {
VALUE_TYPE newValue = valueProvider.VALUE_SUPPLY_GET();
if(VALUE_EQUALS_NOT(newValue, getDefaultReturnValue())) {
put(key, newValue);
return newValue;
}
}
return value;
#else
if(!containsKey(key)) {
VALUE_TYPE newValue = valueProvider.VALUE_SUPPLY_GET();
put(key, newValue);
return newValue;
}
return get(key);
#endif
}
@Override
public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction);
#if VALUE_OBJECT
VALUE_TYPE value;
if(VALUE_EQUALS_NOT((value = GET_VALUE(key)), getDefaultReturnValue()) || containsKey(key)) {
VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, value);
if(VALUE_EQUALS_NOT(newValue, getDefaultReturnValue())) {
put(key, newValue);
return newValue;
}
remove(key);
}
#else
if(containsKey(key)) {
VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, GET_VALUE(key));
put(key, newValue);
return newValue;
}
#endif
return getDefaultReturnValue();
}
#if !VALUE_OBJECT
@Override
public VALUE_TYPE COMPUTENonDefault(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction);
VALUE_TYPE value = GET_VALUE(key); VALUE_TYPE value = GET_VALUE(key);
VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, value); VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, value);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
@@ -215,7 +314,7 @@ public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CL
} }
@Override @Override
public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) { public VALUE_TYPE COMPUTE_IF_ABSENTNonDefault(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction); Objects.requireNonNull(mappingFunction);
VALUE_TYPE value; VALUE_TYPE value;
if((value = GET_VALUE(key)) == getDefaultReturnValue() || !containsKey(key)) { if((value = GET_VALUE(key)) == getDefaultReturnValue() || !containsKey(key)) {
@@ -229,7 +328,7 @@ public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CL
} }
@Override @Override
public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) { public VALUE_TYPE SUPPLY_IF_ABSENTNonDefault(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) {
Objects.requireNonNull(valueProvider); Objects.requireNonNull(valueProvider);
VALUE_TYPE value; VALUE_TYPE value;
if((value = GET_VALUE(key)) == getDefaultReturnValue() || !containsKey(key)) { if((value = GET_VALUE(key)) == getDefaultReturnValue() || !containsKey(key)) {
@@ -243,7 +342,7 @@ public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CL
} }
@Override @Override
public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { public VALUE_TYPE COMPUTE_IF_PRESENTNonDefault(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction); Objects.requireNonNull(mappingFunction);
VALUE_TYPE value; VALUE_TYPE value;
if(VALUE_EQUALS_NOT((value = GET_VALUE(key)), getDefaultReturnValue()) || containsKey(key)) { if(VALUE_EQUALS_NOT((value = GET_VALUE(key)), getDefaultReturnValue()) || containsKey(key)) {
@@ -256,7 +355,8 @@ public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CL
} }
return getDefaultReturnValue(); return getDefaultReturnValue();
} }
#endif
@Override @Override
public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction); Objects.requireNonNull(mappingFunction);
@@ -452,6 +552,132 @@ public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CL
return hash; return hash;
} }
public static class REVERSED_ORDERED_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements ORDERED_MAP KEY_VALUE_GENERIC_TYPE {
ORDERED_MAP KEY_VALUE_GENERIC_TYPE map;
public REVERSED_ORDERED_MAP(ORDERED_MAP KEY_VALUE_GENERIC_TYPE map) {
this.map = map;
}
@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 ORDERED_MAP KEY_VALUE_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); }
@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); }
#if !TYPE_OBJECT || !VALUE_OBJECT
@Override
public boolean remove(KEY_TYPE key, VALUE_TYPE value) { return map.remove(key, value); }
#endif
@Override
public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { return map.REMOVE_VALUEOrDefault(key, defaultValue); }
@Override
#if TYPE_OBJECT
public boolean containsKey(Object key) { return map.containsKey(key); }
#else
public boolean containsKey(KEY_TYPE key) { return map.containsKey(key); }
#endif
@Override
#if VALUE_OBJECT
public boolean containsValue(Object value) { return map.containsValue(value); }
#else
public boolean containsValue(VALUE_TYPE value) { return map.containsValue(value); }
#endif
@Override
public boolean replace(KEY_TYPE key, VALUE_TYPE oldValue, VALUE_TYPE newValue) { return map.replace(key, oldValue, newValue); }
@Override
public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value) { return map.replace(key, value); }
@Override
public void REPLACE_VALUES(MAP KEY_VALUE_GENERIC_TYPE m) { map.REPLACE_VALUES(m); }
@Override
public void REPLACE_VALUES(UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { map.REPLACE_VALUES(mappingFunction); }
@Override
public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { return map.COMPUTE(key, mappingFunction); }
@Override
public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) { return map.COMPUTE_IF_ABSENT(key, mappingFunction); }
@Override
public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) { return map.SUPPLY_IF_ABSENT(key, valueProvider); }
@Override
public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { return map.COMPUTE_IF_PRESENT(key, mappingFunction); }
#if !VALUE_OBJECT
@Override
public VALUE_TYPE COMPUTENonDefault(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { return map.COMPUTENonDefault(key, mappingFunction); }
@Override
public VALUE_TYPE COMPUTE_IF_ABSENTNonDefault(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) { return map.COMPUTE_IF_ABSENTNonDefault(key, mappingFunction); }
@Override
public VALUE_TYPE SUPPLY_IF_ABSENTNonDefault(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) { return map.SUPPLY_IF_ABSENTNonDefault(key, valueProvider); }
@Override
public VALUE_TYPE COMPUTE_IF_PRESENTNonDefault(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { return map.COMPUTE_IF_PRESENTNonDefault(key, mappingFunction); }
#endif
@Override
public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { return map.MERGE(key, value, mappingFunction); }
#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 GET_VALUE(KEY_TYPE key) { return map.GET_VALUE(key); }
@Override
public VALUE_TYPE putAndMoveToFirst(KEY_TYPE key, VALUE_TYPE value) { return map.putAndMoveToLast(key, value); }
@Override
public VALUE_TYPE putAndMoveToLast(KEY_TYPE key, VALUE_TYPE value) { return map.putAndMoveToFirst(key, value); }
@Override
public VALUE_TYPE putFirst(KEY_TYPE key, VALUE_TYPE value) { return map.putLast(key, value); }
@Override
public VALUE_TYPE putLast(KEY_TYPE key, VALUE_TYPE value) { return map.putFirst(key, value); }
@Override
public boolean moveToFirst(KEY_TYPE key) { return map.moveToLast(key); }
@Override
public boolean moveToLast(KEY_TYPE key) { return map.moveToFirst(key); }
@Override
public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key) { return map.getAndMoveToLast(key); }
@Override
public VALUE_TYPE getAndMoveToLast(KEY_TYPE key) { return map.getAndMoveToFirst(key); }
@Override
public KEY_TYPE FIRST_ENTRY_KEY() { return map.LAST_ENTRY_KEY(); }
@Override
public KEY_TYPE POLL_FIRST_ENTRY_KEY() { return map.POLL_LAST_ENTRY_KEY(); }
@Override
public KEY_TYPE LAST_ENTRY_KEY() { return map.FIRST_ENTRY_KEY(); }
@Override
public KEY_TYPE POLL_LAST_ENTRY_KEY() { return map.POLL_FIRST_ENTRY_KEY(); }
@Override
public VALUE_TYPE FIRST_ENTRY_VALUE() { return map.LAST_ENTRY_VALUE(); }
@Override
public VALUE_TYPE LAST_ENTRY_VALUE() { return map.FIRST_ENTRY_VALUE(); }
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE firstEntry() { return map.lastEntry(); }
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE lastEntry() { return map.firstEntry(); }
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirstEntry() { return map.pollLastEntry(); }
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLastEntry() { return map.pollFirstEntry(); }
@Override
public ObjectOrderedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> ENTRY_SET() { return new AbstractObjectSet.ReversedObjectOrderedSet<>(map.ENTRY_SET()); }
@Override
public ORDERED_SET KEY_GENERIC_TYPE keySet() { return new ABSTRACT_SET.REVERSED_ORDERED_SETBRACES(map.keySet()); }
@Override
public VALUE_ORDERED_COLLECTION VALUE_GENERIC_TYPE values() { return map.values().reversed(); }
@Override
public ORDERED_MAP KEY_VALUE_GENERIC_TYPE reversed() { return map; }
}
/** /**
* A Simple Type Specific Entry class to reduce boxing/unboxing * A Simple Type Specific Entry class to reduce boxing/unboxing
* @Type(T) * @Type(T)
@@ -1,95 +1,95 @@
package speiger.src.collections.PACKAGE.maps.interfaces; package speiger.src.collections.PACKAGE.maps.interfaces;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
import java.util.function.BiFunction; import java.util.function.BiFunction;
import java.util.function.Function; import java.util.function.Function;
/** /**
* A type specific ConcurrentMap interface that reduces boxing/unboxing. * A type specific ConcurrentMap interface that reduces boxing/unboxing.
* Since the interface adds nothing new. It is there just for completion sake. * Since the interface adds nothing new. It is there just for completion sake.
* @Type(T) * @Type(T)
* @ValueType(V) * @ValueType(V)
*/ */
public interface CONCURRENT_MAP KEY_VALUE_GENERIC_TYPE extends ConcurrentMap<CLASS_TYPE, CLASS_VALUE_TYPE>, MAP KEY_VALUE_GENERIC_TYPE public interface CONCURRENT_MAP KEY_VALUE_GENERIC_TYPE extends ConcurrentMap<CLASS_TYPE, CLASS_VALUE_TYPE>, MAP KEY_VALUE_GENERIC_TYPE
{ {
@Override @Override
@Primitive @Primitive
public default CLASS_VALUE_TYPE compute(CLASS_TYPE key, BiFunction<? super CLASS_TYPE, ? super CLASS_VALUE_TYPE, ? extends CLASS_VALUE_TYPE> mappingFunction) { public default CLASS_VALUE_TYPE compute(CLASS_TYPE key, BiFunction<? super CLASS_TYPE, ? super CLASS_VALUE_TYPE, ? extends CLASS_VALUE_TYPE> mappingFunction) {
return MAP.super.compute(key, mappingFunction); return MAP.super.compute(key, mappingFunction);
} }
@Override @Override
@Primitive @Primitive
public default CLASS_VALUE_TYPE computeIfAbsent(CLASS_TYPE key, Function<? super CLASS_TYPE, ? extends CLASS_VALUE_TYPE> mappingFunction) { public default CLASS_VALUE_TYPE computeIfAbsent(CLASS_TYPE key, Function<? super CLASS_TYPE, ? extends CLASS_VALUE_TYPE> mappingFunction) {
return MAP.super.computeIfAbsent(key, mappingFunction); return MAP.super.computeIfAbsent(key, mappingFunction);
} }
@Override @Override
@Primitive @Primitive
public default CLASS_VALUE_TYPE computeIfPresent(CLASS_TYPE key, BiFunction<? super CLASS_TYPE, ? super CLASS_VALUE_TYPE, ? extends CLASS_VALUE_TYPE> mappingFunction) { public default CLASS_VALUE_TYPE computeIfPresent(CLASS_TYPE key, BiFunction<? super CLASS_TYPE, ? super CLASS_VALUE_TYPE, ? extends CLASS_VALUE_TYPE> mappingFunction) {
return MAP.super.computeIfPresent(key, mappingFunction); return MAP.super.computeIfPresent(key, mappingFunction);
} }
@Override @Override
@Primitive @Primitive
public default void forEach(BiConsumer<? super CLASS_TYPE, ? super CLASS_VALUE_TYPE> action) { public default void forEach(BiConsumer<? super CLASS_TYPE, ? super CLASS_VALUE_TYPE> action) {
MAP.super.forEach(action); MAP.super.forEach(action);
} }
@Override @Override
@Primitive @Primitive
public default CLASS_VALUE_TYPE merge(CLASS_TYPE key, CLASS_VALUE_TYPE value, BiFunction<? super CLASS_VALUE_TYPE, ? super CLASS_VALUE_TYPE, ? extends CLASS_VALUE_TYPE> mappingFunction) { public default CLASS_VALUE_TYPE merge(CLASS_TYPE key, CLASS_VALUE_TYPE value, BiFunction<? super CLASS_VALUE_TYPE, ? super CLASS_VALUE_TYPE, ? extends CLASS_VALUE_TYPE> mappingFunction) {
return MAP.super.merge(key, value, mappingFunction); return MAP.super.merge(key, value, mappingFunction);
} }
#if TYPE_OBJECT && VALUE_OBJECT #if TYPE_OBJECT && VALUE_OBJECT
@Override @Override
public CLASS_VALUE_TYPE getOrDefault(Object key, CLASS_VALUE_TYPE defaultValue); public CLASS_VALUE_TYPE getOrDefault(Object key, CLASS_VALUE_TYPE defaultValue);
@Override @Override
public CLASS_VALUE_TYPE putIfAbsent(CLASS_TYPE key, CLASS_VALUE_TYPE value); public CLASS_VALUE_TYPE putIfAbsent(CLASS_TYPE key, CLASS_VALUE_TYPE value);
@Override @Override
public boolean remove(Object key, Object value); public boolean remove(Object key, Object value);
@Override @Override
public boolean replace(CLASS_TYPE key, CLASS_VALUE_TYPE oldValue, CLASS_VALUE_TYPE newValue); public boolean replace(CLASS_TYPE key, CLASS_VALUE_TYPE oldValue, CLASS_VALUE_TYPE newValue);
@Override @Override
public CLASS_VALUE_TYPE replace(CLASS_TYPE key, CLASS_VALUE_TYPE value); public CLASS_VALUE_TYPE replace(CLASS_TYPE key, CLASS_VALUE_TYPE value);
#else #else
@Primitive @Primitive
@Override @Override
public default CLASS_VALUE_TYPE getOrDefault(Object key, CLASS_VALUE_TYPE defaultValue) { public default CLASS_VALUE_TYPE getOrDefault(Object key, CLASS_VALUE_TYPE defaultValue) {
return MAP.super.getOrDefault(key, defaultValue); return MAP.super.getOrDefault(key, defaultValue);
} }
@Override @Override
@Primitive @Primitive
public default CLASS_VALUE_TYPE putIfAbsent(CLASS_TYPE key, CLASS_VALUE_TYPE value) { public default CLASS_VALUE_TYPE putIfAbsent(CLASS_TYPE key, CLASS_VALUE_TYPE value) {
return MAP.super.putIfAbsent(key, value); return MAP.super.putIfAbsent(key, value);
} }
@Override @Override
@Deprecated @Deprecated
public default boolean remove(Object key, Object value) { public default boolean remove(Object key, Object value) {
return MAP.super.remove(key, value); return MAP.super.remove(key, value);
} }
@Override @Override
@Deprecated @Deprecated
public default boolean replace(CLASS_TYPE key, CLASS_VALUE_TYPE oldValue, CLASS_VALUE_TYPE newValue) { public default boolean replace(CLASS_TYPE key, CLASS_VALUE_TYPE oldValue, CLASS_VALUE_TYPE newValue) {
return MAP.super.replace(key, oldValue, newValue); return MAP.super.replace(key, oldValue, newValue);
} }
@Override @Override
@Deprecated @Deprecated
public default CLASS_VALUE_TYPE replace(CLASS_TYPE key, CLASS_VALUE_TYPE value) { public default CLASS_VALUE_TYPE replace(CLASS_TYPE key, CLASS_VALUE_TYPE value) {
return MAP.super.replace(key, value); return MAP.super.replace(key, value);
} }
#endif #endif
@Override @Override
@Deprecated @Deprecated
public default void replaceAll(BiFunction<? super CLASS_TYPE, ? super CLASS_VALUE_TYPE, ? extends CLASS_VALUE_TYPE> mappingFunction) { public default void replaceAll(BiFunction<? super CLASS_TYPE, ? super CLASS_VALUE_TYPE, ? extends CLASS_VALUE_TYPE> mappingFunction) {
MAP.super.replaceAll(mappingFunction); MAP.super.replaceAll(mappingFunction);
} }
} }
@@ -154,7 +154,7 @@ public interface MAP KEY_VALUE_GENERIC_TYPE extends Map<CLASS_TYPE, CLASS_VALUE_
* @return the last present value or default return value. * @return the last present value or default return value.
*/ */
public default CLASS_VALUE_TYPE put(Map.Entry<CLASS_TYPE, CLASS_VALUE_TYPE> entry) { public default CLASS_VALUE_TYPE put(Map.Entry<CLASS_TYPE, CLASS_VALUE_TYPE> entry) {
return put(entry.getKey(), entry.getValue()); return put(OBJ_TO_KEY(entry.getKey()), OBJ_TO_VALUE(entry.getValue()));
} }
#endif #endif
@@ -382,21 +382,26 @@ public interface MAP KEY_VALUE_GENERIC_TYPE extends Map<CLASS_TYPE, CLASS_VALUE_
public void REPLACE_VALUES(UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction); public void REPLACE_VALUES(UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction);
/** /**
* A Type Specific compute method to reduce boxing/unboxing * A Type Specific compute method to reduce boxing/unboxing
* If the generated value equals the getDefaultReturnValue it will simply not insert it since that is treated as "null".
* A "Null Value" will be treated as "Do not insert/remove" based on how the Java has specified it.
* @param key the key that should be computed * @param key the key that should be computed
* @param mappingFunction the operator that should generate the value * @param mappingFunction the operator that should generate the value
* @return the result of the computation * @return the result of the computation
*/ */
public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction); public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction);
/** /**
* A Type Specific compute method to reduce boxing/unboxing * A Type Specific computeIfAbsent method to reduce boxing/unboxing
* If the generated value equals the getDefaultReturnValue it will simply not insert it since that is treated as "null".
* A "Null Value" will be treated as "Do not insert/remove" based on how the Java has specified it.
* @param key the key that should be computed * @param key the key that should be computed
* @param mappingFunction the operator that should generate the value if not present * @param mappingFunction the operator that should generate the value if not present
* @return the result of the computed value or present value * @return the result of the computed value or present value
*/ */
public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction); public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction);
/** /**
* A Supplier based computeIfAbsent function to fill the most used usecase of this function * A Supplier based computeIfAbsent function to fill the most used usecase of this function
* If the generated value equals the getDefaultReturnValue it will simply not insert it since that is treated as "null".
* A "Null Value" will be treated as "Do not insert/remove" based on how the Java has specified it.
* @param key the key that should be computed * @param key the key that should be computed
* @param valueProvider the value if not present * @param valueProvider the value if not present
* @return the result of the computed value or present value * @return the result of the computed value or present value
@@ -404,14 +409,57 @@ public interface MAP KEY_VALUE_GENERIC_TYPE extends Map<CLASS_TYPE, CLASS_VALUE_
public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider); public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider);
/** /**
* A Type Specific compute method to reduce boxing/unboxing * A Type Specific compute method to reduce boxing/unboxing
* If the generated value equals the getDefaultReturnValue it will simply not insert it since that is treated as "null".
* A "Null Value" will be treated as "Do not insert/remove" based on how the Java has specified it.
* @param key the key that should be computed * @param key the key that should be computed
* @param mappingFunction the operator that should generate the value if present * @param mappingFunction the operator that should generate the value if present
* @return the result of the default return value or present value * @return the result of the default return value or present value
* @note if not present then compute is not executed * @note if not present then compute is not executed
*/ */
public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction); public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction);
#if !VALUE_OBJECT
/**
* A Type Specific compute method to reduce boxing/unboxing
* If the generated value equals the getDefaultReturnValue it will simply not insert it since that is treated as "null".
* A "Null Value" will be treated as "Do not insert/remove" based on how the Java has specified it.
* @param key the key that should be computed
* @param mappingFunction the operator that should generate the value
* @return the result of the computation
*/
public VALUE_TYPE COMPUTENonDefault(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction);
/**
* A Type Specific computeIfAbsent method to reduce boxing/unboxing
* If the generated value equals the getDefaultReturnValue it will simply not insert it since that is treated as "null".
* A "Null Value" will be treated as "Do not insert/remove" based on how the Java has specified it.
* @param key the key that should be computed
* @param mappingFunction the operator that should generate the value if not present
* @return the result of the computed value or present value
*/
public VALUE_TYPE COMPUTE_IF_ABSENTNonDefault(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction);
/**
* A Supplier based computeIfAbsent function to fill the most used usecase of this function
* If the generated value equals the getDefaultReturnValue it will simply not insert it since that is treated as "null".
* A "Null Value" will be treated as "Do not insert/remove" based on how the Java has specified it.
* @param key the key that should be computed
* @param valueProvider the value if not present
* @return the result of the computed value or present value
*/
public VALUE_TYPE SUPPLY_IF_ABSENTNonDefault(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider);
/**
* A Type Specific compute method to reduce boxing/unboxing
* If the generated value equals the getDefaultReturnValue it will simply not insert it since that is treated as "null".
* A "Null Value" will be treated as "Do not insert/remove" based on how the Java has specified it.
* @param key the key that should be computed
* @param mappingFunction the operator that should generate the value if present
* @return the result of the default return value or present value
* @note if not present then compute is not executed
*/
public VALUE_TYPE COMPUTE_IF_PRESENTNonDefault(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction);
#endif
/** /**
* A Type Specific merge method to reduce boxing/unboxing * A Type Specific merge method to reduce boxing/unboxing
* If the generated value equals the getDefaultReturnValue it will simply not insert it since that is treated as "null".
* A "Null Value" will be treated as "Do not insert/remove" based on how the Java has specified it.
* @param key the key that should be be searched for * @param key the key that should be be searched for
* @param value the value that should be merged with * @param value the value that should be merged with
* @param mappingFunction the operator that should generate the new Value * @param mappingFunction the operator that should generate the new Value
@@ -421,6 +469,8 @@ public interface MAP KEY_VALUE_GENERIC_TYPE extends Map<CLASS_TYPE, CLASS_VALUE_
public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction); public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction);
/** /**
* A Bulk method for merging Maps. * A Bulk method for merging Maps.
* If the generated value equals the getDefaultReturnValue it will simply not insert it since that is treated as "null".
* A "Null Value" will be treated as "Do not insert/remove" based on how the Java has specified it.
* @param m the entries that should be bulk added * @param m the entries that should be bulk added
* @param mappingFunction the operator that should generate the new Value * @param mappingFunction the operator that should generate the new Value
* @note if the result matches the default return value then the key is removed from the map * @note if the result matches the default return value then the key is removed from the map
@@ -1,8 +1,15 @@
package speiger.src.collections.PACKAGE.maps.interfaces; package speiger.src.collections.PACKAGE.maps.interfaces;
#if JAVA_VERSION>=21
import java.util.Map;
import java.util.SequencedMap;
#endif
#if MAPS_FEATURE #if MAPS_FEATURE
import speiger.src.collections.PACKAGE.utils.maps.MAPS; import speiger.src.collections.PACKAGE.utils.maps.MAPS;
#endif #endif
import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP;
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ORDERED_COLLECTION;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.sets.ORDERED_SET; import speiger.src.collections.PACKAGE.sets.ORDERED_SET;
#endif #endif
@@ -17,7 +24,11 @@ import speiger.src.collections.objects.sets.ObjectOrderedSet;
* @Type(T) * @Type(T)
* @ValueType(V) * @ValueType(V)
*/ */
#if JAVA_VERSION>=21
public interface ORDERED_MAP KEY_VALUE_GENERIC_TYPE extends MAP KEY_VALUE_GENERIC_TYPE, SequencedMap<CLASS_TYPE, CLASS_VALUE_TYPE>
#else
public interface ORDERED_MAP KEY_VALUE_GENERIC_TYPE extends MAP KEY_VALUE_GENERIC_TYPE public interface ORDERED_MAP KEY_VALUE_GENERIC_TYPE extends MAP KEY_VALUE_GENERIC_TYPE
#endif
{ {
/** /**
* A customized put method that allows you to insert into the first index. * A customized put method that allows you to insert into the first index.
@@ -37,6 +48,26 @@ public interface ORDERED_MAP KEY_VALUE_GENERIC_TYPE extends MAP KEY_VALUE_GENERI
*/ */
public VALUE_TYPE putAndMoveToLast(KEY_TYPE key, VALUE_TYPE value); public VALUE_TYPE putAndMoveToLast(KEY_TYPE key, VALUE_TYPE value);
/**
* A alternative to putAndMoveToFirst.
* This method simply puts an entry at the first spot of the Map but only if the entry is missing.
* @param key the key that should be inserted
* @param value the value that should be inserted
* @return the previous present or default return value
* @see java.util.Map#put(Object, Object)
*/
public VALUE_TYPE putFirst(KEY_TYPE key, VALUE_TYPE value);
/**
* A alternative to putAndMoveToLast.
* This method simply puts an entry at the last spot of the Map but only if the entry is missing.
* @param key the key that should be inserted
* @param value the value that should be inserted
* @return the previous present or default return value
* @see java.util.Map#put(Object, Object)
*/
public VALUE_TYPE putLast(KEY_TYPE key, VALUE_TYPE value);
/** /**
* A specific move method to move a given key/value to the first index. * A specific move method to move a given key/value to the first index.
* @param key that should be moved to the first index * @param key that should be moved to the first index
@@ -97,13 +128,34 @@ public interface ORDERED_MAP KEY_VALUE_GENERIC_TYPE extends MAP KEY_VALUE_GENERI
*/ */
public VALUE_TYPE LAST_ENTRY_VALUE(); public VALUE_TYPE LAST_ENTRY_VALUE();
@Java21
public MAP.Entry KEY_VALUE_GENERIC_TYPE firstEntry();
@Java21
public MAP.Entry KEY_VALUE_GENERIC_TYPE lastEntry();
@Java21
public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirstEntry();
@Java21
public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLastEntry();
@Override @Override
public ORDERED_MAP KEY_VALUE_GENERIC_TYPE copy(); public ORDERED_MAP KEY_VALUE_GENERIC_TYPE copy();
@Override @Override
public ORDERED_SET KEY_GENERIC_TYPE keySet(); public ORDERED_SET KEY_GENERIC_TYPE keySet();
@Override @Override
public VALUE_ORDERED_COLLECTION VALUE_GENERIC_TYPE values();
@Override
public ObjectOrderedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> ENTRY_SET(); public ObjectOrderedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> ENTRY_SET();
@Java21
public default ORDERED_MAP KEY_VALUE_GENERIC_TYPE reversed() { return new ABSTRACT_MAP.REVERSED_ORDERED_MAPKV_BRACES(this); }
#if JAVA_VERSION>=21
@Override
default ORDERED_SET KEY_GENERIC_TYPE sequencedKeySet() { return keySet(); }
@Override
default VALUE_ORDERED_COLLECTION VALUE_GENERIC_TYPE sequencedValues() { return values(); }
@Override
default ObjectOrderedSet<Map.Entry<CLASS_TYPE, CLASS_VALUE_TYPE>> sequencedEntrySet() { return (ObjectOrderedSet<Map.Entry<CLASS_TYPE, CLASS_VALUE_TYPE>>)(Object)ENTRY_SET(); }
#endif
#if MAPS_FEATURE #if MAPS_FEATURE
/** /**
* Creates a Wrapped SortedMap that is Synchronized * Creates a Wrapped SortedMap that is Synchronized
@@ -130,6 +182,22 @@ public interface ORDERED_MAP KEY_VALUE_GENERIC_TYPE extends MAP KEY_VALUE_GENERI
@Override @Override
public default ORDERED_MAP KEY_VALUE_GENERIC_TYPE unmodifiable() { return MAPS.unmodifiable(this); } public default ORDERED_MAP KEY_VALUE_GENERIC_TYPE unmodifiable() { return MAPS.unmodifiable(this); }
#endif
#if JAVA_VERSION>=21
#if !SAME_TYPE || !TYPE_OBJECT
@Override
@Deprecated
public default CLASS_VALUE_TYPE putFirst(CLASS_TYPE k, CLASS_VALUE_TYPE v) {
return putFirst(OBJ_TO_KEY(k), OBJ_TO_VALUE(v));
}
@Override
@Deprecated
public default CLASS_VALUE_TYPE putLast(CLASS_TYPE k, CLASS_VALUE_TYPE v) {
return putLast(OBJ_TO_KEY(k), OBJ_TO_VALUE(v));
}
#endif
#endif #endif
/** /**
* Fast Ordered Entry Set that allows for a faster Entry Iterator by recycling the Entry Object and just exchanging 1 internal value * Fast Ordered Entry Set that allows for a faster Entry Iterator by recycling the Entry Object and just exchanging 1 internal value
@@ -1,46 +1,46 @@
package speiger.src.collections.PACKAGE.queues; package speiger.src.collections.PACKAGE.queues;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Objects; import java.util.Objects;
#endif #endif
import java.util.StringJoiner; import java.util.StringJoiner;
/** /**
* Helper class that implements all the essential methods for the PriorityQueues * Helper class that implements all the essential methods for the PriorityQueues
* @Type(T) * @Type(T)
*/ */
public abstract class ABSTRACT_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_QUEUE KEY_GENERIC_TYPE public abstract class ABSTRACT_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_QUEUE KEY_GENERIC_TYPE
{ {
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if(obj instanceof PRIORITY_QUEUE) { if(obj instanceof PRIORITY_QUEUE) {
PRIORITY_QUEUE KEY_GENERIC_TYPE queue = (PRIORITY_QUEUE KEY_GENERIC_TYPE)obj; PRIORITY_QUEUE KEY_GENERIC_TYPE queue = (PRIORITY_QUEUE KEY_GENERIC_TYPE)obj;
if(queue.size() != size()) return false; if(queue.size() != size()) return false;
for(int i = 0,m=size();i<m;i++) { for(int i = 0,m=size();i<m;i++) {
if(KEY_EQUALS_NOT(queue.peek(i), peek(i))) return false; if(KEY_EQUALS_NOT(queue.peek(i), peek(i))) return false;
} }
return true; return true;
} }
return false; return false;
} }
@Override @Override
public int hashCode() { public int hashCode() {
int result = 1; int result = 1;
for (int i = 0,m=size();i<m;i++) { for (int i = 0,m=size();i<m;i++) {
result = 31 * result + KEY_TO_HASH(peek(i)); result = 31 * result + KEY_TO_HASH(peek(i));
} }
return result; return result;
} }
@Override @Override
public String toString() public String toString()
{ {
if(isEmpty()) return "[]"; if(isEmpty()) return "[]";
StringJoiner joiner = new StringJoiner(", ", "[", "]"); StringJoiner joiner = new StringJoiner(", ", "[", "]");
for (int i = 0,m=size();i<m;i++) { for (int i = 0,m=size();i<m;i++) {
joiner.add(KEY_TO_STRING(peek(i))); joiner.add(KEY_TO_STRING(peek(i)));
} }
return joiner.toString(); return joiner.toString();
} }
} }
@@ -1,459 +1,523 @@
package speiger.src.collections.PACKAGE.queues; package speiger.src.collections.PACKAGE.queues;
import java.util.Arrays; import java.util.Arrays;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Comparator; import java.util.Comparator;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.BiFunction; import java.util.function.BiFunction;
#endif #endif
import java.util.Objects; import java.util.Objects;
import java.util.NoSuchElementException; #if JDK_TYPE
#if JDK_FUNCTION import java.util.OPTIONAL;
import java.util.function.PREDICATE; #if SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#endif #if !TYPE_OBJECT
import java.util.stream.JAVA_STREAM;
import speiger.src.collections.PACKAGE.collections.ITERATOR; #else
#if !TYPE_OBJECT import java.util.stream.Stream;
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import java.util.stream.Collector;
import speiger.src.collections.PACKAGE.functions.CONSUMER; #endif
#endif #endif
import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER; #endif
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; import java.util.NoSuchElementException;
#if !JDK_FUNCTION #if JDK_FUNCTION
import speiger.src.collections.PACKAGE.functions.function.PREDICATE; import java.util.function.PREDICATE;
#endif #endif
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.utils.ITrimmable; import speiger.src.collections.PACKAGE.collections.ITERATOR;
#if !JDK_TYPE
/** import speiger.src.collections.PACKAGE.functions.OPTIONAL;
* A Simple First In First Out Priority Queue that is a Good Replacement for a linked list (or ArrayDequeue) #endif
* Its specific implementation uses a backing array that grows and shrinks as it is needed. #if !TYPE_OBJECT
* @Type(T) import speiger.src.collections.PACKAGE.functions.COMPARATOR;
*/ import speiger.src.collections.PACKAGE.functions.CONSUMER;
public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_DEQUEUE KEY_GENERIC_TYPE, ITrimmable #endif
{ import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER;
/** Max Possible ArraySize without the JVM Crashing */ import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; #if !JDK_FUNCTION
/** The Minimum Capacity that is allowed */ import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
public static final int MIN_CAPACITY = 4; #endif
/** The Backing array */ import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
protected transient KEY_TYPE[] array; import speiger.src.collections.utils.ITrimmable;
/** The First Index pointer */
protected int first; /**
/** The Last Index pointer */ * A Simple First In First Out Priority Queue that is a Good Replacement for a linked list (or ArrayDequeue)
protected int last; * Its specific implementation uses a backing array that grows and shrinks as it is needed.
/** The Minimum Capacity of the Queue **/ * @Type(T)
protected int minCapacity; */
public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_DEQUEUE KEY_GENERIC_TYPE, ITrimmable
/** {
* Constructor using a initial array /** Max Possible ArraySize without the JVM Crashing */
* @param values the Array that should be used private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
*/ /** The Minimum Capacity that is allowed */
public ARRAY_FIFO_QUEUE(KEY_TYPE[] values) { public static final int MIN_CAPACITY = 4;
this(values, 0, values.length); /** The Backing array */
} protected transient KEY_TYPE[] array;
/** The First Index pointer */
/** protected int first;
* Constructor using a initial array /** The Last Index pointer */
* @param values the Array that should be used protected int last;
* @param size the amount of elements that are in the initial array /** The Minimum Capacity of the Queue **/
* @throws IllegalStateException if values is smaller then size protected int minCapacity;
*/
public ARRAY_FIFO_QUEUE(KEY_TYPE[] values, int size) { /**
this(values, 0, size); * Constructor using a initial array
} * @param values the Array that should be used
*/
/** public ARRAY_FIFO_QUEUE(KEY_TYPE[] values) {
* Constructor using a initial array this(values, 0, values.length);
* @param values the Array that should be used }
* @param offset where to begin in the initial array
* @param size the amount of elements that are in the initial array /**
* @throws IllegalStateException if values is smaller then size * Constructor using a initial array
*/ * @param values the Array that should be used
public ARRAY_FIFO_QUEUE(KEY_TYPE[] values, int offset, int size) { * @param size the amount of elements that are in the initial array
if (values.length < size) throw new IllegalArgumentException("Initial array (" + values.length + ") is smaller then the expected size (" + size + ")"); * @throws IllegalStateException if values is smaller then size
if(values.length <= 0) values = NEW_KEY_ARRAY(MIN_CAPACITY); */
else if(values.length < MIN_CAPACITY) values = Arrays.copyOf(values, MIN_CAPACITY); public ARRAY_FIFO_QUEUE(KEY_TYPE[] values, int size) {
minCapacity = MIN_CAPACITY; this(values, 0, size);
array = values; }
first = offset;
last = (offset + size) % array.length; /**
if(array.length == size) expand(); * Constructor using a initial array
} * @param values the Array that should be used
* @param offset where to begin in the initial array
/** * @param size the amount of elements that are in the initial array
* Constructor with a Min Capacity * @throws IllegalStateException if values is smaller then size
* @param capacity the initial capacity of the backing array */
* @throws IllegalStateException if the initial size is smaller 0 public ARRAY_FIFO_QUEUE(KEY_TYPE[] values, int offset, int size) {
*/ if (values.length < size) throw new IllegalArgumentException("Initial array (" + values.length + ") is smaller then the expected size (" + size + ")");
public ARRAY_FIFO_QUEUE(int capacity) { if(values.length <= 0) values = NEW_KEY_ARRAY(MIN_CAPACITY);
if (capacity < 0) throw new IllegalArgumentException("Initial capacity (" + capacity + ") is negative"); else if(values.length < MIN_CAPACITY) values = Arrays.copyOf(values, MIN_CAPACITY);
array = NEW_KEY_ARRAY(Math.max(MIN_CAPACITY, capacity+1)); minCapacity = MIN_CAPACITY;
minCapacity = array.length; array = values;
} first = offset;
last = (offset + size) % array.length;
/** if(array.length == size) expand();
* Default Construtor }
*/
public ARRAY_FIFO_QUEUE() { /**
this(MIN_CAPACITY); * Constructor with a Min Capacity
} * @param capacity the initial capacity of the backing array
* @throws IllegalStateException if the initial size is smaller 0
@Override */
public ITERATOR KEY_GENERIC_TYPE iterator() { public ARRAY_FIFO_QUEUE(int capacity) {
return new Iter(); if (capacity < 0) throw new IllegalArgumentException("Initial capacity (" + capacity + ") is negative");
} array = NEW_KEY_ARRAY(Math.max(MIN_CAPACITY, capacity+1));
minCapacity = array.length;
@Override }
public int size() {
final int apparentLength = last - first; /**
return apparentLength >= 0 ? apparentLength : array.length + apparentLength; * Default Construtor
} */
public ARRAY_FIFO_QUEUE() {
@Override this(MIN_CAPACITY);
public void clear() { }
if(first != last) {
#if TYPE_OBJECT #if JDK_TYPE && SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
Arrays.fill(array, null); #if TYPE_OBJECT
#endif /**
first = last = 0; * Creates a Collector for a ArrayFIFOQueue
} * @Type(T)
else if(first != 0) { * @return a collector
first = last = 0; */
} public static <T> Collector<T, ARRAY_FIFO_QUEUE<T>, ARRAY_FIFO_QUEUE<T>> toQueue() {
} return Collector.of(ARRAY_FIFO_QUEUE::new, ARRAY_FIFO_QUEUE::enqueue, ARRAY_FIFO_QUEUE::merge);
}
@Override
public void enqueue(KEY_TYPE e) { /**
array[last++] = e; * Collects a Stream to a ArrayFIFOQueue
if(last == array.length) last = 0; * @Type(T)
if(last == first) expand(); * @return a queue with the contents of the Stream
} */
public static <T> ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE toQueue(Stream<T> stream) {
@Override return stream.collect(ARRAY_FIFO_QUEUE::new, ARRAY_FIFO_QUEUE::enqueue, ARRAY_FIFO_QUEUE::merge);
public void enqueueFirst(KEY_TYPE e) { }
if(first == 0) first = array.length;
array[--first] = e; private ARRAY_FIFO_QUEUE<T> merge(ARRAY_FIFO_QUEUE<T> a) {
if(first == last) expand(); enqueueAll(a.toArray((T[])new Object[a.size()]));
} return this;
}
@Override
public KEY_TYPE dequeue() { #else
if(first == last) throw new NoSuchElementException(); /**
KEY_TYPE data = array[first]; * Collects a Stream to a ArrayFIFOQueue
#if TYPE_OBJECT * @return a queue with the contents of the Stream
array[first] = null; */
#endif public static ARRAY_FIFO_QUEUE toQueue(JAVA_STREAM stream) {
if(++first == array.length) first = 0; return stream.collect(ARRAY_FIFO_QUEUE::new, ARRAY_FIFO_QUEUE::enqueue, ARRAY_FIFO_QUEUE::merge);
reduce(); }
return data;
} private ARRAY_FIFO_QUEUE merge(ARRAY_FIFO_QUEUE a) {
enqueueAll(a.TO_ARRAY());
@Override return this;
public KEY_TYPE dequeueLast() { }
if(first == last) throw new NoSuchElementException();
if(last == 0) last = array.length; #endif
KEY_TYPE data = array[--last]; #endif
#if TYPE_OBJECT @Override
array[last] = null; public ITERATOR KEY_GENERIC_TYPE iterator() {
#endif return new Iter();
reduce(); }
return data;
} @Override
public int size() {
@Override final int apparentLength = last - first;
public KEY_TYPE peek(int index) { return apparentLength >= 0 ? apparentLength : array.length + apparentLength;
if(first == last || index < 0 || index >= size()) throw new NoSuchElementException(); }
index += first;
return index >= array.length ? array[index-array.length] : array[index]; @Override
} public void clear() {
if(first != last) {
@Override #if TYPE_OBJECT
public boolean removeFirst(KEY_TYPE e) { Arrays.fill(array, null);
if(first == last) return false; #endif
for(int i = 0,m=size();i<m;i++) { first = last = 0;
int index = (first + i) % array.length; }
if(e == array[index]) else if(first != 0) {
return removeIndex(index); first = last = 0;
} }
return false; }
}
@Override
@Override public void enqueue(KEY_TYPE e) {
public boolean removeLast(KEY_TYPE e) { array[last++] = e;
if(first == last) return false; if(last == array.length) last = 0;
for(int i = size()-1;i>=0;i--) { if(last == first) expand();
int index = (first + i) % array.length; }
if(e == array[index])
return removeIndex(index); @Override
} public void enqueueFirst(KEY_TYPE e) {
return false; if(first == 0) first = array.length;
} array[--first] = e;
if(first == last) expand();
protected boolean removeIndex(int index) { }
if(first >= last ? index < first && index > last : index < first || index > last) return false;
if(index == first) { @Override
#if TYPE_OBJECT public KEY_TYPE dequeue() {
array[first] = null; if(first == last) throw new NoSuchElementException();
#endif KEY_TYPE data = array[first];
first++; #if TYPE_OBJECT
} array[first] = null;
else if(index == last) { #endif
last--; if(++first == array.length) first = 0;
#if TYPE_OBJECT reduce();
array[last] = null; return data;
#endif }
}
else if(index > last) { @Override
System.arraycopy(array, first, array, first+1, (index - first)); public KEY_TYPE dequeueLast() {
#if TYPE_OBJECT if(first == last) throw new NoSuchElementException();
array[first] = null; if(last == 0) last = array.length;
#endif KEY_TYPE data = array[--last];
first = ++first % array.length; #if TYPE_OBJECT
} array[last] = null;
else if(index < first) { #endif
System.arraycopy(array, index+1, array, index, (last - index) - 1); reduce();
#if TYPE_OBJECT return data;
array[last] = null; }
#endif
if(--last < 0) last += array.length; @Override
} public KEY_TYPE peek(int index) {
else { if(first == last || index < 0 || index >= size()) throw new NoSuchElementException();
if(index - first < last - index) { index += first;
System.arraycopy(array, first, array, first+1, (index - first)); return index >= array.length ? array[index-array.length] : array[index];
#if TYPE_OBJECT }
array[first] = null;
#endif @Override
first = ++first % array.length; public boolean contains(KEY_TYPE e) {
} if(first == last) return false;
else { for(int i = 0,m=size();i<m;i++) {
System.arraycopy(array, index+1, array, index, (last - index) - 1); if(e == array[(first + i) % array.length]) return true;
#if TYPE_OBJECT }
array[last] = null; return false;
#endif }
if(--last < 0) last += array.length;
} @Override
} public boolean removeFirst(KEY_TYPE e) {
reduce(); if(first == last) return false;
return true; for(int i = 0,m=size();i<m;i++) {
} int index = (first + i) % array.length;
if(e == array[index])
@Override return removeIndex(index);
public void onChanged() {} }
return false;
@Override }
public ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE copy() {
ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE queue = new ARRAY_FIFO_QUEUEBRACES(); @Override
queue.first = first; public boolean removeLast(KEY_TYPE e) {
queue.last = last; if(first == last) return false;
queue.minCapacity = minCapacity; for(int i = size()-1;i>=0;i--) {
queue.array = Arrays.copyOf(array, array.length); int index = (first + i) % array.length;
return queue; if(e == array[index])
} return removeIndex(index);
}
@Override return false;
public COMPARATOR KEY_SUPER_GENERIC_TYPE comparator() { return null; } }
@Override protected boolean removeIndex(int index) {
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { if(first >= last ? index < first && index > last : index < first || index > last) return false;
Objects.requireNonNull(action); if(index == first) {
if(first == last) return; #if TYPE_OBJECT
for(int i = 0,m=size();i<m;i++) array[first] = null;
action.accept(array[(first + i) % array.length]); #endif
clearAndTrim(0); first++;
} }
else if(index == last) {
@Override last--;
public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) { #if TYPE_OBJECT
Objects.requireNonNull(action); array[last] = null;
if(first == last) return; #endif
for(int i = 0,m=size();i<m;i++) }
action.accept(i, array[(first + i) % array.length]); else if(index > last) {
clearAndTrim(0); System.arraycopy(array, first, array, first+1, (index - first));
} #if TYPE_OBJECT
array[first] = null;
@Override #endif
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) { first = ++first % array.length;
Objects.requireNonNull(action); }
if(first == last) return; else if(index < first) {
for(int i = 0,m=size();i<m;i++) System.arraycopy(array, index+1, array, index, (last - index) - 1);
action.accept(input, array[(first + i) % array.length]); #if TYPE_OBJECT
clearAndTrim(0); array[last] = null;
} #endif
if(--last < 0) last += array.length;
@Override }
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { else {
Objects.requireNonNull(filter); if(index - first < last - index) {
for(int i = 0,m=size();i<m;i++) { System.arraycopy(array, first, array, first+1, (index - first));
if(filter.test(array[(first + i) % array.length])) return true; #if TYPE_OBJECT
} array[first] = null;
return false; #endif
} first = ++first % array.length;
}
@Override else {
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { System.arraycopy(array, index+1, array, index, (last - index) - 1);
Objects.requireNonNull(filter); #if TYPE_OBJECT
for(int i = 0,m=size();i<m;i++) { array[last] = null;
if(filter.test(array[(first + i) % array.length])) return false; #endif
} if(--last < 0) last += array.length;
return true; }
} }
reduce();
@Override return true;
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { }
Objects.requireNonNull(filter);
for(int i = 0,m=size();i<m;i++) { @Override
if(!filter.test(array[(first + i) % array.length])) return false; public void onChanged() {}
}
return true; @Override
} public ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE copy() {
ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE queue = new ARRAY_FIFO_QUEUEBRACES();
@Override queue.first = first;
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { queue.last = last;
Objects.requireNonNull(filter); queue.minCapacity = minCapacity;
for(int i = 0,m=size();i<m;i++) { queue.array = Arrays.copyOf(array, array.length);
int index = (first + i) % array.length; return queue;
if(filter.test(array[index])) { }
KEY_TYPE data = array[index];
removeIndex(index); @Override
return data; public COMPARATOR KEY_SUPER_GENERIC_TYPE comparator() { return null; }
}
} @Override
return EMPTY_VALUE; public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
} Objects.requireNonNull(action);
if(first == last) return;
#if !TYPE_OBJECT for(int i = 0,m=size();i<m;i++)
@Override action.accept(array[(first + i) % array.length]);
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { clearAndTrim(0);
Objects.requireNonNull(operator); }
KEY_TYPE state = identity;
for(int i = 0,m=size();i<m;i++) { @Override
state = operator.APPLY_VALUE(state, array[(first + i) % array.length]); public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) {
} Objects.requireNonNull(action);
return state; if(first == last) return;
} for(int i = 0,m=size();i<m;i++)
action.accept(i, array[(first + i) % array.length]);
#else clearAndTrim(0);
@Override }
public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
Objects.requireNonNull(operator); @Override
KEY_SPECIAL_TYPE state = identity; public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
for(int i = 0,m=size();i<m;i++) { Objects.requireNonNull(action);
state = operator.APPLY_VALUE(state, array[(first + i) % array.length]); if(first == last) return;
} for(int i = 0,m=size();i<m;i++)
return state; action.accept(input, array[(first + i) % array.length]);
} clearAndTrim(0);
}
#endif
@Override @Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(operator); Objects.requireNonNull(filter);
KEY_TYPE state = EMPTY_VALUE; for(int i = 0,m=size();i<m;i++) {
boolean empty = true; if(filter.test(array[(first + i) % array.length])) return true;
for(int i = 0,m=size();i<m;i++) { }
if(empty) { return false;
empty = false; }
state = array[(first + i) % array.length];
continue; @Override
} public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
state = operator.APPLY_VALUE(state, array[(first + i) % array.length]); Objects.requireNonNull(filter);
} for(int i = 0,m=size();i<m;i++) {
return state; if(filter.test(array[(first + i) % array.length])) return false;
} }
return true;
@Override }
public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter); @Override
int result = 0; public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
for(int i = 0,m=size();i<m;i++) { Objects.requireNonNull(filter);
if(filter.test(array[(first + i) % array.length])) result++; for(int i = 0,m=size();i<m;i++) {
} if(!filter.test(array[(first + i) % array.length])) return false;
return result; }
} return true;
}
@Override
public boolean trim(int size) { @Override
int newSize = Math.max(Math.max(size, size()), minCapacity); public OPTIONAL KEY_GENERIC_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
if(newSize >= array.length) return false; Objects.requireNonNull(filter);
KEY_TYPE[] newArray = NEW_KEY_ARRAY(newSize); for(int i = 0,m=size();i<m;i++) {
if(first <= last) System.arraycopy(array, first, newArray, 0, last - first); int index = (first + i) % array.length;
else { if(filter.test(array[index])) {
System.arraycopy(array, first, newArray, 0, array.length - first); KEY_TYPE data = array[index];
System.arraycopy(array, 0, newArray, array.length - first, last); removeIndex(index);
} return OPTIONAL.GET_OPTIONAL(data);
first = 0; }
last = size(); }
array = newArray; return OPTIONAL.empty();
return true; }
}
#if !TYPE_OBJECT
/** @Override
* Trims the collection down to the requested size and clears all elements while doing so public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
* @param size the amount of elements that should be allowed Objects.requireNonNull(operator);
* @note this will enforce minimum size of the collection itself KEY_TYPE state = identity;
*/ for(int i = 0,m=size();i<m;i++) {
@Override state = operator.APPLY_VALUE(state, array[(first + i) % array.length]);
public void clearAndTrim(int size) { }
int newSize = Math.max(minCapacity, size); return state;
if(array.length <= newSize) { }
clear();
return; #else
} @Override
first = last = 0; public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
array = NEW_KEY_ARRAY(newSize); Objects.requireNonNull(operator);
} KEY_SPECIAL_TYPE state = identity;
for(int i = 0,m=size();i<m;i++) {
@Override state = operator.APPLY_VALUE(state, array[(first + i) % array.length]);
public GENERIC_SPECIAL_KEY_BRACES<E> KEY_SPECIAL_TYPE[] TO_ARRAY(KEY_SPECIAL_TYPE[] input) { }
if(input == null || input.length < size()) input = NEW_SPECIAL_KEY_ARRAY(size()); return state;
if (first <= last) System.arraycopy(array, first, input, 0, last - first); }
else {
System.arraycopy(array, first, input, 0, array.length - first); #endif
System.arraycopy(array, 0, input, array.length - first, last); @Override
} public OPTIONAL KEY_GENERIC_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
return input; Objects.requireNonNull(operator);
} KEY_TYPE state = EMPTY_VALUE;
boolean empty = true;
protected void reduce() { for(int i = 0,m=size();i<m;i++) {
final int size = size(); if(empty) {
if (array.length > minCapacity && size <= array.length / 4) resize(size, Math.max(array.length / 2, minCapacity)); empty = false;
} state = array[(first + i) % array.length];
continue;
protected void expand() { }
resize(array.length, (int)Math.min(MAX_ARRAY_SIZE, 2L * array.length)); state = operator.APPLY_VALUE(state, array[(first + i) % array.length]);
} }
return empty ? OPTIONAL.empty() : OPTIONAL.GET_OPTIONAL(state);
protected final void resize(int oldSize, int newSize) { }
KEY_TYPE[] newArray = NEW_KEY_ARRAY(newSize);
if(first >= last) { @Override
if(oldSize != 0) public int count(PREDICATE KEY_GENERIC_TYPE filter) {
{ Objects.requireNonNull(filter);
System.arraycopy(array, first, newArray, 0, array.length - first); int result = 0;
System.arraycopy(array, 0, newArray, array.length - first, last); for(int i = 0,m=size();i<m;i++) {
} if(filter.test(array[(first + i) % array.length])) result++;
} }
else System.arraycopy(array, first, newArray, 0, last-first); return result;
first = 0; }
last = oldSize;
array = newArray; @Override
} public boolean trim(int size) {
int newSize = Math.max(Math.max(size, size()), minCapacity);
private class Iter implements ITERATOR KEY_GENERIC_TYPE if(newSize >= array.length) return false;
{ KEY_TYPE[] newArray = NEW_KEY_ARRAY(newSize);
int index = first; if(first <= last) System.arraycopy(array, first, newArray, 0, last - first);
@Override else {
public boolean hasNext() System.arraycopy(array, first, newArray, 0, array.length - first);
{ System.arraycopy(array, 0, newArray, array.length - first, last);
return index != last; }
} first = 0;
last = size();
@Override array = newArray;
public KEY_TYPE NEXT() { return true;
if(!hasNext()) throw new NoSuchElementException(); }
KEY_TYPE value = array[index];
removeIndex(index); /**
index = ++index % array.length; * Trims the collection down to the requested size and clears all elements while doing so
return value; * @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) {
int newSize = Math.max(minCapacity, size);
if(array.length <= newSize) {
clear();
return;
}
first = last = 0;
array = NEW_KEY_ARRAY(newSize);
}
@Override
public GENERIC_SPECIAL_KEY_BRACES<E> KEY_SPECIAL_TYPE[] TO_ARRAY(KEY_SPECIAL_TYPE[] input) {
if(input == null || input.length < size()) input = NEW_SPECIAL_KEY_ARRAY(size());
if (first <= last) System.arraycopy(array, first, input, 0, last - first);
else {
System.arraycopy(array, first, input, 0, array.length - first);
System.arraycopy(array, 0, input, array.length - first, last);
}
return input;
}
protected void reduce() {
final int size = size();
if (array.length > minCapacity && size <= array.length / 4) resize(size, Math.max(array.length / 2, minCapacity));
}
protected void expand() {
resize(array.length, (int)Math.min(MAX_ARRAY_SIZE, 2L * array.length));
}
protected final void resize(int oldSize, int newSize) {
KEY_TYPE[] newArray = NEW_KEY_ARRAY(newSize);
if(first >= last) {
if(oldSize != 0)
{
System.arraycopy(array, first, newArray, 0, array.length - first);
System.arraycopy(array, 0, newArray, array.length - first, last);
}
}
else System.arraycopy(array, first, newArray, 0, last-first);
first = 0;
last = oldSize;
array = newArray;
}
private class Iter implements ITERATOR KEY_GENERIC_TYPE
{
int index = first;
@Override
public boolean hasNext()
{
return index != last;
}
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
KEY_TYPE value = array[index];
removeIndex(index);
index = ++index % array.length;
return value;
}
}
} }
@@ -1,440 +1,501 @@
package speiger.src.collections.PACKAGE.queues; package speiger.src.collections.PACKAGE.queues;
import java.util.Arrays; import java.util.Arrays;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Comparator; import java.util.Comparator;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.BiFunction; import java.util.function.BiFunction;
#endif #endif
import java.util.Objects; import java.util.Objects;
#if JDK_FUNCTION #if JDK_TYPE
import java.util.function.PREDICATE; import java.util.OPTIONAL;
#endif #if SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.collections.COLLECTION; import java.util.stream.JAVA_STREAM;
import speiger.src.collections.PACKAGE.collections.ITERATOR; #else
#if !TYPE_OBJECT import java.util.stream.Stream;
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import java.util.stream.Collector;
import speiger.src.collections.PACKAGE.functions.CONSUMER; #endif
#endif #endif
import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER; #endif
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; #if JDK_FUNCTION
#if !JDK_FUNCTION import java.util.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE; #endif
#endif
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.utils.ARRAYS; import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.utils.SanityChecks; #if !JDK_TYPE
import speiger.src.collections.PACKAGE.functions.OPTIONAL;
/** #endif
* A Array Priority Queue, this is a very unoptimized implementation of the PriorityQueue for very specific usecases. #if !TYPE_OBJECT
* It allows for duplicated entries and works like {@link java.util.List#indexOf(Object)} search. import speiger.src.collections.PACKAGE.functions.COMPARATOR;
* It is highly suggested to use HeapPriorityQueue otherwise, unless you know why you need this specific implementation import speiger.src.collections.PACKAGE.functions.CONSUMER;
* @Type(T) #endif
*/ import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER;
public class ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEUE KEY_GENERIC_TYPE import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
{ #if !JDK_FUNCTION
/** The Backing Array */ import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
protected transient KEY_TYPE[] array = EMPTY_KEY_ARRAY; #endif
/** The Amount of elements stored within the array */ import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
protected int size; import speiger.src.collections.PACKAGE.utils.ARRAYS;
/** The Last known first index pointer */ import speiger.src.collections.utils.SanityChecks;
protected int firstIndex = -1;
/** The Sorter of the Array */ /**
protected COMPARATOR KEY_SUPER_GENERIC_TYPE comparator; * A Array Priority Queue, this is a very unoptimized implementation of the PriorityQueue for very specific usecases.
* It allows for duplicated entries and works like {@link java.util.List#indexOf(Object)} search.
/** * It is highly suggested to use HeapPriorityQueue otherwise, unless you know why you need this specific implementation
* Default Constructor * @Type(T)
*/ */
public ARRAY_PRIORITY_QUEUE() { public class ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEUE KEY_GENERIC_TYPE
this(0, null); {
} /** The Backing Array */
protected transient KEY_TYPE[] array = EMPTY_KEY_ARRAY;
/** /** The Amount of elements stored within the array */
* Constructor using custom sorter protected int size;
* @param comp Comparator to sort the Array. Can be null /** The Last known first index pointer */
*/ protected int firstIndex = -1;
public ARRAY_PRIORITY_QUEUE(COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { /** The Sorter of the Array */
this(0, comp); protected COMPARATOR KEY_SUPER_GENERIC_TYPE comparator;
}
/**
/** * Default Constructor
* Constructor with a Min Capacity */
* @param size the initial capacity of the backing array public ARRAY_PRIORITY_QUEUE() {
* @throws IllegalStateException if the initial size is smaller 0 this(0, null);
*/ }
public ARRAY_PRIORITY_QUEUE(int size) {
this(size, null); /**
} * Constructor using custom sorter
* @param comp Comparator to sort the Array. Can be null
/** */
* Constructor with a Min Capacity and custom Sorter public ARRAY_PRIORITY_QUEUE(COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
* @param size the initial capacity of the backing array this(0, comp);
* @param comp Comparator to sort the Array. Can be null }
* @throws IllegalStateException if the initial size is smaller 0
*/ /**
public ARRAY_PRIORITY_QUEUE(int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { * Constructor with a Min Capacity
if(size < 0) throw new IllegalAccessError("Size has to be 0 or positive"); * @param size the initial capacity of the backing array
if(size > 0) array = NEW_KEY_ARRAY(size); * @throws IllegalStateException if the initial size is smaller 0
comparator = comp; */
} public ARRAY_PRIORITY_QUEUE(int size) {
this(size, null);
/** }
* Constructor using a initial array
* @param array the Array that should be used /**
*/ * Constructor with a Min Capacity and custom Sorter
public ARRAY_PRIORITY_QUEUE(KEY_TYPE[] array) { * @param size the initial capacity of the backing array
this(array, array.length); * @param comp Comparator to sort the Array. Can be null
} * @throws IllegalStateException if the initial size is smaller 0
*/
/** public ARRAY_PRIORITY_QUEUE(int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
* Constructor using a initial array if(size < 0) throw new IllegalAccessError("Size has to be 0 or positive");
* @param array the Array that should be used if(size > 0) array = NEW_KEY_ARRAY(size);
* @param size the amount of elements found within the array comparator = comp;
* @throws NegativeArraySizeException if size is smaller then 0 }
*/
public ARRAY_PRIORITY_QUEUE(KEY_TYPE[] array, int size) { /**
this.array = Arrays.copyOf(array, size); * Constructor using a initial array
this.size = size; * @param array the Array that should be used
} */
public ARRAY_PRIORITY_QUEUE(KEY_TYPE[] array) {
/** this(array, array.length);
* Constructor using a initial array and a custom sorter }
* @param array the Array that should be used
* @param comp Comparator to sort the Array. Can be null /**
*/ * Constructor using a initial array
public ARRAY_PRIORITY_QUEUE(KEY_TYPE[] array, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { * @param array the Array that should be used
this(array, array.length, comp); * @param size the amount of elements found within the array
} * @throws NegativeArraySizeException if size is smaller then 0
*/
/** public ARRAY_PRIORITY_QUEUE(KEY_TYPE[] array, int size) {
* Constructor using a initial array and a custom sorter this.array = Arrays.copyOf(array, size);
* @param array the Array that should be used this.size = size;
* @param size the amount of elements found within the array }
* @param comp Comparator to sort the Array. Can be null
* @throws NegativeArraySizeException if size is smaller then 0 /**
*/ * Constructor using a initial array and a custom sorter
public ARRAY_PRIORITY_QUEUE(KEY_TYPE[] array, int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { * @param array the Array that should be used
this.array = Arrays.copyOf(array, size); * @param comp Comparator to sort the Array. Can be null
this.size = size; */
this.comparator = comp; public ARRAY_PRIORITY_QUEUE(KEY_TYPE[] array, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
} this(array, array.length, comp);
}
/**
* Constructor using a Collection /**
* @param c the Collection that should be used * Constructor using a initial array and a custom sorter
*/ * @param array the Array that should be used
public ARRAY_PRIORITY_QUEUE(COLLECTION KEY_GENERIC_TYPE c) { * @param size the amount of elements found within the array
array = CAST_KEY_ARRAY c.TO_ARRAY(); * @param comp Comparator to sort the Array. Can be null
size = c.size(); * @throws NegativeArraySizeException if size is smaller then 0
} */
public ARRAY_PRIORITY_QUEUE(KEY_TYPE[] array, int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
/** this.array = Arrays.copyOf(array, size);
* Constructor using a Collection and a custom sorter this.size = size;
* @param c the Collection that should be used this.comparator = comp;
* @param comp Comparator to sort the Array. Can be null }
*/
public ARRAY_PRIORITY_QUEUE(COLLECTION KEY_GENERIC_TYPE c, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { /**
array = CAST_KEY_ARRAY c.TO_ARRAY(); * Constructor using a Collection
size = c.size(); * @param c the Collection that should be used
comparator = comp; */
} public ARRAY_PRIORITY_QUEUE(COLLECTION KEY_GENERIC_TYPE c) {
array = CAST_KEY_ARRAY c.TO_ARRAY();
/** size = c.size();
* Wrapping method to help serialization }
* @param array the array that should be used
* @Type(T) /**
* @return a ArrayPriorityQueue containing the original input array * Constructor using a Collection and a custom sorter
*/ * @param c the Collection that should be used
public static GENERIC_KEY_BRACES ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE wrap(KEY_TYPE[] array) { * @param comp Comparator to sort the Array. Can be null
return wrap(array, array.length); */
} public ARRAY_PRIORITY_QUEUE(COLLECTION KEY_GENERIC_TYPE c, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
array = CAST_KEY_ARRAY c.TO_ARRAY();
/** size = c.size();
* Wrapping method to help serialization comparator = comp;
* @param array the array that should be used }
* @param size the amount of elements within the array
* @Type(T) /**
* @return a ArrayPriorityQueue containing the original input array * Wrapping method to help serialization
*/ * @param array the array that should be used
public static GENERIC_KEY_BRACES ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE wrap(KEY_TYPE[] array, int size) { * @Type(T)
ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE queue = new ARRAY_PRIORITY_QUEUEBRACES(); * @return a ArrayPriorityQueue containing the original input array
queue.array = array; */
queue.size = size; public static GENERIC_KEY_BRACES ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE wrap(KEY_TYPE[] array) {
return queue; return wrap(array, array.length);
} }
/** /**
* Wrapping method to help serialization, using a custom sorter * Wrapping method to help serialization
* @param array the array that should be used * @param array the array that should be used
* @param comp Comparator to sort the Array. Can be null * @param size the amount of elements within the array
* @Type(T) * @Type(T)
* @return a ArrayPriorityQueue containing the original input array * @return a ArrayPriorityQueue containing the original input array
*/ */
public static GENERIC_KEY_BRACES ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE wrap(KEY_TYPE[] array, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { public static GENERIC_KEY_BRACES ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE wrap(KEY_TYPE[] array, int size) {
return wrap(array, array.length, comp); ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE queue = new ARRAY_PRIORITY_QUEUEBRACES();
} queue.array = array;
queue.size = size;
/** return queue;
* Wrapping method to help serialization, using a custom sorter }
* @param array the array that should be used
* @param size the amount of elements within the array /**
* @param comp Comparator to sort the Array. Can be null * Wrapping method to help serialization, using a custom sorter
* @Type(T) * @param array the array that should be used
* @return a ArrayPriorityQueue containing the original input array * @param comp Comparator to sort the Array. Can be null
*/ * @Type(T)
public static GENERIC_KEY_BRACES ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE wrap(KEY_TYPE[] array, int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { * @return a ArrayPriorityQueue containing the original input array
ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE queue = new ARRAY_PRIORITY_QUEUEBRACES(comp); */
queue.array = array; public static GENERIC_KEY_BRACES ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE wrap(KEY_TYPE[] array, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
queue.size = size; return wrap(array, array.length, comp);
return queue; }
}
/**
@Override * Wrapping method to help serialization, using a custom sorter
public void enqueue(KEY_TYPE e) { * @param array the array that should be used
if(size == array.length) array = Arrays.copyOf(array, (int)Math.max(Math.min((long)array.length + (long)(array.length >> 1), (long)SanityChecks.MAX_ARRAY_SIZE), size+1)); * @param size the amount of elements within the array
if(firstIndex != -1){ * @param comp Comparator to sort the Array. Can be null
int compare = comparator == null ? COMPAREABLE_TO_KEY(e, array[firstIndex]) : comparator.compare(e, array[firstIndex]); * @Type(T)
if(compare < 0) firstIndex = size; * @return a ArrayPriorityQueue containing the original input array
else if(compare > 0) firstIndex = -1; */
} public static GENERIC_KEY_BRACES ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE wrap(KEY_TYPE[] array, int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
array[size++] = e; ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE queue = new ARRAY_PRIORITY_QUEUEBRACES(comp);
} queue.array = array;
queue.size = size;
@Override return queue;
public KEY_TYPE dequeue() { }
if(size <= 0) throw new NoSuchElementException(); #if JDK_TYPE && SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
int index = findFirstIndex(); #if TYPE_OBJECT
KEY_TYPE value = array[index]; /**
if(index != --size) System.arraycopy(array, index+1, array, index, size - index); * Creates a Collector for a ArrayPriorityQueue
#if TYPE_OBJECT * @Type(T)
array[size] = null; * @return a collector
#endif */
firstIndex = -1; public static <T> Collector<T, ARRAY_PRIORITY_QUEUE<T>, ARRAY_PRIORITY_QUEUE<T>> toQueue() {
return value; return Collector.of(ARRAY_PRIORITY_QUEUE::new, ARRAY_PRIORITY_QUEUE::enqueue, ARRAY_PRIORITY_QUEUE::merge);
} }
@Override /**
public KEY_TYPE first() { * Collects a Stream to a ArrayPriorityQueue
if(isEmpty()) throw new NoSuchElementException(); * @Type(T)
if(firstIndex == -1) findFirstIndex(); * @return a queue with the contents of the Stream
return array[firstIndex]; */
} public static <T> ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE toQueue(Stream<T> stream) {
return stream.collect(ARRAY_PRIORITY_QUEUE::new, ARRAY_PRIORITY_QUEUE::enqueue, ARRAY_PRIORITY_QUEUE::merge);
@Override }
public KEY_TYPE peek(int index) {
if(index < 0 || index >= size) throw new NoSuchElementException(); private ARRAY_PRIORITY_QUEUE<T> merge(ARRAY_PRIORITY_QUEUE<T> a) {
return array[index]; enqueueAll(a.toArray((T[])new Object[a.size()]));
} return this;
}
@Override
public boolean removeFirst(KEY_TYPE e) { #else
for(int i = 0;i<size;i++) /**
if(KEY_EQUALS(e, array[i])) return removeIndex(i); * Collects a Stream to a ArrayPriorityQueue
return false; * @return a queue with the contents of the Stream
} */
public static ARRAY_PRIORITY_QUEUE toQueue(JAVA_STREAM stream) {
@Override return stream.collect(ARRAY_PRIORITY_QUEUE::new, ARRAY_PRIORITY_QUEUE::enqueue, ARRAY_PRIORITY_QUEUE::merge);
public boolean removeLast(KEY_TYPE e) { }
for(int i = size-1;i>=0;i--)
if(KEY_EQUALS(e, array[i])) return removeIndex(i); private ARRAY_PRIORITY_QUEUE merge(ARRAY_PRIORITY_QUEUE a) {
return false; enqueueAll(a.TO_ARRAY());
} return this;
}
protected boolean removeIndex(int index) {
if(index != --size) System.arraycopy(array, index+1, array, index, size - index); #endif
#if TYPE_OBJECT #endif
array[size] = null; @Override
#endif public void enqueue(KEY_TYPE e) {
if(index == firstIndex) firstIndex = -1; if(size == array.length) array = Arrays.copyOf(array, (int)Math.max(Math.min((long)array.length + (long)(array.length >> 1), (long)SanityChecks.MAX_ARRAY_SIZE), size+1));
else if(firstIndex != -1 && index >= firstIndex) firstIndex--; if(firstIndex != -1){
return true; int compare = comparator == null ? COMPAREABLE_TO_KEY(e, array[firstIndex]) : comparator.compare(e, array[firstIndex]);
} if(compare < 0) firstIndex = size;
else if(compare > 0) firstIndex = -1;
@Override }
public void onChanged() { array[size++] = e;
firstIndex = -1; }
}
@Override
@Override public KEY_TYPE dequeue() {
public int size() { if(size <= 0) throw new NoSuchElementException();
return size; int index = findFirstIndex();
} KEY_TYPE value = array[index];
if(index != --size) System.arraycopy(array, index+1, array, index, size - index);
@Override #if TYPE_OBJECT
public void clear() { array[size] = null;
#if TYPE_OBJECT #endif
Arrays.fill(array, null); firstIndex = -1;
#endif return value;
size = 0; }
}
@Override
@Override public KEY_TYPE first() {
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { if(isEmpty()) throw new NoSuchElementException();
Objects.requireNonNull(action); if(firstIndex == -1) findFirstIndex();
for(int i = 0,m=size;i<m;i++) action.accept(dequeue()); return array[firstIndex];
} }
@Override @Override
public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) { public KEY_TYPE peek(int index) {
Objects.requireNonNull(action); if(index < 0 || index >= size) throw new NoSuchElementException();
for(int i = 0,m=size;i<m;i++) action.accept(i, dequeue()); return array[index];
} }
@Override @Override
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) { public boolean contains(KEY_TYPE e) {
Objects.requireNonNull(action); for(int i = 0;i<size;i++)
for(int i = 0,m=size;i<m;i++) action.accept(input, dequeue()); if(KEY_EQUALS(e, array[i])) return true;
} return false;
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { @Override
Objects.requireNonNull(filter); public boolean removeFirst(KEY_TYPE e) {
for(int i = 0;i<size;i++) { for(int i = 0;i<size;i++)
if(filter.test(array[i])) return true; if(KEY_EQUALS(e, array[i])) return removeIndex(i);
} return false;
return false; }
}
@Override
@Override public boolean removeLast(KEY_TYPE e) {
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { for(int i = size-1;i>=0;i--)
Objects.requireNonNull(filter); if(KEY_EQUALS(e, array[i])) return removeIndex(i);
for(int i = 0;i<size;i++) { return false;
if(filter.test(array[i])) return false; }
}
return true; protected boolean removeIndex(int index) {
} if(index != --size) System.arraycopy(array, index+1, array, index, size - index);
#if TYPE_OBJECT
@Override array[size] = null;
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { #endif
Objects.requireNonNull(filter); if(index == firstIndex) firstIndex = -1;
for(int i = 0;i<size;i++) { else if(firstIndex != -1 && index >= firstIndex) firstIndex--;
if(!filter.test(array[i])) return false; return true;
} }
return true;
} @Override
public void onChanged() {
#if !TYPE_OBJECT firstIndex = -1;
@Override }
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator); @Override
KEY_TYPE state = identity; public int size() {
for(int i = 0;i<size;i++) { return size;
state = operator.APPLY_VALUE(state, array[i]); }
}
return state; @Override
} public void clear() {
#if TYPE_OBJECT
#else Arrays.fill(array, null);
@Override #endif
public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) { size = 0;
Objects.requireNonNull(operator); }
KEY_SPECIAL_TYPE state = identity;
for(int i = 0;i<size;i++) { @Override
state = operator.APPLY_VALUE(state, array[i]); public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
} Objects.requireNonNull(action);
return state; for(int i = 0,m=size;i<m;i++) action.accept(dequeue());
} }
#endif @Override
@Override public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) {
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { Objects.requireNonNull(action);
Objects.requireNonNull(operator); for(int i = 0,m=size;i<m;i++) action.accept(i, dequeue());
KEY_TYPE state = EMPTY_VALUE; }
boolean empty = true;
for(int i = 0;i<size;i++) { @Override
if(empty) { public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
empty = false; Objects.requireNonNull(action);
state = array[i]; for(int i = 0,m=size;i<m;i++) action.accept(input, dequeue());
continue; }
}
state = operator.APPLY_VALUE(state, array[i]); @Override
} public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
return state; Objects.requireNonNull(filter);
} for(int i = 0;i<size;i++) {
if(filter.test(array[i])) return true;
@Override }
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { return false;
Objects.requireNonNull(filter); }
for(int i = 0;i<size;i++) {
if(filter.test(array[i])) { @Override
KEY_TYPE data = array[i]; public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
removeIndex(i); Objects.requireNonNull(filter);
return data; for(int i = 0;i<size;i++) {
} if(filter.test(array[i])) return false;
} }
return EMPTY_VALUE; return true;
} }
@Override @Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) { public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter); Objects.requireNonNull(filter);
int result = 0; for(int i = 0;i<size;i++) {
for(int i = 0;i<size;i++) { if(!filter.test(array[i])) return false;
if(filter.test(array[i])) result++; }
} return true;
return result; }
}
#if !TYPE_OBJECT
@Override @Override
public ITERATOR KEY_GENERIC_TYPE iterator() { public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
return new Iter(); Objects.requireNonNull(operator);
} KEY_TYPE state = identity;
for(int i = 0;i<size;i++) {
@Override state = operator.APPLY_VALUE(state, array[i]);
public ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE copy() { }
ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE queue = new ARRAY_PRIORITY_QUEUEBRACES(); return state;
queue.firstIndex = firstIndex; }
queue.size = size;
queue.comparator = comparator; #else
queue.array = Arrays.copyOf(array, array.length); @Override
return queue; public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
} Objects.requireNonNull(operator);
KEY_SPECIAL_TYPE state = identity;
@Override for(int i = 0;i<size;i++) {
public COMPARATOR KEY_SUPER_GENERIC_TYPE comparator() { state = operator.APPLY_VALUE(state, array[i]);
return comparator; }
} return state;
}
@Override
public GENERIC_SPECIAL_KEY_BRACES<E> KEY_SPECIAL_TYPE[] TO_ARRAY(KEY_SPECIAL_TYPE[] input) { #endif
if(input == null || input.length < size()) input = NEW_SPECIAL_KEY_ARRAY(size()); @Override
System.arraycopy(array, 0, input, 0, size()); public OPTIONAL KEY_GENERIC_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
return input; Objects.requireNonNull(operator);
} KEY_TYPE state = EMPTY_VALUE;
boolean empty = true;
protected int findFirstIndex() { for(int i = 0;i<size;i++) {
if(firstIndex == -1) { if(empty) {
int index = size-1; empty = false;
KEY_TYPE value = array[index]; state = array[i];
if(comparator == null) { continue;
for(int i = index;i>=0;i--) { }
if(COMPAREABLE_TO_KEY(array[i], value) < 0) state = operator.APPLY_VALUE(state, array[i]);
value = array[index = i]; }
} return empty ? OPTIONAL.empty() : OPTIONAL.GET_OPTIONAL(state);
} }
else {
for(int i = index;i>=0;i--) { @Override
if(comparator.compare(array[i], value) < 0) public OPTIONAL KEY_GENERIC_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
value = array[index = i]; Objects.requireNonNull(filter);
} for(int i = 0;i<size;i++) {
} if(filter.test(array[i])) {
firstIndex = index; KEY_TYPE data = array[i];
} removeIndex(i);
return firstIndex; return OPTIONAL.GET_OPTIONAL(data);
} }
}
private class Iter implements ITERATOR KEY_GENERIC_TYPE { return OPTIONAL.empty();
@Override }
public boolean hasNext() {
return !isEmpty(); @Override
} public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
@Override int result = 0;
public KEY_TYPE NEXT() { for(int i = 0;i<size;i++) {
if(!hasNext()) throw new NoSuchElementException(); if(filter.test(array[i])) result++;
return dequeue(); }
} return result;
} }
@Override
public ITERATOR KEY_GENERIC_TYPE iterator() {
return new Iter();
}
@Override
public ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE copy() {
ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE queue = new ARRAY_PRIORITY_QUEUEBRACES();
queue.firstIndex = firstIndex;
queue.size = size;
queue.comparator = comparator;
queue.array = Arrays.copyOf(array, array.length);
return queue;
}
@Override
public COMPARATOR KEY_SUPER_GENERIC_TYPE comparator() {
return comparator;
}
@Override
public GENERIC_SPECIAL_KEY_BRACES<E> KEY_SPECIAL_TYPE[] TO_ARRAY(KEY_SPECIAL_TYPE[] input) {
if(input == null || input.length < size()) input = NEW_SPECIAL_KEY_ARRAY(size());
System.arraycopy(array, 0, input, 0, size());
return input;
}
protected int findFirstIndex() {
if(firstIndex == -1) {
int index = size-1;
KEY_TYPE value = array[index];
if(comparator == null) {
for(int i = index;i>=0;i--) {
if(COMPAREABLE_TO_KEY(array[i], value) < 0)
value = array[index = i];
}
}
else {
for(int i = index;i>=0;i--) {
if(comparator.compare(array[i], value) < 0)
value = array[index = i];
}
}
firstIndex = index;
}
return firstIndex;
}
private class Iter implements ITERATOR KEY_GENERIC_TYPE {
@Override
public boolean hasNext() {
return !isEmpty();
}
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
return dequeue();
}
}
} }
@@ -1,408 +1,470 @@
package speiger.src.collections.PACKAGE.queues; package speiger.src.collections.PACKAGE.queues;
import java.util.Arrays; import java.util.Arrays;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Comparator; import java.util.Comparator;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.BiFunction; import java.util.function.BiFunction;
#endif #endif
import java.util.Objects; import java.util.Objects;
#if JDK_FUNCTION #if JDK_TYPE
import java.util.function.PREDICATE; import java.util.OPTIONAL;
#endif #if SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.collections.COLLECTION; import java.util.stream.JAVA_STREAM;
import speiger.src.collections.PACKAGE.collections.ITERATOR; #else
#if !TYPE_OBJECT import java.util.stream.Stream;
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import java.util.stream.Collector;
import speiger.src.collections.PACKAGE.functions.CONSUMER; #endif
#endif #endif
import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER; #endif
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; #if JDK_FUNCTION
#if !JDK_FUNCTION import java.util.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE; #endif
#endif
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.utils.ARRAYS; import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.utils.SanityChecks; #if !JDK_TYPE
import speiger.src.collections.PACKAGE.functions.OPTIONAL;
/** #endif
* A Simple Heap base Priority Queue implementation #if !TYPE_OBJECT
* It is a ArrayBased Alternative to TreeSets that has less object allocations import speiger.src.collections.PACKAGE.functions.COMPARATOR;
* @Type(T) import speiger.src.collections.PACKAGE.functions.CONSUMER;
*/ #endif
public class HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEUE KEY_GENERIC_TYPE import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER;
{ import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
/** The Backing Array */ #if !JDK_FUNCTION
protected transient KEY_TYPE[] array = EMPTY_KEY_ARRAY; import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
/** The Amount of elements stored within the array */ #endif
protected int size; import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
/** The Sorter of the Array */ import speiger.src.collections.PACKAGE.utils.ARRAYS;
protected COMPARATOR KEY_SUPER_GENERIC_TYPE comparator; import speiger.src.collections.utils.SanityChecks;
/** /**
* Default Constructor * A Simple Heap base Priority Queue implementation
*/ * It is a ArrayBased Alternative to TreeSets that has less object allocations
public HEAP_PRIORITY_QUEUE() { * @Type(T)
this(0, null); */
} public class HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEUE KEY_GENERIC_TYPE
{
/** /** The Backing Array */
* Constructor using custom sorter protected transient KEY_TYPE[] array = EMPTY_KEY_ARRAY;
* @param comp Comparator to sort the Array. Can be null /** The Amount of elements stored within the array */
*/ protected int size;
public HEAP_PRIORITY_QUEUE(COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { /** The Sorter of the Array */
this(0, comp); protected COMPARATOR KEY_SUPER_GENERIC_TYPE comparator;
}
/**
/** * Default Constructor
* Constructor with a Min Capacity */
* @param size the initial capacity of the backing array public HEAP_PRIORITY_QUEUE() {
* @throws IllegalStateException if the initial size is smaller 0 this(0, null);
*/ }
public HEAP_PRIORITY_QUEUE(int size) {
this(size, null); /**
} * Constructor using custom sorter
* @param comp Comparator to sort the Array. Can be null
/** */
* Constructor with a Min Capacity and custom Sorter public HEAP_PRIORITY_QUEUE(COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
* @param size the initial capacity of the backing array this(0, comp);
* @param comp Comparator to sort the Array. Can be null }
* @throws IllegalStateException if the initial size is smaller 0
*/ /**
public HEAP_PRIORITY_QUEUE(int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { * Constructor with a Min Capacity
if(size > 0) array = NEW_KEY_ARRAY(size); * @param size the initial capacity of the backing array
comparator = comp; * @throws IllegalStateException if the initial size is smaller 0
} */
public HEAP_PRIORITY_QUEUE(int size) {
/** this(size, null);
* Constructor using a initial array }
* @param array the Array that should be used
*/ /**
public HEAP_PRIORITY_QUEUE(KEY_TYPE[] array) { * Constructor with a Min Capacity and custom Sorter
this(array, array.length); * @param size the initial capacity of the backing array
} * @param comp Comparator to sort the Array. Can be null
* @throws IllegalStateException if the initial size is smaller 0
/** */
* Constructor using a initial array public HEAP_PRIORITY_QUEUE(int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
* @param array the Array that should be used if(size > 0) array = NEW_KEY_ARRAY(size);
* @param size the amount of elements found within the array comparator = comp;
* @throws NegativeArraySizeException if size is smaller then 0 }
*/
public HEAP_PRIORITY_QUEUE(KEY_TYPE[] array, int size) { /**
this.array = Arrays.copyOf(array, size); * Constructor using a initial array
this.size = size; * @param array the Array that should be used
ARRAYS.heapify(array, size, null); */
} public HEAP_PRIORITY_QUEUE(KEY_TYPE[] array) {
this(array, array.length);
/** }
* Constructor using a initial array and a custom sorter
* @param array the Array that should be used /**
* @param comp Comparator to sort the Array. Can be null * Constructor using a initial array
*/ * @param array the Array that should be used
public HEAP_PRIORITY_QUEUE(KEY_TYPE[] array, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { * @param size the amount of elements found within the array
this(array, array.length, comp); * @throws NegativeArraySizeException if size is smaller then 0
} */
public HEAP_PRIORITY_QUEUE(KEY_TYPE[] array, int size) {
/** this.array = Arrays.copyOf(array, size);
* Constructor using a initial array and a custom sorter this.size = size;
* @param array the Array that should be used ARRAYS.heapify(array, size, null);
* @param size the amount of elements found within the array }
* @param comp Comparator to sort the Array. Can be null
* @throws NegativeArraySizeException if size is smaller then 0 /**
*/ * Constructor using a initial array and a custom sorter
public HEAP_PRIORITY_QUEUE(KEY_TYPE[] array, int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { * @param array the Array that should be used
this.array = Arrays.copyOf(array, size); * @param comp Comparator to sort the Array. Can be null
this.size = size; */
comparator = comp; public HEAP_PRIORITY_QUEUE(KEY_TYPE[] array, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
ARRAYS.heapify(array, size, comp); this(array, array.length, comp);
} }
/** /**
* Constructor using a Collection * Constructor using a initial array and a custom sorter
* @param c the Collection that should be used * @param array the Array that should be used
*/ * @param size the amount of elements found within the array
public HEAP_PRIORITY_QUEUE(COLLECTION KEY_GENERIC_TYPE c) { * @param comp Comparator to sort the Array. Can be null
array = CAST_KEY_ARRAY c.TO_ARRAY(); * @throws NegativeArraySizeException if size is smaller then 0
size = c.size(); */
ARRAYS.heapify(array, size, null); public HEAP_PRIORITY_QUEUE(KEY_TYPE[] array, int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
} this.array = Arrays.copyOf(array, size);
this.size = size;
/** comparator = comp;
* Constructor using a Collection and a custom sorter ARRAYS.heapify(array, size, comp);
* @param c the Collection that should be used }
* @param comp Comparator to sort the Array. Can be null
*/ /**
public HEAP_PRIORITY_QUEUE(COLLECTION KEY_GENERIC_TYPE c, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { * Constructor using a Collection
array = CAST_KEY_ARRAY c.TO_ARRAY(); * @param c the Collection that should be used
size = c.size(); */
comparator = comp; public HEAP_PRIORITY_QUEUE(COLLECTION KEY_GENERIC_TYPE c) {
ARRAYS.heapify(array, size, comp); array = CAST_KEY_ARRAY c.TO_ARRAY();
} size = c.size();
ARRAYS.heapify(array, size, null);
/** }
* Wrapping method to help serialization
* @param array the array that should be used /**
* @Type(T) * Constructor using a Collection and a custom sorter
* @return a HeapPriorityQueue containing the original input array * @param c the Collection that should be used
*/ * @param comp Comparator to sort the Array. Can be null
public static GENERIC_KEY_BRACES HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE wrap(KEY_TYPE[] array) { */
return wrap(array, array.length); public HEAP_PRIORITY_QUEUE(COLLECTION KEY_GENERIC_TYPE c, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
} array = CAST_KEY_ARRAY c.TO_ARRAY();
size = c.size();
/** comparator = comp;
* Wrapping method to help serialization ARRAYS.heapify(array, size, comp);
* @param array the array that should be used }
* @param size the amount of elements within the array
* @Type(T) /**
* @return a HeapPriorityQueue containing the original input array * Wrapping method to help serialization
*/ * @param array the array that should be used
public static GENERIC_KEY_BRACES HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE wrap(KEY_TYPE[] array, int size) { * @Type(T)
HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE queue = new HEAP_PRIORITY_QUEUEBRACES(); * @return a HeapPriorityQueue containing the original input array
queue.array = array; */
queue.size = size; public static GENERIC_KEY_BRACES HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE wrap(KEY_TYPE[] array) {
ARRAYS.heapify(array, size, null); return wrap(array, array.length);
return queue; }
}
/**
/** * Wrapping method to help serialization
* Wrapping method to help serialization, using a custom sorter * @param array the array that should be used
* @param array the array that should be used * @param size the amount of elements within the array
* @param comp Comparator to sort the Array. Can be null * @Type(T)
* @Type(T) * @return a HeapPriorityQueue containing the original input array
* @return a HeapPriorityQueue containing the original input array */
*/ public static GENERIC_KEY_BRACES HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE wrap(KEY_TYPE[] array, int size) {
public static GENERIC_KEY_BRACES HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE wrap(KEY_TYPE[] array, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE queue = new HEAP_PRIORITY_QUEUEBRACES();
return wrap(array, array.length, comp); queue.array = array;
} queue.size = size;
ARRAYS.heapify(array, size, null);
/** return queue;
* Wrapping method to help serialization, using a custom sorter }
* @param array the array that should be used
* @param size the amount of elements within the array /**
* @param comp Comparator to sort the Array. Can be null * Wrapping method to help serialization, using a custom sorter
* @Type(T) * @param array the array that should be used
* @return a HeapPriorityQueue containing the original input array * @param comp Comparator to sort the Array. Can be null
*/ * @Type(T)
public static GENERIC_KEY_BRACES HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE wrap(KEY_TYPE[] array, int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { * @return a HeapPriorityQueue containing the original input array
HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE queue = new HEAP_PRIORITY_QUEUEBRACES(comp); */
queue.array = array; public static GENERIC_KEY_BRACES HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE wrap(KEY_TYPE[] array, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
queue.size = size; return wrap(array, array.length, comp);
ARRAYS.heapify(array, size, comp); }
return queue;
} /**
* Wrapping method to help serialization, using a custom sorter
@Override * @param array the array that should be used
public int size() { * @param size the amount of elements within the array
return size; * @param comp Comparator to sort the Array. Can be null
} * @Type(T)
* @return a HeapPriorityQueue containing the original input array
@Override */
public void clear() { public static GENERIC_KEY_BRACES HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE wrap(KEY_TYPE[] array, int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
#if TYPE_OBJECT HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE queue = new HEAP_PRIORITY_QUEUEBRACES(comp);
Arrays.fill(array, null); queue.array = array;
#endif queue.size = size;
size = 0; ARRAYS.heapify(array, size, comp);
} return queue;
}
@Override
public ITERATOR KEY_GENERIC_TYPE iterator() { #if JDK_TYPE && SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
return new Iter(); #if TYPE_OBJECT
} /**
* Creates a Collector for a ArrayFIFOQueue
@Override * @Type(T)
public void enqueue(KEY_TYPE e) { * @return a collector
if(size == array.length) array = Arrays.copyOf(array, (int)Math.max(Math.min((long)array.length + (long)(array.length >> 1), (long)SanityChecks.MAX_ARRAY_SIZE), size+1)); */
array[size++] = e; public static <T> Collector<T, HEAP_PRIORITY_QUEUE<T>, HEAP_PRIORITY_QUEUE<T>> toQueue() {
ARRAYS.shiftUp(array, size-1, comparator); return Collector.of(HEAP_PRIORITY_QUEUE::new, HEAP_PRIORITY_QUEUE::enqueue, HEAP_PRIORITY_QUEUE::merge);
} }
@Override /**
public KEY_TYPE dequeue() { * Collects a Stream to a ArrayFIFOQueue
if(size <= 0) throw new NoSuchElementException(); * @Type(T)
KEY_TYPE value = array[0]; * @return a queue with the contents of the Stream
array[0] = array[--size]; */
#if TYPE_OBJECT public static <T> HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE toQueue(Stream<T> stream) {
array[size] = null; return stream.collect(HEAP_PRIORITY_QUEUE::new, HEAP_PRIORITY_QUEUE::enqueue, HEAP_PRIORITY_QUEUE::merge);
#endif }
if(size != 0) ARRAYS.shiftDown(array, size, 0, comparator);
return value; private HEAP_PRIORITY_QUEUE<T> merge(HEAP_PRIORITY_QUEUE<T> a) {
} enqueueAll(a.toArray((T[])new Object[a.size()]));
return this;
@Override }
public KEY_TYPE peek(int index) {
if(index < 0 || index >= size) throw new NoSuchElementException(); #else
return array[index]; /**
} * Collects a Stream to a ArrayFIFOQueue
* @return a queue with the contents of the Stream
@Override */
public boolean removeFirst(KEY_TYPE e) { public static HEAP_PRIORITY_QUEUE toQueue(JAVA_STREAM stream) {
for(int i = 0;i<size;i++) return stream.collect(HEAP_PRIORITY_QUEUE::new, HEAP_PRIORITY_QUEUE::enqueue, HEAP_PRIORITY_QUEUE::merge);
if(KEY_EQUALS(e, array[i])) return removeIndex(i); }
return false;
} private HEAP_PRIORITY_QUEUE merge(HEAP_PRIORITY_QUEUE a) {
enqueueAll(a.TO_ARRAY());
@Override return this;
public boolean removeLast(KEY_TYPE e) { }
for(int i = size-1;i>=0;i--)
if(KEY_EQUALS(e, array[i])) return removeIndex(i); #endif
return false; #endif
} @Override
public int size() {
@Override return size;
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { }
Objects.requireNonNull(action);
for(int i = 0,m=size;i<m;i++) action.accept(dequeue()); @Override
} public void clear() {
#if TYPE_OBJECT
@Override Arrays.fill(array, null);
public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) { #endif
Objects.requireNonNull(action); size = 0;
for(int i = 0,m=size;i<m;i++) action.accept(i, dequeue()); }
}
@Override
@Override public ITERATOR KEY_GENERIC_TYPE iterator() {
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) { return new Iter();
Objects.requireNonNull(action); }
for(int i = 0,m=size;i<m;i++) action.accept(input, dequeue());
} @Override
public void enqueue(KEY_TYPE e) {
@Override if(size == array.length) array = Arrays.copyOf(array, (int)Math.max(Math.min((long)array.length + (long)(array.length >> 1), (long)SanityChecks.MAX_ARRAY_SIZE), size+1));
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { array[size++] = e;
Objects.requireNonNull(filter); ARRAYS.shiftUp(array, size-1, comparator);
for(int i = 0;i<size;i++) { }
if(filter.test(array[i])) return true;
} @Override
return false; public KEY_TYPE dequeue() {
} if(size <= 0) throw new NoSuchElementException();
KEY_TYPE value = array[0];
@Override array[0] = array[--size];
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { #if TYPE_OBJECT
Objects.requireNonNull(filter); array[size] = null;
for(int i = 0;i<size;i++) { #endif
if(filter.test(array[i])) return false; if(size != 0) ARRAYS.shiftDown(array, size, 0, comparator);
} return value;
return true; }
}
@Override
@Override public KEY_TYPE peek(int index) {
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { if(index < 0 || index >= size) throw new NoSuchElementException();
Objects.requireNonNull(filter); return array[index];
for(int i = 0;i<size;i++) { }
if(!filter.test(array[i])) return false;
} @Override
return true; public boolean contains(KEY_TYPE e) {
} for(int i = 0;i<size;i++)
if(KEY_EQUALS(e, array[i])) return true;
#if !TYPE_OBJECT return false;
@Override }
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator); @Override
KEY_TYPE state = identity; public boolean removeFirst(KEY_TYPE e) {
for(int i = 0;i<size;i++) { for(int i = 0;i<size;i++)
state = operator.APPLY_VALUE(state, array[i]); if(KEY_EQUALS(e, array[i])) return removeIndex(i);
} return false;
return state; }
}
@Override
#else public boolean removeLast(KEY_TYPE e) {
@Override for(int i = size-1;i>=0;i--)
public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) { if(KEY_EQUALS(e, array[i])) return removeIndex(i);
Objects.requireNonNull(operator); return false;
KEY_SPECIAL_TYPE state = identity; }
for(int i = 0;i<size;i++) {
state = operator.APPLY_VALUE(state, array[i]); @Override
} public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
return state; Objects.requireNonNull(action);
} for(int i = 0,m=size;i<m;i++) action.accept(dequeue());
}
#endif
@Override @Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) {
Objects.requireNonNull(operator); Objects.requireNonNull(action);
KEY_TYPE state = EMPTY_VALUE; for(int i = 0,m=size;i<m;i++) action.accept(i, dequeue());
boolean empty = true; }
for(int i = 0;i<size;i++) {
if(empty) { @Override
empty = false; public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
state = array[i]; Objects.requireNonNull(action);
continue; for(int i = 0,m=size;i<m;i++) action.accept(input, dequeue());
} }
state = operator.APPLY_VALUE(state, array[i]);
} @Override
return state; public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
} Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
@Override if(filter.test(array[i])) return true;
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { }
Objects.requireNonNull(filter); return false;
for(int i = 0;i<size;i++) { }
if(filter.test(array[i])) {
KEY_TYPE data = array[i]; @Override
removeIndex(i); public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
return data; Objects.requireNonNull(filter);
} for(int i = 0;i<size;i++) {
} if(filter.test(array[i])) return false;
return EMPTY_VALUE; }
} return true;
}
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) { @Override
Objects.requireNonNull(filter); public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
int result = 0; Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) { for(int i = 0;i<size;i++) {
if(filter.test(array[i])) result++; if(!filter.test(array[i])) return false;
} }
return result; return true;
} }
protected boolean removeIndex(int index) { #if !TYPE_OBJECT
array[index] = array[--size]; @Override
#if TYPE_OBJECT public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
array[size] = null; Objects.requireNonNull(operator);
#endif KEY_TYPE state = identity;
if(size != index) ARRAYS.shiftDown(array, size, index, comparator); for(int i = 0;i<size;i++) {
return true; state = operator.APPLY_VALUE(state, array[i]);
} }
return state;
@Override }
public void onChanged() {
if(size <= 0) return; #else
ARRAYS.shiftDown(array, size, 0, comparator); @Override
} public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
Objects.requireNonNull(operator);
@Override KEY_SPECIAL_TYPE state = identity;
public HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE copy() { for(int i = 0;i<size;i++) {
HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE queue = new HEAP_PRIORITY_QUEUEBRACES(); state = operator.APPLY_VALUE(state, array[i]);
queue.size = size; }
queue.comparator = comparator; return state;
queue.array = Arrays.copyOf(array, array.length); }
return queue;
} #endif
@Override
@Override public OPTIONAL KEY_GENERIC_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
public COMPARATOR KEY_SUPER_GENERIC_TYPE comparator() { Objects.requireNonNull(operator);
return comparator; KEY_TYPE state = EMPTY_VALUE;
} boolean empty = true;
for(int i = 0;i<size;i++) {
@Override if(empty) {
public GENERIC_SPECIAL_KEY_BRACES<E> KEY_SPECIAL_TYPE[] TO_ARRAY(KEY_SPECIAL_TYPE[] input) { empty = false;
if(input == null || input.length < size()) input = NEW_SPECIAL_KEY_ARRAY(size()); state = array[i];
System.arraycopy(array, 0, input, 0, size()); continue;
return input; }
} state = operator.APPLY_VALUE(state, array[i]);
}
private class Iter implements ITERATOR KEY_GENERIC_TYPE { return empty ? OPTIONAL.empty() : OPTIONAL.GET_OPTIONAL(state);
@Override }
public boolean hasNext() {
return !isEmpty(); @Override
} public OPTIONAL KEY_GENERIC_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
@Override for(int i = 0;i<size;i++) {
public KEY_TYPE NEXT() { if(filter.test(array[i])) {
if(!hasNext()) throw new NoSuchElementException(); KEY_TYPE data = array[i];
return dequeue(); removeIndex(i);
} return OPTIONAL.GET_OPTIONAL(data);
} }
}
return OPTIONAL.empty();
}
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int result = 0;
for(int i = 0;i<size;i++) {
if(filter.test(array[i])) result++;
}
return result;
}
protected boolean removeIndex(int index) {
array[index] = array[--size];
#if TYPE_OBJECT
array[size] = null;
#endif
if(size != index) ARRAYS.shiftDown(array, size, index, comparator);
return true;
}
@Override
public void onChanged() {
if(size <= 0) return;
ARRAYS.shiftDown(array, size, 0, comparator);
}
@Override
public HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE copy() {
HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE queue = new HEAP_PRIORITY_QUEUEBRACES();
queue.size = size;
queue.comparator = comparator;
queue.array = Arrays.copyOf(array, array.length);
return queue;
}
@Override
public COMPARATOR KEY_SUPER_GENERIC_TYPE comparator() {
return comparator;
}
@Override
public GENERIC_SPECIAL_KEY_BRACES<E> KEY_SPECIAL_TYPE[] TO_ARRAY(KEY_SPECIAL_TYPE[] input) {
if(input == null || input.length < size()) input = NEW_SPECIAL_KEY_ARRAY(size());
System.arraycopy(array, 0, input, 0, size());
return input;
}
private class Iter implements ITERATOR KEY_GENERIC_TYPE {
@Override
public boolean hasNext() {
return !isEmpty();
}
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
return dequeue();
}
}
} }
@@ -1,195 +1,203 @@
package speiger.src.collections.PACKAGE.queues; package speiger.src.collections.PACKAGE.queues;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Comparator; import java.util.Comparator;
import java.util.Collection; import java.util.Collection;
import java.util.Iterator; import java.util.Iterator;
import java.util.function.IntFunction; import java.util.function.IntFunction;
#else #else
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
#endif #endif
import speiger.src.collections.PACKAGE.collections.COLLECTION; import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERABLE; import speiger.src.collections.PACKAGE.collections.ITERABLE;
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ITERATOR;
#if QUEUES_FEATURE #if QUEUES_FEATURE
import speiger.src.collections.PACKAGE.utils.PRIORITY_QUEUES; import speiger.src.collections.PACKAGE.utils.PRIORITY_QUEUES;
#endif #endif
/** /**
* A Simple PriorityQueue (or Queue) interface that provides with the nessesary functions to interact with it, without cluttering with the Collection interface. * A Simple PriorityQueue (or Queue) interface that provides with the nessesary functions to interact with it, without cluttering with the Collection interface.
* @Type(T) * @Type(T)
*/ */
public interface PRIORITY_QUEUE KEY_GENERIC_TYPE extends ITERABLE KEY_GENERIC_TYPE public interface PRIORITY_QUEUE KEY_GENERIC_TYPE extends ITERABLE KEY_GENERIC_TYPE
{ {
/** /**
* @return true if the PriorityQueue is empty * @return true if the PriorityQueue is empty
*/ */
public default boolean isEmpty() { return size() <= 0; } public default boolean isEmpty() { return size() <= 0; }
/** /**
* @return the amount of elements that are stored in the PriorityQueue * @return the amount of elements that are stored in the PriorityQueue
*/ */
public int size(); public int size();
/** /**
* clears all elements within the PriorityQueue, * clears all elements within the PriorityQueue,
* this does not resize the backing arrays * this does not resize the backing arrays
*/ */
public void clear(); public void clear();
/** /**
* Method to insert a element into the PriorityQueue * Method to insert a element into the PriorityQueue
* @param e the element that should be inserted * @param e the element that should be inserted
*/ */
public void enqueue(KEY_TYPE e); public void enqueue(KEY_TYPE e);
/** /**
* Method to mass insert elements into the PriorityQueue * Method to mass insert elements into the PriorityQueue
* @param e the elements that should be inserted * @param e the elements that should be inserted
*/ */
public default void enqueueAll(KEY_TYPE... e) { public default void enqueueAll(KEY_TYPE... e) {
enqueueAll(e, 0, e.length); enqueueAll(e, 0, e.length);
} }
/** /**
* Method to mass insert elements into the PriorityQueue * Method to mass insert elements into the PriorityQueue
* @param e the elements that should be inserted * @param e the elements that should be inserted
* @param length the amount of elements that should be inserted * @param length the amount of elements that should be inserted
*/ */
public default void enqueueAll(KEY_TYPE[] e, int length) { public default void enqueueAll(KEY_TYPE[] e, int length) {
enqueueAll(e, 0, length); enqueueAll(e, 0, length);
} }
/** /**
* Method to mass insert elements into the PriorityQueue * Method to mass insert elements into the PriorityQueue
* @param e the elements that should be inserted * @param e the elements that should be inserted
* @param offset the offset where in the array should be started * @param offset the offset where in the array should be started
* @param length the amount of elements that should be inserted * @param length the amount of elements that should be inserted
*/ */
public default void enqueueAll(KEY_TYPE[] e, int offset, int length) { public default void enqueueAll(KEY_TYPE[] e, int offset, int length) {
for(int i = 0;i<length;i++) for(int i = 0;i<length;i++)
enqueue(e[i+offset]); enqueue(e[i+offset]);
} }
/** /**
* Method to mass insert elements into the PriorityQueue * Method to mass insert elements into the PriorityQueue
* @param c the elements that should be inserted from the Collection * @param c the elements that should be inserted from the Collection
*/ */
public default void enqueueAll(COLLECTION KEY_GENERIC_TYPE c) { public default void enqueueAll(COLLECTION KEY_GENERIC_TYPE c) {
for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();) for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();)
enqueue(iter.NEXT()); enqueue(iter.NEXT());
} }
#if TYPE_OBJECT #if TYPE_OBJECT
/** /**
* Method to mass insert elements into the PriorityQueue * Method to mass insert elements into the PriorityQueue
* This method exists to add support for Java Collections to make it more useable * This method exists to add support for Java Collections to make it more useable
* @param c the elements that should be inserted from the Collection * @param c the elements that should be inserted from the Collection
*/ */
public default void enqueueAll(Collection<? extends CLASS_TYPE> c) { public default void enqueueAll(Collection<? extends CLASS_TYPE> c) {
for(Iterator<? extends CLASS_TYPE> iter = c.iterator();iter.hasNext();) for(Iterator<? extends CLASS_TYPE> iter = c.iterator();iter.hasNext();)
enqueue(iter.next()); enqueue(iter.next());
} }
#endif #endif
/** /**
* Method to extract a element from the PriorityQueue * Method to extract a element from the PriorityQueue
* @return a element from the Queue * @return a element from the Queue
* @throws java.util.NoSuchElementException if no element is present * @throws java.util.NoSuchElementException if no element is present
*/ */
public KEY_TYPE dequeue(); public KEY_TYPE dequeue();
/** /**
* Peeking function to see whats inside the queue. * Peeking function to see whats inside the queue.
* @param index of the element that is requested to be viewed. * @param index of the element that is requested to be viewed.
* @return the element that is requested * @return the element that is requested
*/ */
public KEY_TYPE peek(int index); public KEY_TYPE peek(int index);
/** /**
* Shows the element that is to be returned next * Shows the element that is to be returned next
* @return the first element in the Queue * @return the first element in the Queue
*/ */
public default KEY_TYPE first() { return peek(0); } public default KEY_TYPE first() { return peek(0); }
/** /**
* Removes the first found element in the queue * Method to find out if a element is part of the queue
* @param e the element that should be removed * @param e the element that is searched for
* @return if a searched element was removed * @return true if the element is in the queue
*/ */
public boolean removeFirst(KEY_TYPE e); public boolean contains(KEY_TYPE e);
/**
* Removes the last found element in the queue /**
* @param e the element that should be removed * Removes the first found element in the queue
* @return if a searched element was removed * @param e the element that should be removed
*/ * @return if a searched element was removed
public boolean removeLast(KEY_TYPE e); */
public boolean removeFirst(KEY_TYPE e);
/** /**
* Allows to notify the Queue to be revalidate its data * Removes the last found element in the queue
*/ * @param e the element that should be removed
public void onChanged(); * @return if a searched element was removed
*/
/** public boolean removeLast(KEY_TYPE e);
* 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 * Allows to notify the Queue to be revalidate its data
* @return a Shallow Copy of the PriorityQueue */
* @note Wrappers and view PriorityQueues will not support this feature public void onChanged();
*/
public PRIORITY_QUEUE KEY_GENERIC_TYPE copy(); /**
* 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.
* @return the sorter of the Queue, can be null * It can be compared to Cloneable but with less exception risk
*/ * @return a Shallow Copy of the PriorityQueue
public COMPARATOR KEY_SUPER_GENERIC_TYPE comparator(); * @note Wrappers and view PriorityQueues will not support this feature
*/
#if TYPE_OBJECT public PRIORITY_QUEUE KEY_GENERIC_TYPE copy();
/**
* @return draining iterator of the PriorityQueue /**
*/ * @return the sorter of the Queue, can be null
public ITERATOR KEY_GENERIC_TYPE iterator(); */
public COMPARATOR KEY_SUPER_GENERIC_TYPE comparator();
#endif
#if QUEUES_FEATURE #if TYPE_OBJECT
/** /**
* Creates a Wrapped PriorityQueue that is Synchronized * @return draining iterator of the PriorityQueue
* @return a new PriorityQueue that is synchronized */
* @see PRIORITY_QUEUES#synchronize public ITERATOR KEY_GENERIC_TYPE iterator();
*/
public default PRIORITY_QUEUE KEY_GENERIC_TYPE synchronizeQueue() { return PRIORITY_QUEUES.synchronize(this); } #endif
#if QUEUES_FEATURE
/** /**
* Creates a Wrapped PriorityQueue that is Synchronized * Creates a Wrapped PriorityQueue that is Synchronized
* @param mutex is the controller of the synchronization block * @return a new PriorityQueue that is synchronized
* @return a new PriorityQueue Wrapper that is synchronized * @see PRIORITY_QUEUES#synchronize
* @see PRIORITY_QUEUES#synchronize */
*/ public default PRIORITY_QUEUE KEY_GENERIC_TYPE synchronizeQueue() { return PRIORITY_QUEUES.synchronize(this); }
public default PRIORITY_QUEUE KEY_GENERIC_TYPE synchronizeQueue(Object mutex) { return PRIORITY_QUEUES.synchronize(this, mutex); }
/**
#endif * Creates a Wrapped PriorityQueue that is Synchronized
/** * @param mutex is the controller of the synchronization block
* A method to drop the contents of the Queue without clearing the queue * @return a new PriorityQueue Wrapper that is synchronized
* @Type(E) * @see PRIORITY_QUEUES#synchronize
* @return the contents of the queue into a seperate array. */
*/ public default PRIORITY_QUEUE KEY_GENERIC_TYPE synchronizeQueue(Object mutex) { return PRIORITY_QUEUES.synchronize(this, mutex); }
public default GENERIC_SPECIAL_KEY_BRACES<E> KEY_SPECIAL_TYPE[] TO_ARRAY() { return TO_ARRAY(NEW_SPECIAL_KEY_ARRAY(size())); }
/** #endif
* 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 * A method to drop the contents of the Queue without clearing the queue
* @Type(E) * @Type(E)
* @return the contents of the queue into a seperate array. * @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 default GENERIC_SPECIAL_KEY_BRACES<E> KEY_SPECIAL_TYPE[] TO_ARRAY() { return TO_ARRAY(NEW_SPECIAL_KEY_ARRAY(size())); }
public GENERIC_SPECIAL_KEY_BRACES<E> KEY_SPECIAL_TYPE[] TO_ARRAY(KEY_SPECIAL_TYPE[] input); /**
#if TYPE_OBJECT * 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
* A Helper function that simplifies the process of creating a new Array. * @Type(E)
* @param action the array creation function * @return the contents of the queue into a seperate array.
* @return an array containing all of the elements in this collection * @note if the Type is generic then a Object Array is created instead of a Type Array
* @see Collection#toArray(Object[]) */
*/ public GENERIC_SPECIAL_KEY_BRACES<E> KEY_SPECIAL_TYPE[] TO_ARRAY(KEY_SPECIAL_TYPE[] input);
default <E> E[] TO_ARRAY(IntFunction<E[]> action) { #if TYPE_OBJECT
return TO_ARRAY(action.apply(size())); /**
} * A Helper function that simplifies the process of creating a new Array.
#endif * @param action the array creation function
* @param <E> the returning arrayType
* @return an array containing all of the elements in this collection
* @see Collection#toArray(Object[])
*/
default <E> E[] TO_ARRAY(IntFunction<E[]> action) {
return TO_ARRAY(action.apply(size()));
}
#endif
} }
File diff suppressed because it is too large Load Diff
@@ -1,50 +1,152 @@
package speiger.src.collections.PACKAGE.sets; package speiger.src.collections.PACKAGE.sets;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Objects; import java.util.Objects;
#endif #endif
import java.util.Set; import java.util.Set;
import speiger.src.collections.PACKAGE.collections.ABSTRACT_COLLECTION; import speiger.src.collections.PACKAGE.collections.ABSTRACT_COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
import speiger.src.collections.PACKAGE.collections.ITERATOR;
/**
* Abstract Type Specific Set that reduces boxing/unboxing /**
* @Type(T) * 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 */
{ public abstract class ABSTRACT_SET KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION KEY_GENERIC_TYPE implements SET KEY_GENERIC_TYPE
#if TYPE_OBJECT {
@Override #if TYPE_OBJECT
public KEY_TYPE addOrGet(KEY_TYPE o) { throw new UnsupportedOperationException(); } @Override
public KEY_TYPE addOrGet(KEY_TYPE o) { throw new UnsupportedOperationException(); }
#endif
@Override #endif
public abstract ITERATOR KEY_GENERIC_TYPE iterator(); @Override
@Override public abstract ITERATOR KEY_GENERIC_TYPE iterator();
public ABSTRACT_SET KEY_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); } @Override
public ABSTRACT_SET KEY_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); }
@Override
public int hashCode() { @Override
int hashCode = 0; public int hashCode() {
ITERATOR KEY_GENERIC_TYPE i = iterator(); int hashCode = 0;
while(i.hasNext()) ITERATOR KEY_GENERIC_TYPE i = iterator();
hashCode += KEY_TO_HASH(i.NEXT()); while(i.hasNext())
return hashCode; hashCode += KEY_TO_HASH(i.NEXT());
} return hashCode;
}
@Override
public boolean equals(Object o) { @Override
if (o == this) public boolean equals(Object o) {
return true; if (o == this)
if (!(o instanceof Set)) return true;
return false; if (!(o instanceof Set))
Set<?> l = (Set<?>)o; return false;
if(l.size() != size()) return false; Set<?> l = (Set<?>)o;
try { if(l.size() != size()) return false;
return containsAll(l); try {
} catch (ClassCastException | NullPointerException unused) { return containsAll(l);
return false; } catch (ClassCastException | NullPointerException unused) {
} return false;
} }
} }
#if ORDERED_SET_FEATURE
public static class REVERSED_ORDERED_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE {
protected ORDERED_SET KEY_GENERIC_TYPE set;
public REVERSED_ORDERED_SET(ORDERED_SET KEY_GENERIC_TYPE set) {
this.set = set;
}
@Override
public REVERSED_ORDERED_SET KEY_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); }
@Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) {
return set.iterator(fromElement);
}
@Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator() {
return set.reverseIterator();
}
@Override
public BI_ITERATOR KEY_GENERIC_TYPE reverseIterator() {
return set.iterator();
}
@Override
public void addFirst(KEY_TYPE o) {
set.addLast(o);
}
@Override
public void addLast(KEY_TYPE o) {
set.addFirst(o);
}
@Override
#if !TYPE_OBJECT
public boolean remove(KEY_TYPE o) {
#else
public boolean remove(Object o) {
#endif
return set.remove(o);
}
@Override
public boolean add(KEY_TYPE o) {
return set.add(o);
}
@Override
public boolean addAndMoveToFirst(KEY_TYPE o) {
return set.addAndMoveToLast(o);
}
@Override
public boolean addAndMoveToLast(KEY_TYPE o) {
return set.addAndMoveToFirst(o);
}
@Override
public boolean moveToFirst(KEY_TYPE o) {
return set.moveToLast(o);
}
@Override
public boolean moveToLast(KEY_TYPE o) {
return set.moveToFirst(o);
}
@Override
public KEY_TYPE GET_FIRST_KEY() {
return set.GET_LAST_KEY();
}
@Override
public KEY_TYPE REMOVE_FIRST_KEY() {
return set.REMOVE_LAST_KEY();
}
@Override
public KEY_TYPE GET_LAST_KEY() {
return set.GET_FIRST_KEY();
}
@Override
public KEY_TYPE REMOVE_LAST_KEY() {
return set.REMOVE_FIRST_KEY();
}
@Override
public ORDERED_SET KEY_GENERIC_TYPE reversed() {
return set;
}
@Override
public int size() {
return set.size();
}
}
#endif
}
@@ -8,6 +8,15 @@ import java.util.function.BiFunction;
#endif #endif
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Objects; import java.util.Objects;
#if JDK_TYPE
import java.util.OPTIONAL;
#if !TYPE_OBJECT
import java.util.stream.JAVA_STREAM;
#else
import java.util.stream.Stream;
import java.util.stream.Collector;
#endif
#endif
import java.util.Set; import java.util.Set;
#if JDK_FUNCTION #if JDK_FUNCTION
import java.util.function.PREDICATE; import java.util.function.PREDICATE;
@@ -18,7 +27,9 @@ import java.util.function.JAVA_PREDICATE;
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
import speiger.src.collections.PACKAGE.collections.COLLECTION; import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ITERATOR;
#if !JDK_TYPE
import speiger.src.collections.PACKAGE.functions.OPTIONAL;
#endif
import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER; import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER;
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
#if !JDK_FUNCTION #if !JDK_FUNCTION
@@ -69,7 +80,7 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
* @param array the array that should be used for set. * @param array the array that should be used for set.
*/ */
public ARRAY_SET(KEY_TYPE[] array) { public ARRAY_SET(KEY_TYPE[] array) {
this(array, array.length); this(array, 0, array.length);
} }
/** /**
@@ -83,6 +94,18 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
addAll(array, length); addAll(array, length);
} }
/**
* Constructur using initial Array
* @param array the array that should be used for set.
* @param offset the starting offset of where the array should be copied from
* @param length the amount of elements present within the array
* @throws NegativeArraySizeException if the length is negative
*/
public ARRAY_SET(KEY_TYPE[] array, int offset, int length) {
this(length);
addAll(array, offset, length);
}
/** /**
* A Helper constructor that allows to create a Set with exactly the same values as the provided collection. * A Helper constructor that allows to create a Set with exactly the same values as the provided collection.
* @param c the elements that should be added to the set. * @param c the elements that should be added to the set.
@@ -126,6 +149,42 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
for(ITERATOR KEY_GENERIC_TYPE iter = s.iterator();iter.hasNext();data[size++] = iter.NEXT()); for(ITERATOR KEY_GENERIC_TYPE iter = s.iterator();iter.hasNext();data[size++] = iter.NEXT());
} }
#if JDK_TYPE && SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#if TYPE_OBJECT
/**
* Creates a Collector for a ArraySet
* @Type(T)
* @return a collector
*/
public static <T> Collector<T, ARRAY_SET<T>, ARRAY_SET<T>> toList() {
return Collector.of(ARRAY_SET::new, ARRAY_SET::add, ARRAY_SET::merge);
}
/**
* Collects a Stream to a ArraySet
* @Type(T)
* @return a set with the contents of the Stream
*/
public static <T> ARRAY_SET KEY_GENERIC_TYPE toList(Stream<T> stream) {
return stream.collect(ARRAY_SET::new, ARRAY_SET::add, ARRAY_SET::merge);
}
private ARRAY_SET<T> merge(ARRAY_SET<T> a) {
addAll(a);
return this;
}
#else
/**
* Collects a Stream to a ArraySet
* @return a set with the contents of the Stream
*/
public static ARRAY_SET toList(JAVA_STREAM stream) {
return stream.collect(ARRAY_SET::new, ARRAY_SET::add, ARRAY_SET::addAll);
}
#endif
#endif
@Override @Override
public boolean add(KEY_TYPE o) { public boolean add(KEY_TYPE o) {
int index = findIndex(o); int index = findIndex(o);
@@ -148,6 +207,25 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
} }
#endif #endif
@Override
public void addFirst(KEY_TYPE o) {
int index = findIndex(o);
if(index == -1) {
if(data.length == size) data = Arrays.copyOf(data, size == 0 ? 2 : size * 2);
System.arraycopy(data, 0, data, 1, size++);
data[0] = o;
}
}
@Override
public void addLast(KEY_TYPE o) {
int index = findIndex(o);
if(index == -1) {
if(data.length == size) data = Arrays.copyOf(data, size == 0 ? 2 : size * 2);
data[size++] = o;
}
}
@Override @Override
public boolean addAndMoveToFirst(KEY_TYPE o) { public boolean addAndMoveToFirst(KEY_TYPE o) {
int index = findIndex(o); int index = findIndex(o);
@@ -219,13 +297,13 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
#endif #endif
@Override @Override
public KEY_TYPE FIRST_KEY() { public KEY_TYPE GET_FIRST_KEY() {
if(size == 0) throw new NoSuchElementException(); if(size == 0) throw new NoSuchElementException();
return data[0]; return data[0];
} }
@Override @Override
public KEY_TYPE LAST_KEY() { public KEY_TYPE GET_LAST_KEY() {
if(size == 0) throw new NoSuchElementException(); if(size == 0) throw new NoSuchElementException();
return data[size - 1]; return data[size - 1];
} }
@@ -354,7 +432,7 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
#endif #endif
@Override @Override
public KEY_TYPE POLL_FIRST_KEY() { public KEY_TYPE REMOVE_FIRST_KEY() {
if(size == 0) throw new NoSuchElementException(); if(size == 0) throw new NoSuchElementException();
KEY_TYPE result = data[0]; KEY_TYPE result = data[0];
System.arraycopy(data, 1, data, 0, --size); System.arraycopy(data, 1, data, 0, --size);
@@ -365,7 +443,7 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
} }
@Override @Override
public KEY_TYPE POLL_LAST_KEY() { public KEY_TYPE REMOVE_LAST_KEY() {
if(size == 0) throw new NoSuchElementException(); if(size == 0) throw new NoSuchElementException();
size--; size--;
#if TYPE_OBJECT #if TYPE_OBJECT
@@ -438,12 +516,12 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
} }
@Override @Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { public OPTIONAL KEY_GENERIC_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter); Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) { for(int i = 0;i<size;i++) {
if(filter.test(data[i])) return data[i]; if(filter.test(data[i])) return OPTIONAL.GET_OPTIONAL(data[i]);
} }
return EMPTY_VALUE; return OPTIONAL.empty();
} }
#if !TYPE_OBJECT #if !TYPE_OBJECT
@@ -470,7 +548,7 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
#endif #endif
@Override @Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { public OPTIONAL KEY_GENERIC_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator); Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_VALUE; KEY_TYPE state = EMPTY_VALUE;
boolean empty = true; boolean empty = true;
@@ -482,7 +560,7 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
} }
state = operator.APPLY_VALUE(state, data[i]); state = operator.APPLY_VALUE(state, data[i]);
} }
return state; return empty ? OPTIONAL.empty() : OPTIONAL.GET_OPTIONAL(state);
} }
@Override @Override
@@ -511,13 +589,18 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
@Override @Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator() { public BI_ITERATOR KEY_GENERIC_TYPE iterator() {
return new SetIterator(0); return new SetIterator(true, 0);
}
@Override
public BI_ITERATOR KEY_GENERIC_TYPE reverseIterator() {
return new SetIterator(false, size);
} }
@Override @Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) {
int index = findIndex(fromElement); int index = findIndex(fromElement);
if(index != -1) return new SetIterator(index); if(index != -1) return new SetIterator(true, index);
throw new NoSuchElementException(); throw new NoSuchElementException();
} }
@@ -570,45 +653,57 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
} }
private class SetIterator implements LIST_ITERATOR KEY_GENERIC_TYPE { private class SetIterator implements LIST_ITERATOR KEY_GENERIC_TYPE {
boolean forward;
int index; int index;
int lastReturned = -1; int lastReturned = -1;
public SetIterator(int index) { public SetIterator(boolean forward, int index) {
this.forward = forward;
this.index = index; this.index = index;
} }
@Override @Override
public boolean hasNext() { public boolean hasNext() {
return index < size(); return forward ? index < size() : index > 0;
} }
@Override @Override
public KEY_TYPE NEXT() { public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException(); if(!hasNext()) throw new NoSuchElementException();
lastReturned = index; if(forward) {
return data[index++]; lastReturned = index;
return data[index++];
}
index--;
return data[(lastReturned = index)];
} }
@Override @Override
public boolean hasPrevious() { public boolean hasPrevious() {
return index > 0; return forward ? index > 0 : index < size();
} }
@Override @Override
public KEY_TYPE PREVIOUS() { public KEY_TYPE PREVIOUS() {
if(!hasPrevious()) throw new NoSuchElementException(); if(!hasPrevious()) throw new NoSuchElementException();
--index; if(forward) {
return data[(lastReturned = index)]; index--;
return data[(lastReturned = index)];
}
lastReturned = index;
return data[index++];
} }
@Override @Override
public int nextIndex() { public int nextIndex() {
return index; if(forward) return index;
return size - index;
} }
@Override @Override
public int previousIndex() { public int previousIndex() {
return index-1; if(forward) return index-1;
return (size - index)-1;
} }
@Override @Override
@@ -637,15 +732,23 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
@Override @Override
public int skip(int amount) { public int skip(int amount) {
if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed"); if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
return forward ? moveForward(amount) : moveBackwards(amount);
}
@Override
public int back(int amount) {
if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
return forward ? moveBackwards(amount) : moveForward(amount);
}
private int moveForward(int amount) {
int steps = Math.min(amount, size() - index); int steps = Math.min(amount, size() - index);
index += steps; index += steps;
if(steps > 0) lastReturned = Math.min(index-1, size()-1); if(steps > 0) lastReturned = Math.min(index-1, size()-1);
return steps; return steps;
} }
@Override private int moveBackwards(int amount) {
public int back(int amount) {
if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
int steps = Math.min(amount, index); int steps = Math.min(amount, index);
index -= steps; index -= steps;
if(steps > 0) lastReturned = Math.min(index, size()-1); if(steps > 0) lastReturned = Math.min(index, size()-1);
@@ -3,11 +3,13 @@ package speiger.src.collections.PACKAGE.sets;
import java.util.NavigableSet; import java.util.NavigableSet;
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
#if SPLIT_ITERATOR_FEATURE
import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR; import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR;
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
#endif
#if SETS_FEATURE #if SETS_FEATURE
import speiger.src.collections.PACKAGE.utils.SETS; import speiger.src.collections.PACKAGE.utils.SETS;
#endif #endif
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
/** /**
* A Type Specific Navigable Set interface with a couple helper methods * A Type Specific Navigable Set interface with a couple helper methods
@@ -145,6 +147,7 @@ public interface NAVIGABLE_SET KEY_GENERIC_TYPE extends NavigableSet<CLASS_TYPE>
public default NAVIGABLE_SET KEY_GENERIC_TYPE unmodifiable() { return SETS.unmodifiable(this); } public default NAVIGABLE_SET KEY_GENERIC_TYPE unmodifiable() { return SETS.unmodifiable(this); }
#endif #endif
#if SPLIT_ITERATOR_FEATURE
/** /**
* A Type Specific Type Splititerator to reduce boxing/unboxing * A Type Specific Type Splititerator to reduce boxing/unboxing
* @return type specific splititerator * @return type specific splititerator
@@ -152,6 +155,7 @@ public interface NAVIGABLE_SET KEY_GENERIC_TYPE extends NavigableSet<CLASS_TYPE>
@Override @Override
default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createSplititerator(this, 0); } default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createSplititerator(this, 0); }
#endif
#if !TYPE_OBJECT #if !TYPE_OBJECT
@Override @Override
@Deprecated @Deprecated
File diff suppressed because it is too large Load Diff
@@ -1,11 +1,19 @@
package speiger.src.collections.PACKAGE.sets; package speiger.src.collections.PACKAGE.sets;
#if JAVA_VERSION>=21
import java.util.SequencedSet;
#endif
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
import speiger.src.collections.PACKAGE.collections.ORDERED_COLLECTION;
#if SPLIT_ITERATOR_FEATURE
import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR; import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR;
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
#endif
import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET.REVERSED_ORDERED_SET;
#if SETS_FEATURE #if SETS_FEATURE
import speiger.src.collections.PACKAGE.utils.SETS; import speiger.src.collections.PACKAGE.utils.SETS;
#endif #endif
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
/** /**
* A Special Set Interface giving Access to some really usefull functions * A Special Set Interface giving Access to some really usefull functions
@@ -15,7 +23,11 @@ import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
* *
* @Type(T) * @Type(T)
*/ */
public interface ORDERED_SET KEY_GENERIC_TYPE extends SET KEY_GENERIC_TYPE #if JAVA_VERSION>=21
public interface ORDERED_SET KEY_GENERIC_TYPE extends SET KEY_GENERIC_TYPE, ORDERED_COLLECTION KEY_GENERIC_TYPE, SequencedSet<CLASS_TYPE>
#else
public interface ORDERED_SET KEY_GENERIC_TYPE extends SET KEY_GENERIC_TYPE, ORDERED_COLLECTION KEY_GENERIC_TYPE
#endif
{ {
/** /**
* A customized add method that allows you to insert into the first index. * A customized add method that allows you to insert into the first index.
@@ -52,6 +64,7 @@ public interface ORDERED_SET KEY_GENERIC_TYPE extends SET KEY_GENERIC_TYPE
@Override @Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator(); public BI_ITERATOR KEY_GENERIC_TYPE iterator();
public BI_ITERATOR KEY_GENERIC_TYPE reverseIterator();
/** /**
* A type Specific Iterator starting from a given key * A type Specific Iterator starting from a given key
@@ -61,6 +74,7 @@ public interface ORDERED_SET KEY_GENERIC_TYPE extends SET KEY_GENERIC_TYPE
*/ */
public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement); public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement);
#if SPLIT_ITERATOR_FEATURE
/** /**
* A Type Specific Type Splititerator to reduce boxing/unboxing * A Type Specific Type Splititerator to reduce boxing/unboxing
* @return type specific splititerator * @return type specific splititerator
@@ -68,27 +82,81 @@ public interface ORDERED_SET KEY_GENERIC_TYPE extends SET KEY_GENERIC_TYPE
@Override @Override
default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createSplititerator(this, 0); } default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createSplititerator(this, 0); }
#endif
/** /**
* A method to get the first element in the set * A method to get the first element in the set
* @return first element in the set * @return first element in the set
*/ */
public KEY_TYPE FIRST_KEY(); public KEY_TYPE GET_FIRST_KEY();
/** /**
* A method to get and remove the first element in the set * A method to get and remove the first element in the set
* @return first element in the set * @return first element in the set
*/ */
public KEY_TYPE POLL_FIRST_KEY(); public KEY_TYPE REMOVE_FIRST_KEY();
/** /**
* A method to get the last element in the set * A method to get the last element in the set
* @return last element in the set * @return last element in the set
*/ */
public KEY_TYPE LAST_KEY(); public KEY_TYPE GET_LAST_KEY();
/** /**
* A method to get and remove the last element in the set * A method to get and remove the last element in the set
* @return last element in the set * @return last element in the set
*/ */
public KEY_TYPE POLL_LAST_KEY(); public KEY_TYPE REMOVE_LAST_KEY();
#if JAVA_VERSION>=21 && !TYPE_OBJECT
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default void addFirst(CLASS_TYPE e) { addAndMoveToFirst(OBJ_TO_KEY(e)); }
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default void addLast(CLASS_TYPE e) { addAndMoveToLast(OBJ_TO_KEY(e)); }
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default CLASS_TYPE getFirst() { return GET_FIRST_KEY(); }
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default CLASS_TYPE getLast() { return GET_LAST_KEY(); }
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default CLASS_TYPE removeFirst() { return REMOVE_FIRST_KEY(); }
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default CLASS_TYPE removeLast() { return REMOVE_LAST_KEY(); }
#endif
@Java21
public default ORDERED_SET KEY_GENERIC_TYPE reversed() { return new REVERSED_ORDERED_SETBRACES(this); }
#if SETS_FEATURE #if SETS_FEATURE
/** /**
* Creates a Wrapped OrderedSet that is Synchronized * Creates a Wrapped OrderedSet that is Synchronized
File diff suppressed because it is too large Load Diff
@@ -4,11 +4,13 @@ import java.util.Set;
import speiger.src.collections.PACKAGE.collections.COLLECTION; import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ITERATOR;
#if SPLIT_ITERATOR_FEATURE
import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR; import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR;
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
#endif
#if SETS_FEATURE #if SETS_FEATURE
import speiger.src.collections.PACKAGE.utils.SETS; import speiger.src.collections.PACKAGE.utils.SETS;
#endif #endif
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
/** /**
@@ -88,10 +90,12 @@ public interface SET KEY_GENERIC_TYPE extends Set<CLASS_TYPE>, COLLECTION KEY_GE
public default SET KEY_GENERIC_TYPE unmodifiable() { return SETS.unmodifiable(this); } public default SET KEY_GENERIC_TYPE unmodifiable() { return SETS.unmodifiable(this); }
#endif #endif
#if SPLIT_ITERATOR_FEATURE
/** /**
* A Type Specific Type Splititerator to reduce boxing/unboxing * A Type Specific Type Splititerator to reduce boxing/unboxing
* @return type specific splititerator * @return type specific splititerator
*/ */
@Override @Override
default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createSplititerator(this, 0); } default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createSplititerator(this, 0); }
} #endif
}
@@ -3,7 +3,9 @@ package speiger.src.collections.PACKAGE.sets;
import java.util.SortedSet; import java.util.SortedSet;
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
#if SPLIT_ITERATOR_FEATURE
import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR; import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR;
#endif
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Comparator; import java.util.Comparator;
#else #else
@@ -12,7 +14,9 @@ import speiger.src.collections.PACKAGE.functions.COMPARATOR;
#if SETS_FEATURE #if SETS_FEATURE
import speiger.src.collections.PACKAGE.utils.SETS; import speiger.src.collections.PACKAGE.utils.SETS;
#endif #endif
#if SPLIT_ITERATOR_FEATURE
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS; import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
#endif
/** /**
* A Type Specific SortedSet implementation to reduce boxing/unboxing * A Type Specific SortedSet implementation to reduce boxing/unboxing
@@ -67,6 +71,7 @@ public interface SORTED_SET KEY_GENERIC_TYPE extends SET KEY_GENERIC_TYPE, Sorte
public default SORTED_SET KEY_GENERIC_TYPE unmodifiable() { return SETS.unmodifiable(this); } public default SORTED_SET KEY_GENERIC_TYPE unmodifiable() { return SETS.unmodifiable(this); }
#endif #endif
#if SPLIT_ITERATOR_FEATURE
/** /**
* A Type Specific Type Splititerator to reduce boxing/unboxing * A Type Specific Type Splititerator to reduce boxing/unboxing
* @return type specific splititerator * @return type specific splititerator
@@ -74,6 +79,7 @@ public interface SORTED_SET KEY_GENERIC_TYPE extends SET KEY_GENERIC_TYPE, Sorte
@Override @Override
default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createSplititerator(this, 0); } default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createSplititerator(this, 0); }
#endif
#if !TYPE_OBJECT #if !TYPE_OBJECT
/** /**
* A Type Specific SubSet method to reduce boxing/unboxing * A Type Specific SubSet method to reduce boxing/unboxing
File diff suppressed because it is too large Load Diff
@@ -7,6 +7,11 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.LockSupport; import java.util.concurrent.locks.LockSupport;
import java.util.function.Consumer; import java.util.function.Consumer;
#if JDK_TYPE
import java.util.OPTIONAL;
#else
import speiger.src.collections.PACKAGE.functions.OPTIONAL;
#endif
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.CONSUMER; import speiger.src.collections.PACKAGE.functions.CONSUMER;
@@ -16,6 +21,16 @@ import java.util.function.IntFunction;
import java.util.function.BiFunction; import java.util.function.BiFunction;
import java.util.Comparator; import java.util.Comparator;
#iterate
#argument MAPPER Predicate ToByteFunction ToShortFunction ToIntFunction ToLongFunction ToFloatFunction ToDoubleFunction
#argument BUILDER BooleanAsyncBuilder ByteAsyncBuilder ShortAsyncBuilder IntAsyncBuilder LongAsyncBuilder FloatAsyncBuilder DoubleAsyncBuilder
#argument PACKAGE booleans bytes shorts ints longs floats doubles
#argument CHECK BOOLEAN_ASYNC_MODULE BYTE_ASYNC_MODULE SHORT_ASYNC_MODULE INT_ASYNC_MODULE LONG_ASYNC_MODULE FLOAT_ASYNC_MODULE DOUBLE_ASYNC_MODULE
#if CHECK
import speiger.src.collections.objects.functions.function.MAPPER;
import speiger.src.collections.PACKAGE.utils.BUILDER;
#endif
#enditerate
#endif #endif
import speiger.src.collections.PACKAGE.collections.ITERABLE; import speiger.src.collections.PACKAGE.collections.ITERABLE;
#if OBJECT_ASYNC_MODULE #if OBJECT_ASYNC_MODULE
@@ -23,7 +38,9 @@ import speiger.src.collections.PACKAGE.collections.COLLECTION;
#endif #endif
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.functions.TASK; import speiger.src.collections.PACKAGE.functions.TASK;
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.function.PREDICATE; import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
#endif
#if OBJECT_ASYNC_MODULE #if OBJECT_ASYNC_MODULE
import speiger.src.collections.PACKAGE.functions.function.TO_OBJECT_FUNCTION; import speiger.src.collections.PACKAGE.functions.function.TO_OBJECT_FUNCTION;
#endif #endif
@@ -59,7 +76,9 @@ import speiger.src.collections.PACKAGE.sets.ARRAY_SET;
#endif #endif
#endif #endif
#if !TYPE_BOOLEAN && BOOLEAN_ASYNC_MODULE #if !TYPE_BOOLEAN && BOOLEAN_ASYNC_MODULE
#if !TYPE_OBJECT
import speiger.src.collections.booleans.utils.BooleanAsyncBuilder; import speiger.src.collections.booleans.utils.BooleanAsyncBuilder;
#endif
import speiger.src.collections.booleans.utils.BooleanAsyncBuilder.BaseBooleanTask; import speiger.src.collections.booleans.utils.BooleanAsyncBuilder.BaseBooleanTask;
#endif #endif
#if !TYPE_OBJECT && OBJECT_ASYNC_MODULE #if !TYPE_OBJECT && OBJECT_ASYNC_MODULE
@@ -67,7 +86,9 @@ import speiger.src.collections.objects.utils.ObjectAsyncBuilder;
import speiger.src.collections.objects.utils.ObjectAsyncBuilder.BaseObjectTask; import speiger.src.collections.objects.utils.ObjectAsyncBuilder.BaseObjectTask;
#endif #endif
#if !TYPE_INT && INT_ASYNC_MODULE #if !TYPE_INT && INT_ASYNC_MODULE
#if !TYPE_OBJECT
import speiger.src.collections.ints.utils.IntAsyncBuilder; import speiger.src.collections.ints.utils.IntAsyncBuilder;
#endif
import speiger.src.collections.ints.utils.IntAsyncBuilder.BaseIntTask; import speiger.src.collections.ints.utils.IntAsyncBuilder.BaseIntTask;
#endif #endif
import speiger.src.collections.utils.ISizeProvider; import speiger.src.collections.utils.ISizeProvider;
@@ -187,6 +208,25 @@ public class ASYNC_BUILDER KEY_GENERIC_TYPE
return new ObjectAsyncBuilder<>(ITERABLES.arrayFlatMap(iterable, mapper)); return new ObjectAsyncBuilder<>(ITERABLES.arrayFlatMap(iterable, mapper));
} }
#endif
#if TYPE_OBJECT
#iterate
#argument BUILDER BooleanAsyncBuilder ByteAsyncBuilder ShortAsyncBuilder IntAsyncBuilder LongAsyncBuilder FloatAsyncBuilder DoubleAsyncBuilder
#argument MAPPER Predicate ToByteFunction ToShortFunction ToIntFunction ToLongFunction ToFloatFunction ToDoubleFunction
#argument TYPE Boolean Byte Short Int Long Float Double
#argument CHECK BOOLEAN_ASYNC_MODULE BYTE_ASYNC_MODULE SHORT_ASYNC_MODULE INT_ASYNC_MODULE LONG_ASYNC_MODULE FLOAT_ASYNC_MODULE DOUBLE_ASYNC_MODULE
#if CHECK
/**
* Maps the elements to something else
* @param mapper the mapping function
* @return a new Builder Object with the mapped Iterable
*/
public BUILDER mapToTYPE(MAPPER<T> mapper) {
return new BUILDER(ITERABLES.mapToTYPE(iterable, mapper));
}
#endif
#enditerate
#endif #endif
/** /**
* Filters out the unwanted elements out of the Iterable * Filters out the unwanted elements out of the Iterable
@@ -264,9 +304,8 @@ public class ASYNC_BUILDER KEY_GENERIC_TYPE
* @param operator that reduces the elements. * @param operator that reduces the elements.
* @return self with the reduce action applied * @return self with the reduce action applied
*/ */
public ASYNC_BUILDER KEY_GENERIC_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { public ObjectAsyncBuilder<OPTIONAL KEY_GENERIC_TYPE> reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
task = new SimpleReduceTaskBRACES(iterable.iterator(), operator); return new ObjectAsyncBuilder<>(new SimpleReduceTaskBRACES(iterable.iterator(), operator));
return this;
} }
#if TYPE_OBJECT #if TYPE_OBJECT
@@ -400,9 +439,8 @@ public class ASYNC_BUILDER KEY_GENERIC_TYPE
* @param filter that decides the desired elements * @param filter that decides the desired elements
* @return self with the findFirst function applied * @return self with the findFirst function applied
*/ */
public ASYNC_BUILDER KEY_GENERIC_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { public ObjectAsyncBuilder<OPTIONAL KEY_GENERIC_TYPE> findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
task = new FindFirstTaskBRACES(iterable.iterator(), filter); return new ObjectAsyncBuilder<>(new FindFirstTaskBRACES(iterable.iterator(), filter));
return this;
} }
#if INT_ASYNC_MODULE #if INT_ASYNC_MODULE
@@ -555,7 +593,7 @@ public class ASYNC_BUILDER KEY_GENERIC_TYPE
} }
#endif #endif
private static class SimpleReduceTask KEY_GENERIC_TYPE extends BASE_TASK KEY_GENERIC_TYPE private static class SimpleReduceTask KEY_GENERIC_TYPE extends BaseObjectTask<OPTIONAL KEY_GENERIC_TYPE>
{ {
ITERATOR KEY_GENERIC_TYPE iter; ITERATOR KEY_GENERIC_TYPE iter;
UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator; UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator;
@@ -565,6 +603,7 @@ public class ASYNC_BUILDER KEY_GENERIC_TYPE
public SimpleReduceTask(ITERATOR KEY_GENERIC_TYPE iter, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { public SimpleReduceTask(ITERATOR KEY_GENERIC_TYPE iter, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
this.iter = iter; this.iter = iter;
this.operator = operator; this.operator = operator;
this.setResult(OPTIONAL.empty());
} }
@Override @Override
@@ -579,7 +618,7 @@ public class ASYNC_BUILDER KEY_GENERIC_TYPE
} }
} }
if(!iter.hasNext()) { if(!iter.hasNext()) {
setResult(value); setResult(OPTIONAL.GET_OPTIONAL(value));
return true; return true;
} }
return false; return false;
@@ -654,7 +693,7 @@ public class ASYNC_BUILDER KEY_GENERIC_TYPE
} }
#endif #endif
private static class FindFirstTask KEY_GENERIC_TYPE extends BASE_TASK KEY_GENERIC_TYPE private static class FindFirstTask KEY_GENERIC_TYPE extends BaseObjectTask<OPTIONAL KEY_GENERIC_TYPE>
{ {
ITERATOR KEY_GENERIC_TYPE iter; ITERATOR KEY_GENERIC_TYPE iter;
PREDICATE KEY_GENERIC_TYPE filter; PREDICATE KEY_GENERIC_TYPE filter;
@@ -662,6 +701,7 @@ public class ASYNC_BUILDER KEY_GENERIC_TYPE
public FindFirstTask(ITERATOR KEY_GENERIC_TYPE iter, PREDICATE KEY_GENERIC_TYPE filter) { public FindFirstTask(ITERATOR KEY_GENERIC_TYPE iter, PREDICATE KEY_GENERIC_TYPE filter) {
this.iter = iter; this.iter = iter;
this.filter = filter; this.filter = filter;
this.setResult(OPTIONAL.empty());
} }
@Override @Override
@@ -669,7 +709,7 @@ public class ASYNC_BUILDER KEY_GENERIC_TYPE
while(shouldRun() && iter.hasNext()) { while(shouldRun() && iter.hasNext()) {
KEY_TYPE entry = iter.NEXT(); KEY_TYPE entry = iter.NEXT();
if(filter.test(iter.NEXT())) { if(filter.test(iter.NEXT())) {
setResult(entry); setResult(OPTIONAL.GET_OPTIONAL(entry));
return true; return true;
} }
} }
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -4,16 +4,22 @@ package speiger.src.collections.PACKAGE.utils;
import java.util.Collection; import java.util.Collection;
import java.util.Comparator; import java.util.Comparator;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.BiFunction;
#endif #endif
#if JDK_FUNCTION #if JDK_FUNCTION
import java.util.function.PREDICATE; import java.util.function.PREDICATE;
#endif #endif
#if JDK_TYPE
import java.util.OPTIONAL;
#endif
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.collections.COLLECTION; import speiger.src.collections.PACKAGE.collections.COLLECTION;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
#endif #endif
#if !JDK_TYPE
import speiger.src.collections.PACKAGE.functions.OPTIONAL;
#endif
#if DEQUEUE_FEATURE #if DEQUEUE_FEATURE
import speiger.src.collections.PACKAGE.queues.PRIORITY_DEQUEUE; import speiger.src.collections.PACKAGE.queues.PRIORITY_DEQUEUE;
#endif #endif
@@ -24,6 +30,7 @@ import speiger.src.collections.PACKAGE.functions.CONSUMER;
#if !JDK_FUNCTION #if !JDK_FUNCTION
import speiger.src.collections.PACKAGE.functions.function.PREDICATE; import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
#endif #endif
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER; import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
/** /**
@@ -116,6 +123,8 @@ public class PRIORITY_QUEUES
@Override @Override
public KEY_TYPE peek(int index) { synchronized(mutex) { return queue.peek(index); } } public KEY_TYPE peek(int index) { synchronized(mutex) { return queue.peek(index); } }
@Override @Override
public boolean contains(KEY_TYPE e) { synchronized(mutex) { return queue.contains(e); } }
@Override
public boolean removeFirst(KEY_TYPE e) { synchronized(mutex) { return queue.removeFirst(e); } } public boolean removeFirst(KEY_TYPE e) { synchronized(mutex) { return queue.removeFirst(e); } }
@Override @Override
public boolean removeLast(KEY_TYPE e) { synchronized(mutex) { return queue.removeLast(e); } } public boolean removeLast(KEY_TYPE e) { synchronized(mutex) { return queue.removeLast(e); } }
@@ -138,7 +147,15 @@ public class PRIORITY_QUEUES
@Override @Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { synchronized(mutex) { return queue.matchesAll(filter); } } public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { synchronized(mutex) { return queue.matchesAll(filter); } }
@Override @Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { synchronized(mutex) { return queue.findFirst(filter); } } public OPTIONAL KEY_GENERIC_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { synchronized(mutex) { return queue.findFirst(filter); } }
#if TYPE_OBJECT
public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) { synchronized(mutex) { return queue.reduce(identity, operator); } }
#else
@Override
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { synchronized(mutex) { return queue.reduce(identity, operator); } }
#endif
@Override
public OPTIONAL KEY_GENERIC_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { synchronized(mutex) { return queue.reduce(operator); } }
@Override @Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) { synchronized(mutex) { return queue.count(filter); } } public int count(PREDICATE KEY_GENERIC_TYPE filter) { synchronized(mutex) { return queue.count(filter); } }
} }
@@ -360,6 +360,10 @@ public class SETS
s = c; s = c;
} }
@Override
public void addFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public void addLast(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override @Override
public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); } public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override @Override
@@ -371,17 +375,19 @@ public class SETS
@Override @Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator() { return ITERATORS.unmodifiable(s.iterator()); } public BI_ITERATOR KEY_GENERIC_TYPE iterator() { return ITERATORS.unmodifiable(s.iterator()); }
@Override @Override
public BI_ITERATOR KEY_GENERIC_TYPE reverseIterator() { return ITERATORS.unmodifiable(s.reverseIterator()); }
@Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { return ITERATORS.unmodifiable(s.iterator(fromElement)); } public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { return ITERATORS.unmodifiable(s.iterator(fromElement)); }
@Override @Override
public ORDERED_SET KEY_GENERIC_TYPE copy() { return s.copy(); } public ORDERED_SET KEY_GENERIC_TYPE copy() { return s.copy(); }
@Override @Override
public KEY_TYPE FIRST_KEY() { return s.FIRST_KEY(); } public KEY_TYPE GET_FIRST_KEY() { return s.GET_FIRST_KEY(); }
@Override @Override
public KEY_TYPE POLL_FIRST_KEY() { throw new UnsupportedOperationException(); } public KEY_TYPE REMOVE_FIRST_KEY() { throw new UnsupportedOperationException(); }
@Override @Override
public KEY_TYPE LAST_KEY() { return s.LAST_KEY(); } public KEY_TYPE GET_LAST_KEY() { return s.GET_LAST_KEY(); }
@Override @Override
public KEY_TYPE POLL_LAST_KEY() { throw new UnsupportedOperationException(); } public KEY_TYPE REMOVE_LAST_KEY() { throw new UnsupportedOperationException(); }
} }
#endif #endif
@@ -648,7 +654,11 @@ public class SETS
super(c, mutex); super(c, mutex);
s = c; s = c;
} }
@Override
public void addFirst(KEY_TYPE o) { synchronized(mutex) { s.addFirst(o); } }
@Override
public void addLast(KEY_TYPE o) { synchronized(mutex) { s.addLast(o); } }
@Override @Override
public boolean addAndMoveToFirst(KEY_TYPE o) { synchronized(mutex) { return s.addAndMoveToFirst(o); } } public boolean addAndMoveToFirst(KEY_TYPE o) { synchronized(mutex) { return s.addAndMoveToFirst(o); } }
@Override @Override
@@ -660,17 +670,19 @@ public class SETS
@Override @Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator() { synchronized(mutex) { return s.iterator(); } } public BI_ITERATOR KEY_GENERIC_TYPE iterator() { synchronized(mutex) { return s.iterator(); } }
@Override @Override
public BI_ITERATOR KEY_GENERIC_TYPE reverseIterator() { synchronized(mutex) { return s.reverseIterator(); } }
@Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { synchronized(mutex) { return s.iterator(fromElement); } } public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { synchronized(mutex) { return s.iterator(fromElement); } }
@Override @Override
public ORDERED_SET KEY_GENERIC_TYPE copy() { synchronized(mutex) { return s.copy(); } } public ORDERED_SET KEY_GENERIC_TYPE copy() { synchronized(mutex) { return s.copy(); } }
@Override @Override
public KEY_TYPE FIRST_KEY() { synchronized(mutex) { return s.FIRST_KEY(); } } public KEY_TYPE GET_FIRST_KEY() { synchronized(mutex) { return s.GET_FIRST_KEY(); } }
@Override @Override
public KEY_TYPE POLL_FIRST_KEY() { synchronized(mutex) { return s.POLL_FIRST_KEY(); } } public KEY_TYPE REMOVE_FIRST_KEY() { synchronized(mutex) { return s.REMOVE_FIRST_KEY(); } }
@Override @Override
public KEY_TYPE LAST_KEY() { synchronized(mutex) { return s.LAST_KEY(); } } public KEY_TYPE GET_LAST_KEY() { synchronized(mutex) { return s.GET_LAST_KEY(); } }
@Override @Override
public KEY_TYPE POLL_LAST_KEY() { synchronized(mutex) { return s.POLL_LAST_KEY(); } } public KEY_TYPE REMOVE_LAST_KEY() { synchronized(mutex) { return s.REMOVE_LAST_KEY(); } }
} }
#endif #endif
File diff suppressed because it is too large Load Diff
@@ -1,28 +1,28 @@
package speiger.src.testers.PACKAGE.builder; package speiger.src.testers.PACKAGE.builder;
import java.util.List; import java.util.List;
import com.google.common.collect.testing.AbstractTester; import com.google.common.collect.testing.AbstractTester;
import speiger.src.testers.PACKAGE.generators.TEST_QUEUE_GENERATOR; 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_TYPEDequeueDequeueTester;
import speiger.src.testers.PACKAGE.tests.queue.FILE_KEY_TYPEDequeueEnqueueTester; import speiger.src.testers.PACKAGE.tests.queue.FILE_KEY_TYPEDequeueEnqueueTester;
import speiger.src.testers.PACKAGE.tests.queue.FILE_KEY_TYPEDequeueLastTester; import speiger.src.testers.PACKAGE.tests.queue.FILE_KEY_TYPEDequeueLastTester;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class DEQUEUE_TEST_BUILDER KEY_GENERIC_TYPE extends QUEUE_TEST_BUILDER KEY_GENERIC_TYPE 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) { 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); return (DEQUEUE_TEST_BUILDER KEY_GENERIC_TYPE)new DEQUEUE_TEST_BUILDER KEY_GENERIC_TYPE().usingGenerator(builder);
} }
@Override @Override
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
protected List<Class<? extends AbstractTester>> getTesters() { protected List<Class<? extends AbstractTester>> getTesters() {
List<Class<? extends AbstractTester>> tester = super.getTesters(); List<Class<? extends AbstractTester>> tester = super.getTesters();
tester.add(FILE_KEY_TYPEDequeueDequeueTester.class); tester.add(FILE_KEY_TYPEDequeueDequeueTester.class);
tester.add(FILE_KEY_TYPEDequeueEnqueueTester.class); tester.add(FILE_KEY_TYPEDequeueEnqueueTester.class);
tester.add(FILE_KEY_TYPEDequeueLastTester.class); tester.add(FILE_KEY_TYPEDequeueLastTester.class);
return tester; return tester;
} }
} }
@@ -1,384 +1,384 @@
package speiger.src.testers.PACKAGE.builder; package speiger.src.testers.PACKAGE.builder;
#ignore #ignore
import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; 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;
import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS; import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS;
#endignore #endignore
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import com.google.common.collect.testing.AbstractTester; import com.google.common.collect.testing.AbstractTester;
import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder; import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder;
import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.ListTestSuiteBuilder; import com.google.common.collect.testing.ListTestSuiteBuilder;
import com.google.common.collect.testing.OneSizeTestContainerGenerator; import com.google.common.collect.testing.OneSizeTestContainerGenerator;
import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.SampleElements;
import com.google.common.collect.testing.TestListGenerator; import com.google.common.collect.testing.TestListGenerator;
import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.Feature; import com.google.common.collect.testing.features.Feature;
import com.google.common.collect.testing.testers.CollectionSerializationEqualTester; import com.google.common.collect.testing.testers.CollectionSerializationEqualTester;
import com.google.common.collect.testing.testers.ListAddAllAtIndexTester; import com.google.common.collect.testing.testers.ListAddAllAtIndexTester;
import com.google.common.collect.testing.testers.ListAddAllTester; import com.google.common.collect.testing.testers.ListAddAllTester;
import com.google.common.collect.testing.testers.ListAddAtIndexTester; import com.google.common.collect.testing.testers.ListAddAtIndexTester;
import com.google.common.collect.testing.testers.ListAddTester; import com.google.common.collect.testing.testers.ListAddTester;
import com.google.common.collect.testing.testers.ListCreationTester; import com.google.common.collect.testing.testers.ListCreationTester;
import com.google.common.collect.testing.testers.ListEqualsTester; import com.google.common.collect.testing.testers.ListEqualsTester;
import com.google.common.collect.testing.testers.ListGetTester; import com.google.common.collect.testing.testers.ListGetTester;
import com.google.common.collect.testing.testers.ListHashCodeTester; import com.google.common.collect.testing.testers.ListHashCodeTester;
import com.google.common.collect.testing.testers.ListIndexOfTester; import com.google.common.collect.testing.testers.ListIndexOfTester;
import com.google.common.collect.testing.testers.ListLastIndexOfTester; import com.google.common.collect.testing.testers.ListLastIndexOfTester;
import com.google.common.collect.testing.testers.ListRemoveAllTester; import com.google.common.collect.testing.testers.ListRemoveAllTester;
import com.google.common.collect.testing.testers.ListRemoveAtIndexTester; import com.google.common.collect.testing.testers.ListRemoveAtIndexTester;
import com.google.common.collect.testing.testers.ListRemoveTester; import com.google.common.collect.testing.testers.ListRemoveTester;
import com.google.common.collect.testing.testers.ListReplaceAllTester; import com.google.common.collect.testing.testers.ListReplaceAllTester;
import com.google.common.collect.testing.testers.ListRetainAllTester; import com.google.common.collect.testing.testers.ListRetainAllTester;
import com.google.common.collect.testing.testers.ListSetTester; import com.google.common.collect.testing.testers.ListSetTester;
import com.google.common.collect.testing.testers.ListSubListTester; import com.google.common.collect.testing.testers.ListSubListTester;
import com.google.common.collect.testing.testers.ListToArrayTester; import com.google.common.collect.testing.testers.ListToArrayTester;
import com.google.common.testing.SerializableTester; import com.google.common.testing.SerializableTester;
import junit.framework.TestSuite; import junit.framework.TestSuite;
import speiger.src.collections.PACKAGE.collections.ITERABLE; import speiger.src.collections.PACKAGE.collections.ITERABLE;
import speiger.src.collections.PACKAGE.lists.LIST; import speiger.src.collections.PACKAGE.lists.LIST;
import speiger.src.testers.base.tests.list.JavaListListIteratorTester; import speiger.src.testers.base.tests.list.JavaListListIteratorTester;
import speiger.src.testers.PACKAGE.generators.TEST_LIST_GENERATOR; 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_TYPEListAbsentTester;
import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListAddAllArrayAtIndexTester; 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_TYPEListAddAllAtIndexTester;
import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListAddAllListAtIndexTester; 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_TYPEListAddAllTester;
import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListAddAtIndexTester; 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_TYPEListAddTester;
import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListCreationTester; 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_TYPEListEqualsTester;
import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListExtractElementsTester; 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_TYPEListGetElementsTester;
import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListGetTester; 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_TYPEListIndexOfTester;
import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListLastIndexOfTester; 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_TYPEListListIteratorTester;
import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListPresentTester; 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_TYPEListRemoveAllTester;
import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListRemoveAtIndexTester; 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_TYPEListRemoveElementsTester;
import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListRemoveTester; import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListRemoveTester;
#if !TYPE_BOOLEAN #if !TYPE_BOOLEAN
import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListSortTester; import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListSortTester;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListFillBufferTester; import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListFillBufferTester;
#endif #endif
import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListReplaceAllTester; import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListReplaceAllTester;
#endif #endif
import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListRetainAllTester; 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_TYPEListSetTester;
import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListSubListTester; 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_TYPEListSwapRemoveAtIndexTester;
import speiger.src.testers.PACKAGE.tests.list.FILE_KEY_TYPEListSwapRemoveTester; 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.tests.list.FILE_KEY_TYPEListToArrayTester;
import speiger.src.testers.PACKAGE.utils.SAMPLE_ELEMENTS; import speiger.src.testers.PACKAGE.utils.SAMPLE_ELEMENTS;
#if !TYPE_BOOLEAN #if !TYPE_BOOLEAN
import speiger.src.testers.utils.SpecialFeature; import speiger.src.testers.utils.SpecialFeature;
#endif #endif
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class LIST_TEST_BUILDER KEY_GENERIC_TYPE extends COLLECTION_TEST_BUILDER KEY_GENERIC_TYPE { public class LIST_TEST_BUILDER KEY_GENERIC_TYPE extends COLLECTION_TEST_BUILDER KEY_GENERIC_TYPE {
#if TYPE_OBJECT #if TYPE_OBJECT
KEY_TYPE[] prefixes; KEY_TYPE[] prefixes;
KEY_TYPE[] suffixes; KEY_TYPE[] suffixes;
#else #else
KEY_TYPE[] prefixes = createPrefixes(); KEY_TYPE[] prefixes = createPrefixes();
KEY_TYPE[] suffixes = createSuffixes(); KEY_TYPE[] suffixes = createSuffixes();
#endif #endif
public static GENERIC_KEY_BRACES LIST_TEST_BUILDER KEY_GENERIC_TYPE using(TEST_LIST_GENERATOR KEY_GENERIC_TYPE generator) { 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); 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) { public LIST_TEST_BUILDER KEY_GENERIC_TYPE setPrefixes(KEY_TYPE[] prefixes) {
this.prefixes = prefixes; this.prefixes = prefixes;
return this; return this;
} }
public LIST_TEST_BUILDER KEY_GENERIC_TYPE setSuffixes(KEY_TYPE[] suffixes) { public LIST_TEST_BUILDER KEY_GENERIC_TYPE setSuffixes(KEY_TYPE[] suffixes) {
this.suffixes = suffixes; this.suffixes = suffixes;
return this; return this;
} }
#if !TYPE_OBJECT #if !TYPE_OBJECT
public KEY_TYPE[] createPrefixes() { public KEY_TYPE[] createPrefixes() {
#if TYPE_BOOLEAN #if TYPE_BOOLEAN
return new KEY_TYPE[]{false, false, false}; return new KEY_TYPE[]{false, false, false};
#else if TYPE_BYTE #else if TYPE_BYTE
return new KEY_TYPE[]{(byte)-3, (byte)-2, (byte)-1}; return new KEY_TYPE[]{(byte)-3, (byte)-2, (byte)-1};
#else if TYPE_SHORT #else if TYPE_SHORT
return new KEY_TYPE[]{(short)-3, (short)-2, (short)-1}; return new KEY_TYPE[]{(short)-3, (short)-2, (short)-1};
#else if TYPE_CHAR #else if TYPE_CHAR
return new KEY_TYPE[]{'^', '_', '`'}; return new KEY_TYPE[]{'^', '_', '`'};
#else #else
return new KEY_TYPE[]{-3, -2, -1}; return new KEY_TYPE[]{-3, -2, -1};
#endif #endif
} }
public KEY_TYPE[] createSuffixes() { public KEY_TYPE[] createSuffixes() {
#if TYPE_BOOLEAN #if TYPE_BOOLEAN
return new KEY_TYPE[]{true, true, true}; return new KEY_TYPE[]{true, true, true};
#else if TYPE_BYTE #else if TYPE_BYTE
return new KEY_TYPE[]{(byte)5, (byte)6, (byte)7}; return new KEY_TYPE[]{(byte)5, (byte)6, (byte)7};
#else if TYPE_SHORT #else if TYPE_SHORT
return new KEY_TYPE[]{(short)5, (short)6, (short)7}; return new KEY_TYPE[]{(short)5, (short)6, (short)7};
#else if TYPE_CHAR #else if TYPE_CHAR
return new KEY_TYPE[]{'f', 'g', 'h'}; return new KEY_TYPE[]{'f', 'g', 'h'};
#else #else
return new KEY_TYPE[]{5, 6, 7}; return new KEY_TYPE[]{5, 6, 7};
#endif #endif
} }
#endif #endif
@Override @Override
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
protected List<Class<? extends AbstractTester>> getTesters() { protected List<Class<? extends AbstractTester>> getTesters() {
List<Class<? extends AbstractTester>> testers = Helpers.copyToList(super.getTesters()); List<Class<? extends AbstractTester>> testers = Helpers.copyToList(super.getTesters());
testers.add(CollectionSerializationEqualTester.class); testers.add(CollectionSerializationEqualTester.class);
testers.add(ListAddAllAtIndexTester.class); testers.add(ListAddAllAtIndexTester.class);
testers.add(ListAddAllTester.class); testers.add(ListAddAllTester.class);
testers.add(ListAddAtIndexTester.class); testers.add(ListAddAtIndexTester.class);
testers.add(ListAddTester.class); testers.add(ListAddTester.class);
testers.add(ListCreationTester.class); testers.add(ListCreationTester.class);
testers.add(ListEqualsTester.class); testers.add(ListEqualsTester.class);
testers.add(ListGetTester.class); testers.add(ListGetTester.class);
testers.add(ListHashCodeTester.class); testers.add(ListHashCodeTester.class);
testers.add(ListIndexOfTester.class); testers.add(ListIndexOfTester.class);
testers.add(ListLastIndexOfTester.class); testers.add(ListLastIndexOfTester.class);
testers.add(JavaListListIteratorTester.class); testers.add(JavaListListIteratorTester.class);
testers.add(ListRemoveAllTester.class); testers.add(ListRemoveAllTester.class);
testers.add(ListRemoveAtIndexTester.class); testers.add(ListRemoveAtIndexTester.class);
testers.add(ListRemoveTester.class); testers.add(ListRemoveTester.class);
testers.add(ListReplaceAllTester.class); testers.add(ListReplaceAllTester.class);
testers.add(ListRetainAllTester.class); testers.add(ListRetainAllTester.class);
testers.add(ListSetTester.class); testers.add(ListSetTester.class);
testers.add(ListSubListTester.class); testers.add(ListSubListTester.class);
testers.add(ListToArrayTester.class); testers.add(ListToArrayTester.class);
testers.add(FILE_KEY_TYPEListAddAllAtIndexTester.class); testers.add(FILE_KEY_TYPEListAddAllAtIndexTester.class);
testers.add(FILE_KEY_TYPEListAddAllListAtIndexTester.class); testers.add(FILE_KEY_TYPEListAddAllListAtIndexTester.class);
testers.add(FILE_KEY_TYPEListAddAllArrayAtIndexTester.class); testers.add(FILE_KEY_TYPEListAddAllArrayAtIndexTester.class);
testers.add(FILE_KEY_TYPEListAddAllTester.class); testers.add(FILE_KEY_TYPEListAddAllTester.class);
testers.add(FILE_KEY_TYPEListAddAtIndexTester.class); testers.add(FILE_KEY_TYPEListAddAtIndexTester.class);
testers.add(FILE_KEY_TYPEListAddTester.class); testers.add(FILE_KEY_TYPEListAddTester.class);
testers.add(FILE_KEY_TYPEListAbsentTester.class); testers.add(FILE_KEY_TYPEListAbsentTester.class);
testers.add(FILE_KEY_TYPEListPresentTester.class); testers.add(FILE_KEY_TYPEListPresentTester.class);
testers.add(FILE_KEY_TYPEListCreationTester.class); testers.add(FILE_KEY_TYPEListCreationTester.class);
testers.add(FILE_KEY_TYPEListEqualsTester.class); testers.add(FILE_KEY_TYPEListEqualsTester.class);
testers.add(FILE_KEY_TYPEListGetTester.class); testers.add(FILE_KEY_TYPEListGetTester.class);
testers.add(FILE_KEY_TYPEListGetElementsTester.class); testers.add(FILE_KEY_TYPEListGetElementsTester.class);
testers.add(FILE_KEY_TYPEListExtractElementsTester.class); testers.add(FILE_KEY_TYPEListExtractElementsTester.class);
testers.add(FILE_KEY_TYPEListIndexOfTester.class); testers.add(FILE_KEY_TYPEListIndexOfTester.class);
testers.add(FILE_KEY_TYPEListLastIndexOfTester.class); testers.add(FILE_KEY_TYPEListLastIndexOfTester.class);
testers.add(FILE_KEY_TYPEListListIteratorTester.class); testers.add(FILE_KEY_TYPEListListIteratorTester.class);
testers.add(FILE_KEY_TYPEListRemoveAllTester.class); testers.add(FILE_KEY_TYPEListRemoveAllTester.class);
testers.add(FILE_KEY_TYPEListRemoveAtIndexTester.class); testers.add(FILE_KEY_TYPEListRemoveAtIndexTester.class);
testers.add(FILE_KEY_TYPEListRemoveTester.class); testers.add(FILE_KEY_TYPEListRemoveTester.class);
testers.add(FILE_KEY_TYPEListRemoveElementsTester.class); testers.add(FILE_KEY_TYPEListRemoveElementsTester.class);
testers.add(FILE_KEY_TYPEListSwapRemoveAtIndexTester.class); testers.add(FILE_KEY_TYPEListSwapRemoveAtIndexTester.class);
testers.add(FILE_KEY_TYPEListSwapRemoveTester.class); testers.add(FILE_KEY_TYPEListSwapRemoveTester.class);
#if !TYPE_BOOLEAN #if !TYPE_BOOLEAN
testers.add(FILE_KEY_TYPEListSortTester.class); testers.add(FILE_KEY_TYPEListSortTester.class);
#if !TYPE_OBJECT #if !TYPE_OBJECT
testers.add(FILE_KEY_TYPEListFillBufferTester.class); testers.add(FILE_KEY_TYPEListFillBufferTester.class);
#endif #endif
testers.add(FILE_KEY_TYPEListReplaceAllTester.class); testers.add(FILE_KEY_TYPEListReplaceAllTester.class);
#endif #endif
testers.add(FILE_KEY_TYPEListRetainAllTester.class); testers.add(FILE_KEY_TYPEListRetainAllTester.class);
testers.add(FILE_KEY_TYPEListSetTester.class); testers.add(FILE_KEY_TYPEListSetTester.class);
testers.add(FILE_KEY_TYPEListSubListTester.class); testers.add(FILE_KEY_TYPEListSubListTester.class);
testers.add(FILE_KEY_TYPEListToArrayTester.class); testers.add(FILE_KEY_TYPEListToArrayTester.class);
return testers; return testers;
} }
@Override @Override
public TestSuite createTestSuite() { public TestSuite createTestSuite() {
#ignore #ignore
withFeatures(KNOWN_ORDER); withFeatures(KNOWN_ORDER);
#endignore #endignore
return super.createTestSuite(); return super.createTestSuite();
} }
@Override @Override
protected List<TestSuite> createDerivedSuites(FeatureSpecificTestSuiteBuilder<?, ? extends OneSizeTestContainerGenerator<Collection<CLASS_TYPE>, CLASS_TYPE>> parentBuilder) { protected List<TestSuite> createDerivedSuites(FeatureSpecificTestSuiteBuilder<?, ? extends OneSizeTestContainerGenerator<Collection<CLASS_TYPE>, CLASS_TYPE>> parentBuilder) {
List<TestSuite> derivedSuites = new ArrayList<>(super.createDerivedSuites(parentBuilder)); List<TestSuite> derivedSuites = new ArrayList<>(super.createDerivedSuites(parentBuilder));
#ignore #ignore
if (parentBuilder.getFeatures().contains(SERIALIZABLE)) { if (parentBuilder.getFeatures().contains(SERIALIZABLE)) {
#endignore #endignore
derivedSuites.add(ListTestSuiteBuilder.using(new ReserializedListGenerator<CLASS_TYPE>(parentBuilder.getSubjectGenerator())) derivedSuites.add(ListTestSuiteBuilder.using(new ReserializedListGenerator<CLASS_TYPE>(parentBuilder.getSubjectGenerator()))
.named(getName() + " reserialized") .named(getName() + " reserialized")
.withFeatures(computeReserializedCollectionFeatures(parentBuilder.getFeatures())) .withFeatures(computeReserializedCollectionFeatures(parentBuilder.getFeatures()))
.suppressing(parentBuilder.getSuppressedTests()).withSetUp(parentBuilder.getSetUp()) .suppressing(parentBuilder.getSuppressedTests()).withSetUp(parentBuilder.getSetUp())
.withTearDown(parentBuilder.getTearDown()).createTestSuite()); .withTearDown(parentBuilder.getTearDown()).createTestSuite());
} }
#ignore #ignore
if(!parentBuilder.getFeatures().contains(CollectionFeature.SUBSET_VIEW)) { if(!parentBuilder.getFeatures().contains(CollectionFeature.SUBSET_VIEW)) {
#endignore #endignore
#if !TYPE_BOOLEAN #if !TYPE_BOOLEAN
if(prefixes != null) { if(prefixes != null) {
derivedSuites.add(LIST_TEST_BUILDER.using(new SubListListGeneratorBRACES(parentBuilder.getSubjectGenerator(), prefixes, null)) derivedSuites.add(LIST_TEST_BUILDER.using(new SubListListGeneratorBRACES(parentBuilder.getSubjectGenerator(), prefixes, null))
.named(getName() + " subSet_prefix") .named(getName() + " subSet_prefix")
.withFeatures(computeSubListFeatures(parentBuilder.getFeatures())) .withFeatures(computeSubListFeatures(parentBuilder.getFeatures()))
.suppressing(parentBuilder.getSuppressedTests()).withSetUp(parentBuilder.getSetUp()) .suppressing(parentBuilder.getSuppressedTests()).withSetUp(parentBuilder.getSetUp())
.withTearDown(parentBuilder.getTearDown()).createTestSuite()); .withTearDown(parentBuilder.getTearDown()).createTestSuite());
} }
if(suffixes != null) { if(suffixes != null) {
derivedSuites.add(LIST_TEST_BUILDER.using(new SubListListGeneratorBRACES(parentBuilder.getSubjectGenerator(), null, suffixes)) derivedSuites.add(LIST_TEST_BUILDER.using(new SubListListGeneratorBRACES(parentBuilder.getSubjectGenerator(), null, suffixes))
.named(getName() + " subSet_suffixes") .named(getName() + " subSet_suffixes")
.withFeatures(computeSubListFeatures(parentBuilder.getFeatures())) .withFeatures(computeSubListFeatures(parentBuilder.getFeatures()))
.suppressing(parentBuilder.getSuppressedTests()).withSetUp(parentBuilder.getSetUp()) .suppressing(parentBuilder.getSuppressedTests()).withSetUp(parentBuilder.getSetUp())
.withTearDown(parentBuilder.getTearDown()).createTestSuite()); .withTearDown(parentBuilder.getTearDown()).createTestSuite());
} }
if(prefixes != null && suffixes != null) { if(prefixes != null && suffixes != null) {
derivedSuites.add(LIST_TEST_BUILDER.using(new SubListListGeneratorBRACES(parentBuilder.getSubjectGenerator(), prefixes, suffixes)) derivedSuites.add(LIST_TEST_BUILDER.using(new SubListListGeneratorBRACES(parentBuilder.getSubjectGenerator(), prefixes, suffixes))
.named(getName() + " subSet") .named(getName() + " subSet")
.withFeatures(computeSubListFeatures(parentBuilder.getFeatures())) .withFeatures(computeSubListFeatures(parentBuilder.getFeatures()))
.suppressing(parentBuilder.getSuppressedTests()).withSetUp(parentBuilder.getSetUp()) .suppressing(parentBuilder.getSuppressedTests()).withSetUp(parentBuilder.getSetUp())
.withTearDown(parentBuilder.getTearDown()).createTestSuite()); .withTearDown(parentBuilder.getTearDown()).createTestSuite());
} }
#endif #endif
} }
return derivedSuites; return derivedSuites;
} }
static class SubListListGenerator KEY_GENERIC_TYPE implements TEST_LIST_GENERATOR KEY_GENERIC_TYPE { static class SubListListGenerator KEY_GENERIC_TYPE implements TEST_LIST_GENERATOR KEY_GENERIC_TYPE {
TEST_LIST_GENERATOR KEY_GENERIC_TYPE generator; TEST_LIST_GENERATOR KEY_GENERIC_TYPE generator;
KEY_TYPE[] prefix; KEY_TYPE[] prefix;
KEY_TYPE[] suffix; KEY_TYPE[] suffix;
public SubListListGenerator(OneSizeTestContainerGenerator<Collection<CLASS_TYPE>, CLASS_TYPE> gen, KEY_TYPE[] prefix, KEY_TYPE[] suffix) { public SubListListGenerator(OneSizeTestContainerGenerator<Collection<CLASS_TYPE>, CLASS_TYPE> gen, KEY_TYPE[] prefix, KEY_TYPE[] suffix) {
generator = (TEST_LIST_GENERATOR KEY_GENERIC_TYPE)gen.getInnerGenerator(); generator = (TEST_LIST_GENERATOR KEY_GENERIC_TYPE)gen.getInnerGenerator();
this.prefix = prefix; this.prefix = prefix;
this.suffix = suffix; this.suffix = suffix;
} }
@Override @Override
public SampleElements<CLASS_TYPE> samples() { public SampleElements<CLASS_TYPE> samples() {
return generator.samples(); return generator.samples();
} }
@Override @Override
public CLASS_TYPE[] createArray(int length) { public CLASS_TYPE[] createArray(int length) {
return generator.createArray(length); return generator.createArray(length);
} }
@Override @Override
public Iterable<CLASS_TYPE> order(List<CLASS_TYPE> insertionOrder) { public Iterable<CLASS_TYPE> order(List<CLASS_TYPE> insertionOrder) {
return generator.order(insertionOrder); return generator.order(insertionOrder);
} }
@Override @Override
public SAMPLE_ELEMENTS KEY_GENERIC_TYPE getSamples() { public SAMPLE_ELEMENTS KEY_GENERIC_TYPE getSamples() {
return generator.getSamples(); return generator.getSamples();
} }
@Override @Override
public ITERABLE KEY_GENERIC_TYPE order(LIST KEY_GENERIC_TYPE insertionOrder) { public ITERABLE KEY_GENERIC_TYPE order(LIST KEY_GENERIC_TYPE insertionOrder) {
return generator.order(insertionOrder); return generator.order(insertionOrder);
} }
#if !TYPE_OBJECT #if !TYPE_OBJECT
@Override @Override
public LIST KEY_GENERIC_TYPE create(Object... elements) { public LIST KEY_GENERIC_TYPE create(Object... elements) {
KEY_TYPE[] array = NEW_KEY_ARRAY(elements.length); KEY_TYPE[] array = NEW_KEY_ARRAY(elements.length);
int i = 0; int i = 0;
for (Object e : elements) { for (Object e : elements) {
array[i++] = CLASS_TO_KEY(e); array[i++] = CLASS_TO_KEY(e);
} }
return create(array); return create(array);
} }
@Override @Override
public LIST KEY_GENERIC_TYPE create(KEY_TYPE... elements) { public LIST KEY_GENERIC_TYPE create(KEY_TYPE... elements) {
int length = getLength(prefix); int length = getLength(prefix);
return generator.create(merge(elements)).subList(length, length+elements.length); return generator.create(merge(elements)).subList(length, length+elements.length);
} }
#else #else
@Override @Override
public LIST KEY_GENERIC_TYPE create(Object... elements) { public LIST KEY_GENERIC_TYPE create(Object... elements) {
KEY_TYPE[] array = NEW_KEY_ARRAY(elements.length); KEY_TYPE[] array = NEW_KEY_ARRAY(elements.length);
int i = 0; int i = 0;
for (Object e : elements) { for (Object e : elements) {
array[i++] = CLASS_TO_KEY(e); array[i++] = CLASS_TO_KEY(e);
} }
int length = getLength(prefix); int length = getLength(prefix);
return generator.create(merge(array)).subList(length, length+elements.length); return generator.create(merge(array)).subList(length, length+elements.length);
} }
#endif #endif
private int getLength(KEY_TYPE[] keys) { private int getLength(KEY_TYPE[] keys) {
return keys == null ? 0 : keys.length; return keys == null ? 0 : keys.length;
} }
private KEY_TYPE[] merge(KEY_TYPE[] input) { private KEY_TYPE[] merge(KEY_TYPE[] input) {
int prefixLength = getLength(prefix); int prefixLength = getLength(prefix);
int suffixLength = getLength(suffix); int suffixLength = getLength(suffix);
KEY_TYPE[] result = NEW_KEY_ARRAY(input.length+prefixLength+suffixLength); KEY_TYPE[] result = NEW_KEY_ARRAY(input.length+prefixLength+suffixLength);
if(prefixLength != 0) System.arraycopy(prefix, 0, result, 0, prefixLength); if(prefixLength != 0) System.arraycopy(prefix, 0, result, 0, prefixLength);
System.arraycopy(input, 0, result, prefixLength, input.length); System.arraycopy(input, 0, result, prefixLength, input.length);
if(suffixLength != 0) System.arraycopy(suffix, 0, result, prefixLength+input.length, suffixLength); if(suffixLength != 0) System.arraycopy(suffix, 0, result, prefixLength+input.length, suffixLength);
return result; return result;
} }
} }
static class ReserializedListGenerator<E> implements TestListGenerator<E> { static class ReserializedListGenerator<E> implements TestListGenerator<E> {
final OneSizeTestContainerGenerator<Collection<E>, E> gen; final OneSizeTestContainerGenerator<Collection<E>, E> gen;
private ReserializedListGenerator(OneSizeTestContainerGenerator<Collection<E>, E> gen) { private ReserializedListGenerator(OneSizeTestContainerGenerator<Collection<E>, E> gen) {
this.gen = gen; this.gen = gen;
} }
@Override @Override
public SampleElements<E> samples() { public SampleElements<E> samples() {
return gen.samples(); return gen.samples();
} }
@Override @Override
public List<E> create(Object... elements) { public List<E> create(Object... elements) {
return (List<E>) SerializableTester.reserialize(gen.create(elements)); return (List<E>) SerializableTester.reserialize(gen.create(elements));
} }
@Override @Override
public E[] createArray(int length) { public E[] createArray(int length) {
return gen.createArray(length); return gen.createArray(length);
} }
@Override @Override
public Iterable<E> order(List<E> insertionOrder) { public Iterable<E> order(List<E> insertionOrder) {
return gen.order(insertionOrder); return gen.order(insertionOrder);
} }
} }
#if !TYPE_BOOLEAN #if !TYPE_BOOLEAN
private static Set<Feature<?>> computeSubListFeatures(Set<Feature<?>> features) { private static Set<Feature<?>> computeSubListFeatures(Set<Feature<?>> features) {
Set<Feature<?>> derivedFeatures = new HashSet<>(features); Set<Feature<?>> derivedFeatures = new HashSet<>(features);
#ignore #ignore
derivedFeatures.add(CollectionFeature.SUBSET_VIEW); derivedFeatures.add(CollectionFeature.SUBSET_VIEW);
derivedFeatures.remove(SpecialFeature.COPYING); derivedFeatures.remove(SpecialFeature.COPYING);
derivedFeatures.remove(SpecialFeature.CHILDREN_COPY); derivedFeatures.remove(SpecialFeature.CHILDREN_COPY);
#endignore #endignore
return derivedFeatures; return derivedFeatures;
} }
#endif #endif
private static Set<Feature<?>> computeReserializedCollectionFeatures(Set<Feature<?>> features) { private static Set<Feature<?>> computeReserializedCollectionFeatures(Set<Feature<?>> features) {
Set<Feature<?>> derivedFeatures = new HashSet<>(features); Set<Feature<?>> derivedFeatures = new HashSet<>(features);
#ignore #ignore
derivedFeatures.remove(SERIALIZABLE); derivedFeatures.remove(SERIALIZABLE);
derivedFeatures.remove(SERIALIZABLE_INCLUDING_VIEWS); derivedFeatures.remove(SERIALIZABLE_INCLUDING_VIEWS);
#endignore #endignore
return derivedFeatures; return derivedFeatures;
} }
} }
@@ -1,140 +1,140 @@
package speiger.src.testers.PACKAGE.builder; package speiger.src.testers.PACKAGE.builder;
#ignore #ignore
import static com.google.common.collect.testing.features.CollectionFeature.DESCENDING_VIEW; import static com.google.common.collect.testing.features.CollectionFeature.DESCENDING_VIEW;
import static com.google.common.collect.testing.features.CollectionFeature.SUBSET_VIEW; import static com.google.common.collect.testing.features.CollectionFeature.SUBSET_VIEW;
#endignore #endignore
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import com.google.common.collect.testing.AbstractTester; import com.google.common.collect.testing.AbstractTester;
import com.google.common.collect.testing.DerivedCollectionGenerators.Bound; import com.google.common.collect.testing.DerivedCollectionGenerators.Bound;
import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder; import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder;
import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.OneSizeTestContainerGenerator; import com.google.common.collect.testing.OneSizeTestContainerGenerator;
import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.SampleElements;
import com.google.common.collect.testing.features.Feature; import com.google.common.collect.testing.features.Feature;
import com.google.common.collect.testing.testers.NavigableSetNavigationTester; import com.google.common.collect.testing.testers.NavigableSetNavigationTester;
import junit.framework.TestSuite; import junit.framework.TestSuite;
import speiger.src.collections.PACKAGE.collections.ITERABLE; import speiger.src.collections.PACKAGE.collections.ITERABLE;
import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; import speiger.src.collections.PACKAGE.lists.ARRAY_LIST;
import speiger.src.collections.PACKAGE.lists.LIST; import speiger.src.collections.PACKAGE.lists.LIST;
import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET; import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET;
import speiger.src.collections.PACKAGE.utils.LISTS; import speiger.src.collections.PACKAGE.utils.LISTS;
import speiger.src.testers.PACKAGE.generators.TEST_NAVIGABLE_SET_GENERATOR; 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.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.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.tests.set.FILE_KEY_TYPENavigableSetNavigationTester;
import speiger.src.testers.PACKAGE.utils.SAMPLE_ELEMENTS; import speiger.src.testers.PACKAGE.utils.SAMPLE_ELEMENTS;
import speiger.src.testers.utils.SpecialFeature; import speiger.src.testers.utils.SpecialFeature;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class NAVIGABLE_SET_TEST_BUILDER KEY_GENERIC_TYPE extends SORTED_SET_TEST_BUILDER KEY_GENERIC_TYPE { 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) { 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); return (NAVIGABLE_SET_TEST_BUILDER KEY_GENERIC_TYPE) new NAVIGABLE_SET_TEST_BUILDER KEY_GENERIC_TYPE().usingGenerator(generator);
} }
@Override @Override
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
protected List<Class<? extends AbstractTester>> getTesters() { protected List<Class<? extends AbstractTester>> getTesters() {
List<Class<? extends AbstractTester>> testers = Helpers.copyToList(super.getTesters()); List<Class<? extends AbstractTester>> testers = Helpers.copyToList(super.getTesters());
testers.add(NavigableSetNavigationTester.class); testers.add(NavigableSetNavigationTester.class);
testers.add(FILE_KEY_TYPENavigableSetNavigationTester.class); testers.add(FILE_KEY_TYPENavigableSetNavigationTester.class);
return testers; return testers;
} }
@Override @Override
protected List<TestSuite> createDerivedSuites(FeatureSpecificTestSuiteBuilder<?, ? extends OneSizeTestContainerGenerator<Collection<CLASS_TYPE>, CLASS_TYPE>> parentBuilder) { protected List<TestSuite> createDerivedSuites(FeatureSpecificTestSuiteBuilder<?, ? extends OneSizeTestContainerGenerator<Collection<CLASS_TYPE>, CLASS_TYPE>> parentBuilder) {
List<TestSuite> derivedSuites = new ArrayList<>(super.createDerivedSuites(parentBuilder)); List<TestSuite> derivedSuites = new ArrayList<>(super.createDerivedSuites(parentBuilder));
#ignore #ignore
if (!parentBuilder.getFeatures().contains(SUBSET_VIEW)) { if (!parentBuilder.getFeatures().contains(SUBSET_VIEW)) {
#endignore #endignore
// Other combinations are inherited from SortedSetTestSuiteBuilder. // Other combinations are inherited from SortedSetTestSuiteBuilder.
derivedSuites.add(createSubsetSuite(parentBuilder, Bound.NO_BOUND, Bound.INCLUSIVE)); 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.NO_BOUND));
derivedSuites.add(createSubsetSuite(parentBuilder, Bound.EXCLUSIVE, Bound.EXCLUSIVE)); derivedSuites.add(createSubsetSuite(parentBuilder, Bound.EXCLUSIVE, Bound.EXCLUSIVE));
derivedSuites.add(createSubsetSuite(parentBuilder, Bound.EXCLUSIVE, Bound.INCLUSIVE)); derivedSuites.add(createSubsetSuite(parentBuilder, Bound.EXCLUSIVE, Bound.INCLUSIVE));
derivedSuites.add(createSubsetSuite(parentBuilder, Bound.INCLUSIVE, Bound.INCLUSIVE)); derivedSuites.add(createSubsetSuite(parentBuilder, Bound.INCLUSIVE, Bound.INCLUSIVE));
} }
#ignore #ignore
if (!parentBuilder.getFeatures().contains(DESCENDING_VIEW)) { if (!parentBuilder.getFeatures().contains(DESCENDING_VIEW)) {
#endignore #endignore
derivedSuites.add(createDescendingSuite(parentBuilder)); derivedSuites.add(createDescendingSuite(parentBuilder));
} }
return derivedSuites; return derivedSuites;
} }
@Override @Override
SORTED_SET_TEST_BUILDER KEY_GENERIC_TYPE newBuilderUsing(TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE delegate, Bound to, Bound from) { 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)); return NAVIGABLE_SET_TEST_BUILDER.using(new SUB_NAVIGABLE_SET_CLASS_GENERATORBRACES(delegate, to, from));
} }
private TestSuite createDescendingSuite(FeatureSpecificTestSuiteBuilder<?, ? extends OneSizeTestContainerGenerator<Collection<CLASS_TYPE>, CLASS_TYPE>> parentBuilder) { private TestSuite createDescendingSuite(FeatureSpecificTestSuiteBuilder<?, ? extends OneSizeTestContainerGenerator<Collection<CLASS_TYPE>, CLASS_TYPE>> parentBuilder) {
TEST_NAVIGABLE_SET_GENERATOR KEY_GENERIC_TYPE delegate = (TEST_NAVIGABLE_SET_GENERATOR KEY_GENERIC_TYPE) parentBuilder.getSubjectGenerator().getInnerGenerator(); TEST_NAVIGABLE_SET_GENERATOR KEY_GENERIC_TYPE delegate = (TEST_NAVIGABLE_SET_GENERATOR KEY_GENERIC_TYPE) parentBuilder.getSubjectGenerator().getInnerGenerator();
List<Feature<?>> features = new ArrayList<>(); List<Feature<?>> features = new ArrayList<>();
#ignore #ignore
features.add(DESCENDING_VIEW); features.add(DESCENDING_VIEW);
features.addAll(parentBuilder.getFeatures()); features.addAll(parentBuilder.getFeatures());
features.remove(SpecialFeature.COPYING); features.remove(SpecialFeature.COPYING);
features.remove(SpecialFeature.CHILDREN_COPY); features.remove(SpecialFeature.CHILDREN_COPY);
#endignore #endignore
return NAVIGABLE_SET_TEST_BUILDER.using(new TEST_NAVIGABLE_SET_GENERATOR KEY_GENERIC_TYPE() { return NAVIGABLE_SET_TEST_BUILDER.using(new TEST_NAVIGABLE_SET_GENERATOR KEY_GENERIC_TYPE() {
@Override @Override
public SampleElements<CLASS_TYPE> samples() { public SampleElements<CLASS_TYPE> samples() {
return delegate.samples(); return delegate.samples();
} }
@Override @Override
public SAMPLE_ELEMENTS KEY_GENERIC_TYPE getSamples() { public SAMPLE_ELEMENTS KEY_GENERIC_TYPE getSamples() {
return delegate.getSamples(); return delegate.getSamples();
} }
@Override @Override
public ITERABLE KEY_GENERIC_TYPE order(LIST KEY_GENERIC_TYPE insertionOrder) { public ITERABLE KEY_GENERIC_TYPE order(LIST KEY_GENERIC_TYPE insertionOrder) {
LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES();
delegate.order(insertionOrder).forEach(list::add); delegate.order(insertionOrder).forEach(list::add);
LISTS.reverse(list); LISTS.reverse(list);
return list; return list;
} }
@Override @Override
public Iterable<CLASS_TYPE> order(List<CLASS_TYPE> insertionOrder) { public Iterable<CLASS_TYPE> order(List<CLASS_TYPE> insertionOrder) {
LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES();
for(CLASS_TYPE entry : delegate.order(insertionOrder)) for(CLASS_TYPE entry : delegate.order(insertionOrder))
{ {
list.add(OBJ_TO_KEY(entry)); list.add(OBJ_TO_KEY(entry));
} }
LISTS.reverse(list); LISTS.reverse(list);
return list; return list;
} }
@Override @Override
public KEY_TYPE belowSamplesLesser() { return delegate.aboveSamplesGreater(); } public KEY_TYPE belowSamplesLesser() { return delegate.aboveSamplesGreater(); }
@Override @Override
public KEY_TYPE belowSamplesGreater() { return delegate.aboveSamplesLesser(); } public KEY_TYPE belowSamplesGreater() { return delegate.aboveSamplesLesser(); }
@Override @Override
public KEY_TYPE aboveSamplesLesser() { return delegate.belowSamplesGreater(); } public KEY_TYPE aboveSamplesLesser() { return delegate.belowSamplesGreater(); }
@Override @Override
public KEY_TYPE aboveSamplesGreater() { return delegate.belowSamplesLesser(); } public KEY_TYPE aboveSamplesGreater() { return delegate.belowSamplesLesser(); }
#if !TYPE_OBJECT #if !TYPE_OBJECT
@Override @Override
public NAVIGABLE_SET KEY_GENERIC_TYPE create(KEY_TYPE... elements) { public NAVIGABLE_SET KEY_GENERIC_TYPE create(KEY_TYPE... elements) {
return delegate.create(elements).descendingSet(); return delegate.create(elements).descendingSet();
} }
#endif #endif
@Override @Override
public NAVIGABLE_SET KEY_GENERIC_TYPE create(Object... elements) { public NAVIGABLE_SET KEY_GENERIC_TYPE create(Object... elements) {
return delegate.create(elements).descendingSet(); return delegate.create(elements).descendingSet();
} }
}).named(parentBuilder.getName() + " descending").withFeatures(features) }).named(parentBuilder.getName() + " descending").withFeatures(features)
.suppressing(parentBuilder.getSuppressedTests()).createTestSuite(); .suppressing(parentBuilder.getSuppressedTests()).createTestSuite();
} }
} }
@@ -1,38 +1,115 @@
package speiger.src.testers.PACKAGE.builder; package speiger.src.testers.PACKAGE.builder;
import java.util.List; import java.util.ArrayList;
import java.util.Collection;
import com.google.common.collect.testing.AbstractTester; import java.util.List;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.AbstractTester;
import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder;
import junit.framework.TestSuite; import com.google.common.collect.testing.Helpers;
import speiger.src.testers.PACKAGE.generators.TEST_ORDERED_SET_GENERATOR; import com.google.common.collect.testing.OneSizeTestContainerGenerator;
import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPEOrderedSetMoveTester; import com.google.common.collect.testing.SampleElements;
import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPEOrderedSetIterationTester; import com.google.common.collect.testing.features.CollectionFeature;
import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPEOrderedSetNavigationTester; import com.google.common.collect.testing.features.Feature;
@SuppressWarnings("javadoc") import junit.framework.TestSuite;
public class ORDERED_SET_TEST_BUILDER KEY_GENERIC_TYPE extends SET_TEST_BUILDER KEY_GENERIC_TYPE { import speiger.src.collections.PACKAGE.collections.ITERABLE;
public static GENERIC_KEY_BRACES ORDERED_SET_TEST_BUILDER KEY_GENERIC_TYPE using(TEST_ORDERED_SET_GENERATOR KEY_GENERIC_TYPE generator) { import speiger.src.collections.PACKAGE.lists.ARRAY_LIST;
return (ORDERED_SET_TEST_BUILDER KEY_GENERIC_TYPE) new ORDERED_SET_TEST_BUILDER KEY_GENERIC_TYPE().usingGenerator(generator); import speiger.src.collections.PACKAGE.lists.LIST;
} import speiger.src.collections.PACKAGE.sets.ORDERED_SET;
import speiger.src.collections.PACKAGE.utils.LISTS;
@Override import speiger.src.testers.PACKAGE.generators.TEST_ORDERED_SET_GENERATOR;
@SuppressWarnings("rawtypes") import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPEOrderedSetMoveTester;
protected List<Class<? extends AbstractTester>> getTesters() { import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPEOrderedSetIterationTester;
List<Class<? extends AbstractTester>> testers = Helpers.copyToList(super.getTesters()); import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPEOrderedSetNavigationTester;
testers.add(FILE_KEY_TYPEOrderedSetNavigationTester.class); import speiger.src.testers.PACKAGE.utils.SAMPLE_ELEMENTS;
testers.add(FILE_KEY_TYPEOrderedSetMoveTester.class); import speiger.src.testers.utils.SpecialFeature;
testers.add(FILE_KEY_TYPEOrderedSetIterationTester.class);
return testers; @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) {
@Override return (ORDERED_SET_TEST_BUILDER KEY_GENERIC_TYPE) new ORDERED_SET_TEST_BUILDER KEY_GENERIC_TYPE().usingGenerator(generator);
public TestSuite createTestSuite() { }
#ignore
withFeatures(CollectionFeature.KNOWN_ORDER); @Override
#endignore @SuppressWarnings("rawtypes")
return super.createTestSuite(); protected List<Class<? extends AbstractTester>> getTesters() {
} List<Class<? extends AbstractTester>> 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();
}
@Override
protected List<TestSuite> createDerivedSuites(
FeatureSpecificTestSuiteBuilder<?, ? extends OneSizeTestContainerGenerator<Collection<CLASS_TYPE>, CLASS_TYPE>> parentBuilder) {
List<TestSuite> derivedSuites = super.createDerivedSuites(parentBuilder);
if (!parentBuilder.getFeatures().contains(SpecialFeature.REVERSE)) {
derivedSuites.add(createReverseSuite(parentBuilder));
}
return derivedSuites;
}
private TestSuite createReverseSuite(FeatureSpecificTestSuiteBuilder<?, ? extends OneSizeTestContainerGenerator<Collection<CLASS_TYPE>, CLASS_TYPE>> parentBuilder) {
TEST_ORDERED_SET_GENERATOR KEY_GENERIC_TYPE delegate = (TEST_ORDERED_SET_GENERATOR KEY_GENERIC_TYPE) parentBuilder.getSubjectGenerator().getInnerGenerator();
List<Feature<?>> features = new ArrayList<>();
features.add(SpecialFeature.REVERSE);
features.addAll(parentBuilder.getFeatures());
features.remove(SpecialFeature.COPYING);
features.remove(SpecialFeature.CHILDREN_COPY);
return ORDERED_SET_TEST_BUILDER.using(new TEST_ORDERED_SET_GENERATOR KEY_GENERIC_TYPE() {
@Override
public SampleElements<CLASS_TYPE> 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) {
return insertionOrder;
}
@Override
public Iterable<CLASS_TYPE> order(List<CLASS_TYPE> insertionOrder) {
return insertionOrder;
}
#if !TYPE_OBJECT
@Override
public ORDERED_SET KEY_GENERIC_TYPE create(KEY_TYPE... elements) {
LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(elements);
LISTS.reverse(list);
return delegate.create(list.TO_ARRAY()).reversed();
}
#endif
@Override
public ORDERED_SET KEY_GENERIC_TYPE create(Object... elements) {
LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES();
for (Object e : elements) {
list.add(CLASS_TO_KEY(e));
}
LISTS.reverse(list);
return delegate.create(list.toArray()).reversed();
}
}).named(parentBuilder.getName() + " reversing").withFeatures(features)
.suppressing(parentBuilder.getSuppressedTests()).createTestSuite();
}
}
@@ -1,60 +1,60 @@
package speiger.src.testers.PACKAGE.builder; package speiger.src.testers.PACKAGE.builder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.google.common.collect.testing.AbstractTester; import com.google.common.collect.testing.AbstractTester;
import com.google.common.collect.testing.PerCollectionSizeTestSuiteBuilder; import com.google.common.collect.testing.PerCollectionSizeTestSuiteBuilder;
import speiger.src.collections.PACKAGE.queues.PRIORITY_QUEUE; import speiger.src.collections.PACKAGE.queues.PRIORITY_QUEUE;
import speiger.src.testers.PACKAGE.generators.TEST_QUEUE_GENERATOR; 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_TYPEQueueDequeueTester;
import speiger.src.testers.PACKAGE.tests.queue.FILE_KEY_TYPEQueueEnqueueTester; 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_TYPEQueueFirstTester;
import speiger.src.testers.PACKAGE.tests.queue.FILE_KEY_TYPEQueueRemoveTester; 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_TYPEQueueCountTester;
import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueDistinctTester; 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_TYPEQueueFilterTester;
import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueFindFirstTester; 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_TYPEQueueLimitTester;
import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueMapTester; 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_TYPEQueueMatchesTester;
import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueuePeekTester; 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_TYPEQueueForEachTester;
import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueReduceTester; import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueReduceTester;
import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueSortedTester; import speiger.src.testers.PACKAGE.tests.queue.iterators.FILE_KEY_TYPEQueueSortedTester;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class QUEUE_TEST_BUILDER KEY_GENERIC_TYPE extends PerCollectionSizeTestSuiteBuilder<QUEUE_TEST_BUILDER KEY_GENERIC_TYPE, TEST_QUEUE_GENERATOR KEY_GENERIC_TYPE, PRIORITY_QUEUE KEY_GENERIC_TYPE, CLASS_TYPE> public class QUEUE_TEST_BUILDER KEY_GENERIC_TYPE extends PerCollectionSizeTestSuiteBuilder<QUEUE_TEST_BUILDER KEY_GENERIC_TYPE, TEST_QUEUE_GENERATOR KEY_GENERIC_TYPE, PRIORITY_QUEUE KEY_GENERIC_TYPE, CLASS_TYPE>
{ {
public static GENERIC_KEY_BRACES QUEUE_TEST_BUILDER KEY_GENERIC_TYPE using(TEST_QUEUE_GENERATOR KEY_GENERIC_TYPE builder) { 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); return new QUEUE_TEST_BUILDER KEY_GENERIC_TYPE().usingGenerator(builder);
} }
@Override @Override
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
protected List<Class<? extends AbstractTester>> getTesters() protected List<Class<? extends AbstractTester>> getTesters()
{ {
List<Class<? extends AbstractTester>> testers = new ArrayList<>(); List<Class<? extends AbstractTester>> testers = new ArrayList<>();
testers.add(FILE_KEY_TYPEQueueEnqueueTester.class); testers.add(FILE_KEY_TYPEQueueEnqueueTester.class);
testers.add(FILE_KEY_TYPEQueueDequeueTester.class); testers.add(FILE_KEY_TYPEQueueDequeueTester.class);
testers.add(FILE_KEY_TYPEQueueFirstTester.class); testers.add(FILE_KEY_TYPEQueueFirstTester.class);
testers.add(FILE_KEY_TYPEQueueRemoveTester.class); testers.add(FILE_KEY_TYPEQueueRemoveTester.class);
testers.add(FILE_KEY_TYPEQueueCountTester.class); testers.add(FILE_KEY_TYPEQueueCountTester.class);
testers.add(FILE_KEY_TYPEQueueCountTester.class); testers.add(FILE_KEY_TYPEQueueCountTester.class);
testers.add(FILE_KEY_TYPEQueueDequeueTester.class); testers.add(FILE_KEY_TYPEQueueDequeueTester.class);
testers.add(FILE_KEY_TYPEQueueDistinctTester.class); testers.add(FILE_KEY_TYPEQueueDistinctTester.class);
testers.add(FILE_KEY_TYPEQueueFilterTester.class); testers.add(FILE_KEY_TYPEQueueFilterTester.class);
testers.add(FILE_KEY_TYPEQueueFindFirstTester.class); testers.add(FILE_KEY_TYPEQueueFindFirstTester.class);
testers.add(FILE_KEY_TYPEQueueFirstTester.class); testers.add(FILE_KEY_TYPEQueueFirstTester.class);
testers.add(FILE_KEY_TYPEQueueLimitTester.class); testers.add(FILE_KEY_TYPEQueueLimitTester.class);
testers.add(FILE_KEY_TYPEQueueMapTester.class); testers.add(FILE_KEY_TYPEQueueMapTester.class);
testers.add(FILE_KEY_TYPEQueueMatchesTester.class); testers.add(FILE_KEY_TYPEQueueMatchesTester.class);
testers.add(FILE_KEY_TYPEQueuePeekTester.class); testers.add(FILE_KEY_TYPEQueuePeekTester.class);
testers.add(FILE_KEY_TYPEQueueForEachTester.class); testers.add(FILE_KEY_TYPEQueueForEachTester.class);
testers.add(FILE_KEY_TYPEQueueReduceTester.class); testers.add(FILE_KEY_TYPEQueueReduceTester.class);
testers.add(FILE_KEY_TYPEQueueSortedTester.class); testers.add(FILE_KEY_TYPEQueueSortedTester.class);
return testers; return testers;
} }
} }
@@ -1,116 +1,116 @@
package speiger.src.testers.PACKAGE.builder; package speiger.src.testers.PACKAGE.builder;
#ignore #ignore
import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE; import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE;
import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS; import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS;
#endignore #endignore
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import com.google.common.collect.testing.AbstractTester; import com.google.common.collect.testing.AbstractTester;
import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder; import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder;
import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.OneSizeTestContainerGenerator; import com.google.common.collect.testing.OneSizeTestContainerGenerator;
import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.SampleElements;
import com.google.common.collect.testing.SetTestSuiteBuilder; import com.google.common.collect.testing.SetTestSuiteBuilder;
import com.google.common.collect.testing.TestSetGenerator; import com.google.common.collect.testing.TestSetGenerator;
import com.google.common.collect.testing.features.Feature; import com.google.common.collect.testing.features.Feature;
import com.google.common.collect.testing.testers.CollectionSerializationEqualTester; import com.google.common.collect.testing.testers.CollectionSerializationEqualTester;
import com.google.common.collect.testing.testers.SetAddAllTester; import com.google.common.collect.testing.testers.SetAddAllTester;
import com.google.common.collect.testing.testers.SetAddTester; import com.google.common.collect.testing.testers.SetAddTester;
import com.google.common.collect.testing.testers.SetCreationTester; import com.google.common.collect.testing.testers.SetCreationTester;
import com.google.common.collect.testing.testers.SetEqualsTester; import com.google.common.collect.testing.testers.SetEqualsTester;
import com.google.common.collect.testing.testers.SetHashCodeTester; import com.google.common.collect.testing.testers.SetHashCodeTester;
import com.google.common.collect.testing.testers.SetRemoveTester; import com.google.common.collect.testing.testers.SetRemoveTester;
import com.google.common.testing.SerializableTester; import com.google.common.testing.SerializableTester;
import junit.framework.TestSuite; import junit.framework.TestSuite;
import speiger.src.testers.PACKAGE.generators.TEST_SET_GENERATOR; 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_TYPESetAddAllTester;
import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPESetAddTester; 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_TYPESetCreationTester;
import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPESetEqualsTester; import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPESetEqualsTester;
import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPESetRemoveTester; import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPESetRemoveTester;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class SET_TEST_BUILDER KEY_GENERIC_TYPE extends COLLECTION_TEST_BUILDER KEY_GENERIC_TYPE { 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) { 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); return (SET_TEST_BUILDER KEY_GENERIC_TYPE) new SET_TEST_BUILDER KEY_GENERIC_TYPE().usingGenerator(generator);
} }
@Override @Override
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
protected List<Class<? extends AbstractTester>> getTesters() { protected List<Class<? extends AbstractTester>> getTesters() {
List<Class<? extends AbstractTester>> testers = Helpers.copyToList(super.getTesters()); List<Class<? extends AbstractTester>> testers = Helpers.copyToList(super.getTesters());
testers.add(CollectionSerializationEqualTester.class); testers.add(CollectionSerializationEqualTester.class);
testers.add(SetAddAllTester.class); testers.add(SetAddAllTester.class);
testers.add(SetAddTester.class); testers.add(SetAddTester.class);
testers.add(SetCreationTester.class); testers.add(SetCreationTester.class);
testers.add(SetHashCodeTester.class); testers.add(SetHashCodeTester.class);
testers.add(SetEqualsTester.class); testers.add(SetEqualsTester.class);
testers.add(SetRemoveTester.class); testers.add(SetRemoveTester.class);
testers.add(FILE_KEY_TYPESetAddAllTester.class); testers.add(FILE_KEY_TYPESetAddAllTester.class);
testers.add(FILE_KEY_TYPESetAddTester.class); testers.add(FILE_KEY_TYPESetAddTester.class);
testers.add(FILE_KEY_TYPESetCreationTester.class); testers.add(FILE_KEY_TYPESetCreationTester.class);
testers.add(FILE_KEY_TYPESetEqualsTester.class); testers.add(FILE_KEY_TYPESetEqualsTester.class);
testers.add(FILE_KEY_TYPESetRemoveTester.class); testers.add(FILE_KEY_TYPESetRemoveTester.class);
return testers; return testers;
} }
@Override @Override
protected List<TestSuite> createDerivedSuites( protected List<TestSuite> createDerivedSuites(
FeatureSpecificTestSuiteBuilder<?, ? extends OneSizeTestContainerGenerator<Collection<CLASS_TYPE>, CLASS_TYPE>> parentBuilder) { FeatureSpecificTestSuiteBuilder<?, ? extends OneSizeTestContainerGenerator<Collection<CLASS_TYPE>, CLASS_TYPE>> parentBuilder) {
List<TestSuite> derivedSuites = new ArrayList<>(super.createDerivedSuites(parentBuilder)); List<TestSuite> derivedSuites = new ArrayList<>(super.createDerivedSuites(parentBuilder));
if (parentBuilder.getFeatures().contains(SERIALIZABLE)) { if (parentBuilder.getFeatures().contains(SERIALIZABLE)) {
derivedSuites.add(SetTestSuiteBuilder.using(new ReserializedSetGenerator<CLASS_TYPE>(parentBuilder.getSubjectGenerator())) derivedSuites.add(SetTestSuiteBuilder.using(new ReserializedSetGenerator<CLASS_TYPE>(parentBuilder.getSubjectGenerator()))
.named(getName() + " reserialized") .named(getName() + " reserialized")
.withFeatures(computeReserializedCollectionFeatures(parentBuilder.getFeatures())) .withFeatures(computeReserializedCollectionFeatures(parentBuilder.getFeatures()))
.suppressing(parentBuilder.getSuppressedTests()).withSetUp(parentBuilder.getSetUp()) .suppressing(parentBuilder.getSuppressedTests()).withSetUp(parentBuilder.getSetUp())
.withTearDown(parentBuilder.getTearDown()).createTestSuite()); .withTearDown(parentBuilder.getTearDown()).createTestSuite());
} }
return derivedSuites; return derivedSuites;
} }
static class ReserializedSetGenerator<E> implements TestSetGenerator<E> { static class ReserializedSetGenerator<E> implements TestSetGenerator<E> {
final OneSizeTestContainerGenerator<Collection<E>, E> gen; final OneSizeTestContainerGenerator<Collection<E>, E> gen;
private ReserializedSetGenerator(OneSizeTestContainerGenerator<Collection<E>, E> gen) { private ReserializedSetGenerator(OneSizeTestContainerGenerator<Collection<E>, E> gen) {
this.gen = gen; this.gen = gen;
} }
@Override @Override
public SampleElements<E> samples() { public SampleElements<E> samples() {
return gen.samples(); return gen.samples();
} }
@Override @Override
public Set<E> create(Object... elements) { public Set<E> create(Object... elements) {
return (Set<E>) SerializableTester.reserialize(gen.create(elements)); return (Set<E>) SerializableTester.reserialize(gen.create(elements));
} }
@Override @Override
public E[] createArray(int length) { public E[] createArray(int length) {
return gen.createArray(length); return gen.createArray(length);
} }
@Override @Override
public Iterable<E> order(List<E> insertionOrder) { public Iterable<E> order(List<E> insertionOrder) {
return gen.order(insertionOrder); return gen.order(insertionOrder);
} }
} }
private static Set<Feature<?>> computeReserializedCollectionFeatures(Set<Feature<?>> features) { private static Set<Feature<?>> computeReserializedCollectionFeatures(Set<Feature<?>> features) {
Set<Feature<?>> derivedFeatures = new HashSet<>(features); Set<Feature<?>> derivedFeatures = new HashSet<>(features);
#ignore #ignore
derivedFeatures.remove(SERIALIZABLE); derivedFeatures.remove(SERIALIZABLE);
derivedFeatures.remove(SERIALIZABLE_INCLUDING_VIEWS); derivedFeatures.remove(SERIALIZABLE_INCLUDING_VIEWS);
#endignore #endignore
return derivedFeatures; return derivedFeatures;
} }
} }
@@ -1,88 +1,88 @@
package speiger.src.testers.PACKAGE.builder; package speiger.src.testers.PACKAGE.builder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import com.google.common.collect.testing.AbstractTester; import com.google.common.collect.testing.AbstractTester;
import com.google.common.collect.testing.DerivedCollectionGenerators.Bound; import com.google.common.collect.testing.DerivedCollectionGenerators.Bound;
import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder; import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder;
import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.OneSizeTestContainerGenerator; import com.google.common.collect.testing.OneSizeTestContainerGenerator;
import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.Feature; import com.google.common.collect.testing.features.Feature;
import com.google.common.collect.testing.testers.SortedSetNavigationTester; import com.google.common.collect.testing.testers.SortedSetNavigationTester;
import junit.framework.TestSuite; import junit.framework.TestSuite;
import speiger.src.testers.PACKAGE.generators.TEST_SORTED_SET_GENERATOR; 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.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_TYPESortedSetIterationTester;
import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPESortedSetNaviationTester; import speiger.src.testers.PACKAGE.tests.set.FILE_KEY_TYPESortedSetNaviationTester;
import speiger.src.testers.utils.SpecialFeature; import speiger.src.testers.utils.SpecialFeature;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class SORTED_SET_TEST_BUILDER KEY_GENERIC_TYPE extends SET_TEST_BUILDER KEY_GENERIC_TYPE { 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) { 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); return (SORTED_SET_TEST_BUILDER KEY_GENERIC_TYPE) new SORTED_SET_TEST_BUILDER KEY_GENERIC_TYPE().usingGenerator(generator);
} }
@Override @Override
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
protected List<Class<? extends AbstractTester>> getTesters() { protected List<Class<? extends AbstractTester>> getTesters() {
List<Class<? extends AbstractTester>> testers = Helpers.copyToList(super.getTesters()); List<Class<? extends AbstractTester>> testers = Helpers.copyToList(super.getTesters());
testers.add(SortedSetNavigationTester.class); testers.add(SortedSetNavigationTester.class);
testers.add(FILE_KEY_TYPESortedSetIterationTester.class); testers.add(FILE_KEY_TYPESortedSetIterationTester.class);
testers.add(FILE_KEY_TYPESortedSetNaviationTester.class); testers.add(FILE_KEY_TYPESortedSetNaviationTester.class);
return testers; return testers;
} }
@Override @Override
public TestSuite createTestSuite() { public TestSuite createTestSuite() {
if (!getFeatures().contains(CollectionFeature.KNOWN_ORDER)) { if (!getFeatures().contains(CollectionFeature.KNOWN_ORDER)) {
List<Feature<?>> features = Helpers.copyToList(getFeatures()); List<Feature<?>> features = Helpers.copyToList(getFeatures());
#ignore #ignore
features.add(CollectionFeature.KNOWN_ORDER); features.add(CollectionFeature.KNOWN_ORDER);
#endignore #endignore
withFeatures(features); withFeatures(features);
} }
return super.createTestSuite(); return super.createTestSuite();
} }
@Override @Override
protected List<TestSuite> createDerivedSuites( protected List<TestSuite> createDerivedSuites(
FeatureSpecificTestSuiteBuilder<?, ? extends OneSizeTestContainerGenerator<Collection<CLASS_TYPE>, CLASS_TYPE>> parentBuilder) { FeatureSpecificTestSuiteBuilder<?, ? extends OneSizeTestContainerGenerator<Collection<CLASS_TYPE>, CLASS_TYPE>> parentBuilder) {
List<TestSuite> derivedSuites = super.createDerivedSuites(parentBuilder); List<TestSuite> derivedSuites = super.createDerivedSuites(parentBuilder);
#ignore #ignore
if (!parentBuilder.getFeatures().contains(CollectionFeature.SUBSET_VIEW)) { if (!parentBuilder.getFeatures().contains(CollectionFeature.SUBSET_VIEW)) {
#endignore #endignore
derivedSuites.add(createSubsetSuite(parentBuilder, Bound.NO_BOUND, Bound.EXCLUSIVE)); 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.NO_BOUND));
derivedSuites.add(createSubsetSuite(parentBuilder, Bound.INCLUSIVE, Bound.EXCLUSIVE)); derivedSuites.add(createSubsetSuite(parentBuilder, Bound.INCLUSIVE, Bound.EXCLUSIVE));
} }
return derivedSuites; return derivedSuites;
} }
final TestSuite createSubsetSuite( final TestSuite createSubsetSuite(
FeatureSpecificTestSuiteBuilder<?, ? extends OneSizeTestContainerGenerator<Collection<CLASS_TYPE>, CLASS_TYPE>> parentBuilder, FeatureSpecificTestSuiteBuilder<?, ? extends OneSizeTestContainerGenerator<Collection<CLASS_TYPE>, CLASS_TYPE>> parentBuilder,
Bound from, Bound to) { Bound from, Bound to) {
TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE delegate = (TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE) parentBuilder.getSubjectGenerator().getInnerGenerator(); TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE delegate = (TEST_SORTED_SET_GENERATOR KEY_GENERIC_TYPE) parentBuilder.getSubjectGenerator().getInnerGenerator();
List<Feature<?>> features = new ArrayList<>(parentBuilder.getFeatures()); List<Feature<?>> features = new ArrayList<>(parentBuilder.getFeatures());
#ignore #ignore
features.remove(CollectionFeature.ALLOWS_NULL_VALUES); features.remove(CollectionFeature.ALLOWS_NULL_VALUES);
features.add(CollectionFeature.SUBSET_VIEW); features.add(CollectionFeature.SUBSET_VIEW);
features.remove(SpecialFeature.COPYING); features.remove(SpecialFeature.COPYING);
features.remove(SpecialFeature.CHILDREN_COPY); features.remove(SpecialFeature.CHILDREN_COPY);
#endignore #endignore
return newBuilderUsing(delegate, to, from).named(parentBuilder.getName() + " subSet " + from + "-" + to) return newBuilderUsing(delegate, to, from).named(parentBuilder.getName() + " subSet " + from + "-" + to)
.withFeatures(features).suppressing(parentBuilder.getSuppressedTests()) .withFeatures(features).suppressing(parentBuilder.getSuppressedTests())
.withSetUp(parentBuilder.getSetUp()).withTearDown(parentBuilder.getTearDown()).createTestSuite(); .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) { 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)); return using(new SUB_SORTED_SET_CLASS_GENERATORBRACES(delegate, to, from));
} }
} }

Some files were not shown because too many files have changed in this diff Show More