Author SHA1 Message Date
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
Speiger 4dd3a4a6e8 0.8.0 Release 2022-12-20 09:33:26 +01:00
Speiger efd29bbe7e First draft of the 0.8.0 patch. 2022-12-19 16:03:43 +01:00
Speiger 96458bd8b6 Changes:
- Added: RandomGenerator support (Java17), though requires self
compilation
- Added: Optimizations for HashUtils next power of function.
- Added: toArray() now returns a cached empty array if the collection is
empty.
- Added: toArray function for AsyncBuilder
- Updated: SCG to version 1.2.2
2022-12-16 18:17:51 +01:00
Speiger 477f3c9f40 Implemented ForEachIndexed into all collections 2022-12-16 13:03:28 +01:00
Speiger 3f6e7fbb88 Added forEachIndexed 2022-12-15 20:08:33 +01:00
Speiger 5650c6e69b Fixed tests don't force generate 2022-12-15 18:28:00 +01:00
Speiger 61df32b7b2 Fixed unit tests and java 8 incompat. 2022-12-15 18:10:59 +01:00
Speiger 859d00da16 Fixed Java9 or newer issues. 2022-12-15 17:13:34 +01:00
Speiger 9df95c0fc3 Supplier now uses javas function name. Tests will still fail. 2022-12-15 16:26:05 +01:00
Speiger d6d2c0a396 Changed that function names are closer to javas names. 2022-12-15 16:07:44 +01:00
Speiger 127eb71968 Massive refactor.
-Changed: Classes that used Primitive Collections Functions now use Java functions if possible to increase compat.
-Changed: Started that functions go closer to javas naming sceme.
2022-12-14 18:32:04 +01:00
Speiger 6005d0fd39 Updated SCG to version 1.2.1
This fixes that all expressions are supported.
2022-12-13 13:34:11 +01:00
Speiger 290e626f07 Updated to SCG 1.2.0 2022-12-13 13:07:24 +01:00
Speiger e30d011273 Fixed Unit Test and Added putIfAbsentTest 2022-12-08 10:40:21 +01:00
Speiger 4c52636c23 Fixed Unit Tests 2022-12-07 08:22:45 +01:00
Speiger aa580c1772 Merged branches hopefully 2022-12-07 07:36:25 +01:00
Speiger 8f7d49b280 Finished Function module and added breaking change. 2022-12-07 07:31:30 +01:00
Speiger 342b0cece9 Collection Module Works now. (Least Configurable for obvious Reasons) 2022-12-07 06:27:47 +01:00
Speiger 3ce52668df Added Priority Queue Module 2022-12-07 05:30:23 +01:00
Speiger ce9343348e Pair Module is now done. 2022-12-07 04:35:29 +01:00
Speiger 8d9f7a6761 Improved Settings a bit.
-Added: "Implementations" configuration to turn of all "Implementations" keeping the interfaces/wrappers/abstract classes. Reducing the amount of configurations that need to be set.
-Changed: removed "Sets/Maps/Lists" configuration and replaced it with "Wrappers" since they are wrappers.
-Changed: Category Specific settings (except "Enabled") is sorted by Name.
2022-12-07 04:07:11 +01:00
Speiger 1b1ec4b87a Improving Dependency Checks to be more recursive. 2022-12-07 03:30:59 +01:00
Speiger cc92ef953a Added Dependency Checks into the Module System.
Why a Dependency Check system was added?
2022-12-07 03:23:19 +01:00
Speiger 8d8c30c9a7 Finishing the Set configuration. 2022-12-07 02:50:42 +01:00
Speiger d44ad2d42e 99% of the Set Module done.
The 1% is the Distinct Iterator that relies on a Set implementation.
So I have to make a dedicated set implementation.
2022-12-06 04:57:43 +01:00
Speiger 2ed090e989 Fixed a few bugs and Started the Set compilation. 2022-12-06 04:09:40 +01:00
Speiger dafb162797 Fixed a small bug where generic types can not be disabled. 2022-12-06 03:21:48 +01:00
Speiger 57280b8285 Map Generation can now be turned off. 2022-12-06 03:05:58 +01:00
Speiger c9fc963670 Few changes.
-Removed: BooleanSet classes are gone. (Unused anyways)
-Removed: Boolean2xMaps are also now gone. (Unused Anyways)
-Added: GlobalFlags that are shared across packages.
2022-12-05 07:10:53 +01:00
Speiger cc87cae145 Implemented Lists can now be Disabled
Each List implementation can be now turned off.
Or all Lists can be turned off.
ListIterator can't be turned of since it is a IndexBasedIterator and not
a List and a few implementation use them.
2022-12-05 00:01:53 +01:00
Speiger f53d61a5bc Fixed bug in the module generator config. 2022-12-04 08:00:31 +01:00
Speiger b29874189c Finishing Framework and making Async Module Optional. 2022-12-04 07:56:04 +01:00
Speiger 6722f399db Implemented Module Configuration 2022-12-02 22:36:34 +01:00
Speiger 8e39acef45 Finished adding the modules and implemented sorting algorythm.
That this works is crazy...
2022-11-29 14:33:16 +01:00
Speiger b065ebe9ba Start of the Modularization
-Added: Base code to modularize the project.
-Added: Javas Base Module.
2022-11-27 13:16:21 +01:00
Speiger 25a7cd060a The beginning of modulizing Primitive Collections.
This will be a small rewrite of the "Builder".
Why this is done?
Basically this library is really big and having the Option to turn of
modules that you don't need is really important.

And right now enabling/disabling modules is really difficult since
everything is merged together.

So the first goal is to modularized where everything can be turned on or
of as wished.
2022-11-21 06:45:07 +01:00
Speiger 21f330260e The beginning of modulizing Primitive Collections.
This will be a small rewrite of the "Builder".
Why this is done?
2022-11-21 06:39:22 +01:00
Speiger 99e9afe7b1 Started working on the next patch.
- Added: ISizeProvider interface (Optimization Helper)
- Added: ISizeProvider into most Iterable implementations
(Distinct/Filter/FlatMap/ArrayFlatMap don't support it, for obvious
reasons)
- Added: ToArray function into Iterable which uses ISizeProvider to
reduce overhead of duplicating arrays.
- Fixed: putIfAbsent now replaces defaultValues
2022-11-20 08:56:23 +01:00
Speiger 5118ae8b1f Small Publish action fix.
-Fixed: Renamed files to junit_files since the original is deprecated
2022-07-16 05:00:50 +02:00
Speiger 03b23f0e3c Added New Iterable Feature
-Added: Repeating iterable/iterator/async feature which allows to repeate collections a desired amount of times.
-Added: Tests for it.
2022-07-16 05:00:22 +02:00
Speiger ca33c9eb9e Upgrading to TestResult Publish V2 2022-07-16 04:02:45 +02:00
Speiger b4374fdd4d Reverting build scripts because done with it. 2022-07-06 16:47:15 +02:00
Speiger 455ee64a88 Trying to expand memory a bit. 2022-07-06 14:44:06 +02:00
Speiger 893b371017 Adding a forced delay 2022-07-05 07:51:49 +02:00
Speiger 5fa9baae7a Testing Ram limits 2022-07-04 22:55:27 +02:00
Speiger 70d565c785 Hopefully Fixed setup-java 2022-07-04 22:02:49 +02:00
Speiger 5c27e332cd Attempt on including testruns. 2022-07-02 07:43:18 +02:00
Speiger f2d919bae5 Undoing what i have done so unit tests pass again. 2022-06-21 13:20:34 +02:00
Speiger 7d4c77332b Testing Improved Test Info Generator 2022-06-21 12:08:44 +02:00
Speiger d1186d4f82 Updated Readme and disabled auto sync. 2022-06-14 10:44:02 +02:00
Speiger 3b8a02ac51 Fixed syncer 2022-06-14 09:33:10 +02:00
Speiger f356d4ab57 Trying out a auto sync between branches. 2022-06-14 09:23:20 +02:00
Speiger b07bc85114 Oops 2022-06-14 09:04:38 +02:00
Speiger c37746cd84 Small Fixes
-Fixed: Unit Test Generator is now Silenced. Because 4k lines.
-Fixed: Reverted to JavaSetupV1 for build because java14 support.
-Added: Java18 support for build
2022-06-14 09:03:20 +02:00
Speiger fb7c417394 Refactor of the Project on Github.
-Added: Better System to decide what code should be generated.
-Added: Unit Tests are now included in the main branch.
-Added: Automatic System to test the main branch and ensure that tests work.
-Added: Pull Requests now run tests too.
2022-06-14 08:55:40 +02:00
Speiger ddc58ee221 Version 0.7.0 Release
- Added: Coverage Badge
- Updated: Changelog.
- Changed: Changelog now has info how to obtain the sourcecode.
- 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
- Added: EnumMap specialized forEach implementation.
- Added: AbstractMap.remove now delegates to its primitive counterpart.
- Added: ConcurrentHashMap now implements ITrimmable
- Refactor: Removed a lot of disabled code from ArraySet.
- Removed: LinkedList.addAll(index, List) now delegates to
LinkedList.addAll(index, Collection) due to no special optimization
required.
- Fixed: AbstractList.SubList.get/set/swapRemove didn't calculate their
List index Properly
- Fixed: AbstractList.SubList chains now properly if you create SubLists
within SubLists.
- 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.
- Fixed: CopyOnWriteArrayList.extract/removeElements(int, int) does now
proper range checks and remove elements properly.
- Fixed: CopyOnWriteArrayList.SubList now works properly. (Reimplemented
entirely)
- Fixed: CopyOnWriteArrayList.Iterator.previous() was returning the
wrong values.
- 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.
- Fixed: LinkedList had an edge case where the entire reverse iterator
would break if the wrong element was removed.
- Fixed: LinkedList.extractElement now returns the correct values.
- Fixed: AbstractMap.entrySet().remove(Object) now returns true if
defaultReturnValue elements were removed.
- Fixed: ConcurrentHashMap.remove(Object, Object) checks if the type
matches before comparing against null Values.
- 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.
- Fixed: ImmutableMap now compares empty values (0) against nullKeys
when Object Variants of the type are used.
- Fixed: ArrayMap.iterator(key) now throws NoSuchElementException when
the element wasn't found.
- Fixed: Linked/EnumMap array constructor was creating the wrong size
values array.
- 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.
- Fixed: Map.Builder wasn't throwing a IllegalStateException when
creating a negative size builder.
- Fixed: AVL/RBTreeSet.DecendingSet.subSet(from, fromInclusive, to,
toInclusive) was creating a corrupt asending subset.
- Fixed: ArraySet throws now a IllegalStateException when trying to
create it with a negative size.
- Fixed: ArraySet.addMoveToLast(key) was crashing when a key was already
present.
- Fixed: Immutable/LinkedHashSet now keep track of their iteration index
properly.
- Fixed: LinkedHashSet.moveToFirst/Last(key) would crash if the Set was
empty.
- 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.
2022-06-12 14:31:45 +02:00
Speiger 8b5e5a75c1 Fixing bugs found when implementing Bidirectional Iterator unit tests.
-Fixed: AbstractList/ImmutableList/ArraySet/ArrayMap skip/back implementation was causing crashes and didn't update the last returned value.
-Fixed: ArraySet/ArrayMap previous was not subtracting before returning value.
-Fixed: BidirectionalIterator back was calling the object variant instead of the TypeSpecific Variant.
-Fixed: TreeSets/Maps Iterator now fully supports backwards Iterating.
-Added: Specialized skip/back function to improve speed in ImmutableHashSet/LinkedHashSet/CustomLinkedHashSet
2022-06-04 21:05:31 +02:00
Speiger c1862e6b05 Fixed a Few bugs with wrappers.
-Fixed: Maps.EmptyMap getOrDefault wasn't returning the default value.
-Fixed: Maps.UnmodifiableMap wasn't respecting the change of the DefaultReturnValue. (it has its own version of it so it doesn't break the rule of it, it wasn't returning the expected value.
-Added: A bunch of Methods for Unmodifiable/Empty maps that should fail right out but would still make it past a certain point. (Compute/Merge/Supply/etc)
2022-06-03 14:38:56 +02:00
Speiger c2c2780967 MapFixes found with unit tests.
-Fixed: CollectionWrapper.equals wasn't accounting for self.
-Fixed: MapWrapper.get didn't account for that it was a wrapper.
-Fixed: UnmodifiableMapWrapper was linking to synchronized maps due to a unknown reason.
-Added: UnmodifiableMapWrapper now has a lot more functions it right out says unsupported instead of indirect ways.
2022-06-02 16:21:48 +02:00
Speiger 086d933a0d Small fixes
-Fixed: NavigableMap.keySet is now a NavigableSet instead of a sorted one.
-Started: Trying to fix wrappers.
2022-06-02 14:59:39 +02:00
Speiger 1e7da394a1 Fixed Bugs found with wrapper collections
-Fixed: AbstractCollection.Iterator was changing the pointer before validating if the element was added. (ImmutableLists)
-Fixed: EmptyCollections containsAll should return true if it is compared against a emptyCollection.
-Fixed: HashCode/Equals for the Lists/Sets implementations.
-Changed: Iterators.wrap(Array) allows now dynamic arrays.
2022-06-02 11:02:19 +02:00
Speiger 9eb220194f Small fixes.
-Fixed: SynchronizedList.addElements was calling itself.
-Fixed: UnmodifiableSet was missing implementations that were causing fails.
2022-06-02 00:47:05 +02:00
Speiger 0baf141e4b New Snapshot builds xD 2022-05-31 19:27:20 +02:00
Speiger 569d4f5c86 Small Fix
-Fixed: HashSet/Map.reduce was using size to iterate instead of array.length
2022-05-31 19:05:54 +02:00
Speiger 36f24731b0 Script Cleanup, Changelog Update and Version Bump.
Added a lot of Unit Tests (Roughly 7 Million) to Primitive Collections
(look Debug Branch) and found some really big bugs.
The Coverage was moved from 1.9% to 34.7% so far.
So there were a lot bugs found and at this point I need a break so this
is the first fixpatch until new tests are added.
2022-05-28 23:34:37 +02:00
Speiger ea5ace0166 Another Coverage Try 2022-05-28 20:32:15 +02:00
Speiger 663809ff27 another test 2022-05-28 20:11:00 +02:00
Speiger 5d6adb5446 Added Jacoco reports 2022-05-28 19:58:54 +02:00
Speiger 212ad1ace2 Add coverage test 2022-05-28 19:56:28 +02:00
Speiger 707827929a Updated version number 2022-05-27 21:21:11 +02:00
Speiger 27ad01657d More fixes from Unit tests.
-Fixed: ArrayList/LinkedList extractElements crashing when 0 or less elements are desired.
-Fixed: TreeMap pollFirst/LastKey should return the defaultMin/max value instead of a Empty value.
-Fixed: TreeMap keySet implementation was missing the class type implementations to pass keySet tests.
-Fixed: TreeMap.SubMap Iterator (primitive Keys) was crashing because a Null was set on to a primitive.
2022-05-27 16:35:41 +02:00
Speiger e7da7acc08 Started massive unit testing library these are the first fixes.
-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.
-Fixed: SubList didn't check for ranges properly or didn't use parent list to validate changes.
-Fixed: ArrayList.addElements didn't check input array fully and used the wrong variable to move the elements around.
-Fixed: LinkedList.addElements(EmptyInput) would crash.
-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.
-Fixed: LinkedHashSet.addAndMoveToFirst wouldn't move elements to the first place.
2022-05-22 15:13:29 +02:00
Speiger 72943cb22c Added AsyncBuilder for arrays 2022-05-17 18:10:07 +02:00
Speiger 068cc4a4f7 Fixed Bugs with Java Iterators not throwing the correct exception. 2022-05-17 10:45:05 +02:00
Speiger 31b34f5de1 Fixed a couple bugs.
-Fixed: TreeMap.subMap().entrySet().remove() wouldn't check primitives properly.
-Fixed: SortedMap.sub/tail/headMap were looping into themselves.
-Changed: LinkedList.addBulk variable definition was triggering a false positive.
2022-05-17 07:59:57 +02:00
Speiger 4bded1af80 Small Change to sorting
-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.
2022-04-30 22:41:11 +02:00
Speiger 100c7fe260 Updated yml Scripts
-Updated: yml Scripts and ReadMe since the gradle setup no longer requires 2 commands to work properly.
2022-04-28 19:09:42 +02:00
Speiger 04f628fcc1 Pushing release 2022-04-21 17:41:50 +02:00
Speiger 5fa26bfbf3 New Stuff
-Fixed: Crash with FIFOQueues peek function when loops were applied.
-Fixed: FIFOQueues clean function was doing unessesary extra work.
-Added: Stream Overrides functions now support sorted.
-Updated: Changelog.
-Added: A couple more badges because why not.
2022-04-21 17:25:23 +02:00
Speiger 4d3eaaf604 removing SolarCloud code 2022-04-19 17:16:53 +02:00
Speiger 33ab7c48bf hopefully doesn't filter anything. Last attempt 2022-04-19 17:10:57 +02:00
Speiger 1f4784c75e Testing single task requirement 2022-04-19 16:58:22 +02:00
Speiger ae5a4ea818 Readded caching 2022-04-19 16:33:16 +02:00
Speiger 5d66f7b453 Update Code compare 2022-04-19 16:11:20 +02:00
Speiger 12af656150 Updated Task Name 2022-04-19 16:04:20 +02:00
Speiger 603ff3df0f Fixed code compare 2022-04-19 15:52:41 +02:00
Speiger b712981718 Code quality test 2022-04-19 15:51:01 +02:00
Speiger 863d1a1027 Updated Readme. 2022-04-18 21:41:55 +02:00
Speiger 6287da8efe ReadMe restructuring. 2022-04-18 09:06:32 +02:00
Speiger c27e852ccb typo missed by the spellchecker... 2022-04-17 20:39:06 +02:00
Speiger 0157765628 Hotfix. 2022-04-17 20:24:31 +02:00
Speiger 8689037ceb Documentation update 2022-04-17 20:21:48 +02:00
Speiger 03a8914986 Completion Jitpack Integration 2022-04-14 09:51:36 +02:00
Speiger 26b9d6706d Fixed Classification 2022-04-14 09:34:16 +02:00
Speiger a21d4a9eb6 Fixing Jitpack Publishing 2022-04-14 09:24:13 +02:00
Speiger 212d614ebd Trying switching Jitpack Java version. 2022-04-14 09:19:27 +02:00
Speiger bcba3ccde0 Another try 2022-04-14 09:13:53 +02:00
Speiger b42ad76372 Jitpack Test 2022-04-14 09:12:03 +02:00
Speiger f95565771a 0.6.0 Release Commit 2022-04-14 07:56:39 +02:00
Speiger 3d6cbf5ac1 Finishing touches for the 0.6.0 release. 2022-04-14 07:29:32 +02:00
Speiger fc5d43e14b Updated Changelog. 2022-04-14 06:06:35 +02:00
Speiger b3264748cd Added Author to module Info. 2022-04-14 05:47:19 +02:00
Speiger ede40f06d0 Small fixes.
-Fixed: Some imports.
-Fixed: containsValue for OpenHashMap was not checking nullEntry properly
2022-04-14 05:37:41 +02:00
Speiger e69c675f82 Fixed bug with linux & cleanup of the java version detector 2022-04-13 02:58:35 +02:00
Speiger 17c1c90957 Added Module-Info support 2022-04-13 02:54:03 +02:00
Speiger c6f2f71f6c Switching to a new lock to make read operations actually concurrent. 2022-04-13 02:00:52 +02:00
Speiger d2c7c151bc Implemented tests.
-Added: ConcurrentHashMap test suite
-Fixed: Bugs found in ConcurrentHashMaps with the iterator and clear function.
2022-04-12 08:08:17 +02:00
Speiger 4448eca787 Finishing ConcurrentHashMap implementation, next tests 2022-04-12 06:06:18 +02:00
Speiger 0350a77dff Finishing the ConcurrentMap implementation
This though isn't finishing the rest because the interface still needs
to be implemented.
-Added: Rest of the ConcurrentMap implementation
-Fixed: LinkedOpenHashMap Count method was returning prematurely.
2022-04-11 03:20:28 +02:00
Speiger 4f98c599df New Features.
-Added: ArrayList.of(CLASS, size) function that allows to preallocate
the size of the generic list.
-Updated: ListTests suppressors only suprres what they need to.
-Added: Start of the ConcurrentHashMap implementation (based on Guavas
implementation)

Note that the ConcurrentHashMap implementation is just started not
finished and still needs a lot of work, but the base code - any
subclasses is technically finished.
The implementation is also using linkedMaps to have faster iteration
performance.
2022-04-10 15:49:16 +02:00
Speiger 103b2407d2 Updated Changelog 2022-04-09 04:23:57 +02:00
Speiger 059da9be12 New Features
-Added: CopyOnWriteArrayList
-Added: UnitTests for CopyOnWriteArrayLists
2022-04-09 03:56:54 +02:00
Speiger 3cac3a997e And hopefully the last javaDoc fixes 2022-04-08 00:24:37 +02:00
Speiger 3ffb001c73 More fixes
-Fixed: More javadoc fixes
-Fixed: BaseIntIterableTest no longer uses a deprecated function
2022-04-08 00:13:51 +02:00
Speiger 2810a6f952 Small fixes
-Fixed: JavaDoc
-Changed: callback is now called onCompletion
2022-04-08 00:00:45 +02:00
Speiger 166362334b Added gradle now uses the java version it runs on. 2022-04-07 20:26:53 +02:00
Speiger d3f9103ebf Adding Logger for testings 2022-04-07 20:19:47 +02:00
Speiger 1c5507d4a5 Switching to local properties 2022-04-07 20:16:59 +02:00
Speiger 5e3cd9f484 Trying out something with github actions 2022-04-07 20:14:23 +02:00
Speiger f27b884b6a Moving to a more up to date system.
-Changed: Moved to gradle 7.3 for java17 support of the project.
-Changed: Moved to maven-publish plugin and added a bit more info to the poms.
2022-04-07 16:00:58 +02:00
Speiger 769a9d8ea5 Upgraded gradle version to 6.3 for a test 2022-04-07 13:32:04 +02:00
Speiger 9499a7f0e0 Setup matrix so multiple java versions are tested. 2022-04-07 13:27:12 +02:00
Speiger ca38583f96 Fixed Java11 Incompat 2022-04-07 00:14:09 +02:00
Speiger 9557a0cfb5 Merge branch 'master' of git@github.com:Speiger/Primitive-Collections.git 2022-04-07 00:08:05 +02:00
Speiger c61e8bb7fc New Features
- Added: addOrGet for sets.
- Added: Async API which allows to easily execute Iterables/Collections
offthread without the complexity.
2022-04-07 00:06:49 +02:00
SpeigerandSpeiger 4fbcaa47f8 Update README.md 2022-04-07 00:06:19 +02:00
Speiger 6f31fc5abb New Features
- Added: addOrGet for sets.
- Added: Async API which allows to easily execute Iterables/Collections
offthread without the complexity.
2022-04-07 00:04:52 +02:00
SpeigerandGitHub 10ec0e35d0 Update README.md 2021-12-27 21:29:51 +01:00
Speiger 29c4d253cf Disabling badge 2021-12-27 21:28:07 +01:00
Speiger 55c870d392 Adding Build Passing badge 2021-12-27 21:22:57 +01:00
SpeigerandGitHub cda6ec066d Adding Build Validation
Create gradle.yml
2021-12-27 20:38:55 +01:00
Speiger c8b89e6847 Renaming file for what the action did. 2021-12-27 20:34:15 +01:00
Speiger b46a739008 Finishing Build Action 2021-12-27 20:28:45 +01:00
Speiger af62394651 Testing for secrets to be present 2021-12-27 20:04:50 +01:00
SpeigerandGitHub bc75a5cd97 Merge pull request #8 from Speiger/master
Moving Credentials Away from this file because now i need it
2021-12-27 20:00:58 +01:00
Speiger 7d8af3af08 Moving Credentials Away from this file because now i need it 2021-12-27 19:59:19 +01:00
SpeigerandGitHub ef8197b275 Update gradle.yml 2021-12-27 19:24:16 +01:00
SpeigerandGitHub 58d9ac7fdd Update gradle.yml 2021-12-27 19:21:59 +01:00
SpeigerandGitHub 86a893916d Update gradle.yml 2021-12-27 19:20:06 +01:00
SpeigerandGitHub e7a6292fe9 Update gradle.yml 2021-12-27 19:10:09 +01:00
SpeigerandGitHub 81209b0cf8 Update gradle.yml 2021-12-27 19:07:05 +01:00
SpeigerandGitHub 77b8147f9b Update gradle.yml 2021-12-27 19:05:33 +01:00
SpeigerandGitHub 32abd7e14e Update gradle.yml 2021-12-27 19:04:33 +01:00
SpeigerandGitHub 8a582f0b08 Create gradle.yml 2021-12-27 19:01:45 +01:00
SpeigerandGitHub 01be6f7d43 Delete gradle.yml 2021-12-27 18:56:49 +01:00
SpeigerandGitHub 9011700879 testing build only 2021-12-27 18:55:51 +01:00
SpeigerandGitHub 12cd4e5e5f Update gradle.yml 2021-12-27 18:50:24 +01:00
SpeigerandGitHub 10201bcadb hopefully this works 2021-12-27 18:44:47 +01:00
SpeigerandGitHub 3b4fcc0069 Merge pull request #6 from Speiger/actions
Update gradle.yml
2021-12-27 18:32:51 +01:00
SpeigerandGitHub 31a1ef74fb Update gradle.yml 2021-12-27 18:32:23 +01:00
SpeigerandGitHub 9be3a1475f another build try 2021-12-27 18:29:54 +01:00
SpeigerandGitHub 7591f396fd getting into github actions
Adding a build test
2021-12-27 18:18:24 +01:00
Speiger 517b84042f Version Bump 2021-12-26 01:58:22 +01:00
Speiger dbfae33074 Fixed Bug with FIFOQueue performance 2021-12-26 00:08:19 +01:00
Speiger ead34009c6 Added pourAsList and pourAsSet 2021-12-25 20:27:33 +01:00
Speiger 7a4a0f05d1 Added subFrom (which is the inverse of addTo) 2021-12-25 20:07:37 +01:00
Speiger 8f32b2d887 Merge remote-tracking branch 'Github/master' 2021-12-25 03:49:45 +01:00
Speiger e6c9600b40 Refactoring and Deprecating SortedMap/Sets
- Added: OrderedMap/Set
- Added: All Relevant functions into Ordered interface
- Changed: Marked all Relevant SortedMap/Set functions Deprecated until
0.6.0
- Fixed: All code that was relevant to this
2021-12-25 03:46:51 +01:00
SpeigerandGitHub d5f2acb9ab Update LICENSE 2021-12-19 21:19:28 +01:00
Speiger 3274e96355 Added Benchmark links 2021-12-16 14:03:39 +01:00
Speiger 78dfa286b0 New Version
- Fixed: Bugs with Queues starting with the wrong size
- Fixed: ArrayGrowth for Queues was +1 instead of +50%
- Added: Benchmarks with java and FastUtil
2021-12-16 13:46:55 +01:00
Speiger f32624d131 Build Release..
-Fixed: Doc error on gradle build.
-Fixed: SubSet.iterator had a ambiguity.
2021-12-14 09:05:25 +01:00
Speiger 59a417056c Added Missing method & fixed potential issue with TreeSetBiIterators 2021-12-13 13:56:28 +01:00
Speiger 18f6704ed7 Expanded Unit tests to IntLists/Sets
Maps are sadly not possible. It will require writing templates for
permutations effectively copying guavas Test library.
So this will take a lot longer
2021-12-13 13:45:35 +01:00
Speiger caf2f22e9f Finished the Basic Unit test frame work to ensure stablity.
-Added: 150k Unit tests.
-Fixed: Reworked the NavigableSet/Map implementations of RBTree/AVLTree/Array Sets/Maps
2021-12-13 10:41:20 +01:00
Speiger 865966db55 Build Fixes & Build Release Doc update 2021-12-11 13:27:33 +01:00
Speiger 6266a6293c Slight rewording 2021-12-11 12:58:02 +01:00
Speiger 70ea60aacf More doc fixes 2021-12-11 12:57:03 +01:00
Speiger 599cc44fff Fixed Doc 2021-12-11 12:56:01 +01:00
Speiger e1df59d512 We are now to 16k tests. Fixed loads of issues.
-Added: Tests for Lists and Sets.
-Fixed: SubLists are now stable (they weren't before)
-Fixed: All the bugs that the unit tests found so far.
-Updated: ReadMe/Changelog
2021-12-11 12:53:58 +01:00
Speiger eaa45976c7 Added over 6k tests...
- Fixed: ImmutableMaps issues thanks to the tests. Roughly the same as
the rest of the maps
- Fixed: RB/AVLTreeMaps issues. Roughly the same as the rest of the maps
2021-12-10 10:55:16 +01:00
Speiger 362838c434 Found something in FastUtil i needed to address too. BulkFixes coming.
- Added: Guava TestSuit
- Fixed: HashCode and toString method would crash if the Object
Key/Value was null
- 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.
- Fixed: Set.hashCode now is the sum of the elements instead of a Unique
HashCode based on the elements.
- Fixed: Added missing NonNull Checks.
- Fixed: OpenHashMap.containsValue implementation was wrong.
- Fixed: OpenHashMap.compute/present/absent now works how it is
specified in the Java Documentation
- Fixed: OpenHashMap.merge/BulkMerge now works how it is specified in
the Java Documentation
- Fixed: OpenHashMap.keySet.remove was causing a infinite loop.
- Fixed: OpenHashMap.mapIterator now no longer crashes in certain cases.
2021-12-10 05:54:37 +01:00
Speiger 52caa9cdd2 Doc Update 2021-12-10 03:27:33 +01:00
Speiger c6afdb8762 New Tests & Fixes
- 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.
2021-12-10 03:23:28 +01:00
Speiger c4964806f0 Loads of new features & fixes.
- Added: pour function directly into Iterable which allows to collect
all elements in the Iterable directly.
- Added: The new ToArray method from Java9 and newer into the library.
Using a functional interface. (Just a backport)
- 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.
- Added: Unmodifiable and Synchronize wrapper functions direclty into
Collection Interfaces. This is mostly a quality of life thing.
- 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: A boxed putAll array variant.
- 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.
2021-12-09 09:14:55 +01:00
Speiger a2506b927a New Small feature
- Added: 2 Helper functions to find out how many bits are required to
store a Number.
2021-11-30 16:20:08 +01:00
Speiger 53061d9f78 Update Readme 2021-10-30 07:42:13 +02:00
Speiger 2555dc7fc2 Version Bump 2021-10-30 07:39:05 +02:00
Speiger 058087e15a Added some more tests for some of the new functions 2021-10-30 07:21:41 +02:00
Speiger c20c6393e5 Added Better forEach support for Iterables. 2021-10-29 17:23:52 +02:00
Speiger a25ec85ba2 Added Reduce function to all implementations 2021-10-29 16:03:39 +02:00
Speiger c930bda7a6 Added RemoveSwap 2021-10-28 23:39:19 +02:00
Speiger e7bc242292 Fixes and a lot new features. But still WIP
- Fixed: Supplier get function wasn't referencing original function.
- Added: addIfPresent/Absent to lists
- Added: distinct, limit and peek iterators
- Added: Iterable's can now reduce its contents
2021-10-27 14:09:19 +02:00
Speiger b90a9ec7d8 Added new Remove/RetainAll function to Collection 2021-10-24 01:11:11 +02:00
Speiger d18a35d9b7 Updated Readme to include deprecation of to old patches to save on space 2021-10-11 19:39:09 +02:00
Speiger ffc34a131f New Features and Bugfixes.
- Fixed: ObjectArrayList.of was causing crashes because of a Poor
implementation.
- Added: Unsorted HashMaps/Sets now throw Concurrent exceptions if they
were modified during a rehash.
- Added: Array/Collection version of enqueue and enqueueFirst to
PriorityQueues.
- Added: fillBuffer function into PrimitiveLists which allow to optimize
JavaNio buffers if needed.
2021-10-11 19:05:54 +02:00
Speiger a38e7b069a More Consistency and more features.
- Added: Wrapper now support the Optimized Lambda replacer functions to
improve performance.
- Added: FIFO Queue has now a minimum capacity and that is now checked
more consistently.
- Added: Changelog & Version Bump
2021-10-07 14:50:52 +02:00
Speiger 9c15980e68 Version Bump 2021-10-06 20:53:19 +02:00
Speiger a05689017e Update information 2021-10-06 20:33:11 +02:00
Speiger 54c9660145 New Tests & BugFixes
-Added: Tests for the Copying of Collections.
-Fixed: PriorityQueues didn't have hashCode/equals/toString implemented
2021-10-06 20:23:40 +02:00
Speiger 0c4ef7f6c4 Queues are now copyable 2021-10-06 18:47:15 +02:00
Speiger 61d7a88c82 Maps are now copyable too 2021-10-06 18:32:10 +02:00
Speiger dff173222d Collections are now copyable 2021-10-06 17:48:37 +02:00
Speiger 6eded1f4be Sets are now Copyable 2021-10-06 17:43:46 +02:00
Speiger 07b715dd4c Start of adding copyable collections. Starting with Lists. 2021-10-06 16:30:53 +02:00
Speiger 1f1aa995df Release of 0.4.1 2021-09-29 02:11:29 +02:00
Speiger 1e2703acf2 ChangelogUpdate 2021-09-28 13:23:41 +02:00
Speiger 07abba6312 New Features
-Added: Count method for Iterable
-Fixed: A couple of bugs with the new stream removers not working well in LinkedCollections
2021-09-28 13:20:05 +02:00
Speiger 3f872463b6 Fixed a Rule Break with the new ComputeIfAbsent function 2021-09-28 12:26:44 +02:00
Speiger 531443531d New Features.
-Added: Suppliers.
-Added: ComputeIfAbsent but value generator is a supplier
2021-09-28 12:06:51 +02:00
Speiger 49c5e9eadd Changes.
-Added: New Changes to Changelog
-Fixed: Missing Autogenerated Type
-Cleanup: Gradle file got cleaned up from things it no longer needs.
-Changed: Upgraded to SCG 1.0.5 for incoming new features.
2021-09-28 04:43:04 +02:00
Speiger 3c5769e0e2 Added java type support for Stream replacer functions. 2021-09-28 03:34:53 +02:00
Speiger 0e061921e9 New Features and improvements
-Added: addAll array function.
-Fixed: forEach with input now puts the input at the key instead of value
2021-09-28 03:23:21 +02:00
Speiger edca820634 Version 0.4.0 Release and Readme Update 2021-09-20 01:41:24 +02:00
Speiger bc7afad793 Last Minute Fixes 2021-09-20 00:52:23 +02:00
Speiger 86dbed4bf9 Added Essential Methods 2021-09-19 22:36:23 +02:00
Speiger 2f31d7b641 Updated Changelog a bit 2021-09-19 22:34:46 +02:00
Speiger ef0b9d23c3 Added Pairs 2021-09-19 22:31:04 +02:00
Speiger 6e30a54ead Cleanup Space are now converted into tabs. 2021-09-19 19:38:05 +02:00
Speiger fa3cf743f9 TreeSubSets (RB/AVL) got their functional implementations improved too. 2021-09-19 18:03:02 +02:00
Speiger 5b67e85009 RBTreeMap got now the same improvements like AVLTreeMap 2021-09-19 17:41:54 +02:00
Speiger 59c4d1aa90 Changelog update 2021-09-18 10:31:51 +02:00
Speiger abc1c075f5 AVLTreeMap gets some love regarding forEach/etc 2021-09-18 10:30:28 +02:00
Speiger 4aac66b6fb Updated Changelog 2021-09-16 23:56:11 +02:00
Speiger 17f0dddf20 Refactor and New Features
-Changed: Refactored some variable names because they got out of hand since they were handed for single cases instead of making actual specific rules.
-Added: mapping functions (only to objects) are now accessible to primitive collections.
-Added: Filter function for Iterables/Iterators. (Iterable implements them automatically)
2021-09-16 23:53:57 +02:00
Speiger c5720e591c Changelog update 2021-09-16 02:58:50 +02:00
Speiger 796cd7c007 New Implementations & Fixes (Tree Maps get soon more love too)
-Added: New Implementations for new Iterable functions.
-Fixed: Reduced the Conditional Code by adding better Variables.
-Changed: Removed a lot of duplicated for each methods.
2021-09-16 02:57:09 +02:00
Speiger c9cd62f5d7 New Fixes
- Fixed: Compute/ComputeIfAbsent/ComputeIfPresent/Merge/BulkMerge in
maps now behave like they should.
2021-09-15 05:44:19 +02:00
Speiger fc1a738625 Started Next larger patch.
- Changed: Iterable specific helper functions were moved out of
Iterators and moved into Iterables
- Added: New Stream replacing functions: findFirst, matchesAny/All/None
2021-09-15 05:09:14 +02:00
Speiger 854678fd3c Added Specialized Collection functions to the documentation. 2021-09-14 17:19:27 +02:00
Speiger 3fa75ba18e Updated Maven Build 2021-09-13 17:54:10 +02:00
Speiger 212f532350 Fixed small logic error in clearAndTrim (Maps/Sets) 2021-09-13 17:15:40 +02:00
Speiger 29f2b8e305 Updated Description/Version/Changelog 2021-09-13 17:09:31 +02:00
Speiger e30ca4103f Fixed recent found bugs
-Fixed: addAll with non Specific Collections was crashing lists.
-Fixed/Refactor: Clear and trim implementation was all over the place
-Fixed: Wrappers toString/hashCode/equals function wasn't implemented
-Added: Tests for addAll bug
-Refactor: Did small code style cleanups as I was fixing bugs.
2021-09-13 17:02:24 +02:00
Speiger ec817fb9c2 Added found bugs to the Readme so people can avoid them util a fix 2021-09-13 01:08:11 +02:00
Speiger 88918dfb35 Updated known bugs 2021-09-03 10:52:03 +02:00
Speiger 0f072ddd59 Updated Release Version 2021-09-02 13:49:25 +02:00
Speiger a1b422dbe8 Version Bump 2021-09-02 13:41:47 +02:00
Speiger 3af5ca49cc Small Fix
- Fixed: Dependency to SimpleCodeGenerator should be no longer a thing.
Because the resulting library doesn't need it only the builder does.
2021-09-02 13:40:33 +02:00
Speiger 117d0f36e6 New Fixes
- Fixed: ObjectLists Crashed when a null was provided as a Comparator.
(Unless the List was Initialized with the ClassType)
- Fixed: LinkedLists didn't implement add(Object)
- Fixed: Object Collections did have the JavaCollections deprecated as
the Constructor. This should only be deprecated for Primitives
- Added: Tests with 5k Random names for Object sorting.
- Changed: Object Arrays no longer require a Comparable[] it just
assumes now that the elements in the Array are Comparable
2021-09-02 13:38:25 +02:00
Speiger aa1e7da38c Code generator was wrongly added as a required dependency. 2021-08-27 07:45:41 +02:00
Speiger ea83f5017e Hotfixing a bug where ArrayLists didn't resize Properly when empty 2021-08-15 18:09:34 +02:00
Speiger efc3745690 Updated Issues list 2021-08-12 15:08:53 +02:00
Speiger 6ae4a8f582 Updated Feature List 2021-08-12 15:06:04 +02:00
Speiger b46456dd32 Fixed markdown 2021-08-12 15:03:52 +02:00
Speiger 4ae353a0bd Updated Release and added direct downloads 2021-08-12 15:03:05 +02:00
Speiger 45d118a77a New Features and bugfixes.
- Fixed: AbstractCollection bulk adding methods now link to the
specialized implementations.
- Fixed: A bug with getElements in ArrayList.
- 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
2021-08-12 14:31:29 +02:00
Speiger 73916f4fd9 Fixed AVLTrees pollFirst/pollLast 2021-07-23 22:04:59 +02:00
Speiger 4a3cc66401 Added Flat/Mapping Functions for Iterables/Iterators (Object Only) 2021-07-21 16:32:30 +02:00
Speiger 0ed1208d59 Updated Latest Version 2021-06-27 21:43:37 +02:00
Speiger b99abaafec Fixed last second bugs. 2021-06-27 21:31:42 +02:00
Speiger ee02997881 Version Bump 2021-06-27 17:23:55 +02:00
Speiger 626ab29fc7 Lists.addElements(T...elements) was adding elements at the beginning of
a list instead of the end.
2021-06-27 17:23:34 +02:00
Speiger e6c4d43f6e Updated readme a bit. 2021-06-27 16:05:43 +02:00
Speiger 880a9169e5 Maps can now be created through the interface. 2021-06-27 16:02:26 +02:00
Speiger 4c68c925d3 Fixed a bug where exact duplication would break immutableMaps/sets 2021-06-25 21:14:45 +02:00
Speiger 9d17dc17fd Added ImmutableOpenHashMap that is not editable (is linked by default
for fast iteration)
2021-06-25 17:44:48 +02:00
Speiger 84bc785cdc CustomOpenHashSets now implement foreach and have less overhead. 2021-06-25 16:37:17 +02:00
Speiger b784041894 New Features
- Added: OpenHashSets now implement foreach and have less overhead.
- Added: ImmutableOpenHashSet that is not editable (is linked by default
for fast iteration)
2021-06-25 14:22:22 +02:00
Speiger 2b408fb2b2 New Features
- 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.
2021-06-25 12:28:19 +02:00
Speiger 8618c10d01 Fixed a crash with Map.put 2021-06-24 20:58:17 +02:00
Speiger dff5e534ff Updated Release Version 2021-06-24 17:21:26 +02:00
Speiger e95e0a3e8f Version Bump 2021-06-24 17:16:59 +02:00
Speiger 3b27604258 More fixes.
- 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.
2021-06-24 17:16:36 +02:00
Speiger c0fef15e64 More Fixes
- Fixed: containsKey & containsValue in HashMaps were deprecated for
Object Variants.
- Fixed: HashMap wasn't deleting Keys & Values references when removing
a Object
- Fixed: AVLTreeSet didn't balance properly.
- Changed: EnumMap no longer tries to access SharedSecrets since its
gone in java11
2021-06-24 13:17:48 +02:00
Speiger 3c0f4acc05 Fixed a missing import & Updated readme. 2021-06-23 22:17:52 +02:00
Speiger 406a57bb9d Version Bump 2021-06-23 22:14:41 +02:00
Speiger b50307c88d Added PriorityQueues 2021-06-23 22:14:08 +02:00
Speiger a28149ac8d Added Shuffle & Reverse Methods and Concat Iterators. 2021-06-23 21:45:12 +02:00
Speiger b55b049508 Another set of changes.
- 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.
2021-06-23 19:58:31 +02:00
Speiger ce8f49cd1f Maps.get function is no longer using Suffixes unless its absolutely
necessary.
2021-06-23 19:34:32 +02:00
Speiger 357b40e670 PriorityQueues no longer extends Object Variant. 2021-06-23 19:22:19 +02:00
Speiger a669f69d99 Primitive Stacks no longer depend on the base Stack class. 2021-06-23 19:07:30 +02:00
Speiger f4c25c683f Removed Suffixes of unmodifiable & synchronize methods. 2021-06-23 18:53:40 +02:00
Speiger 9f4bede08e Small Additions & Redsign
- Added: Stack.isEmpty was missing
- Changed: remove/removeLast/enqueue/enqueueFirst no longer use Type
Suffixes
2021-06-23 18:38:23 +02:00
Speiger 3676849efc Updated Builder version that no is +Java11 Compatible 2021-06-23 00:23:08 +02:00
Speiger 5ea1e3c358 Got the If switched up. 2021-06-22 19:49:32 +02:00
Speiger 500514fb20 SharedConstants still making issues. 2021-06-22 19:40:48 +02:00
Speiger fd32f404c0 Pushing Wrapper 2021-06-22 17:34:53 +02:00
Speiger d1453fbc95 Adding more info if someone wants to contribute 2021-06-22 16:34:32 +02:00
Speiger 8fee81bd19 Keeping the Primitive Collections Name. 2021-06-22 16:19:19 +02:00
Speiger 7fd54cd094 Testing Multi Remote 2021-06-22 16:13:01 +02:00
Speiger a44e091851 Added Maven Readme 2021-06-22 15:53:52 +02:00
Speiger ed193d9fc0 Moving towards Maven Release. 2021-06-22 15:15:10 +02:00
Speiger ac4dab9d7e Updated Docs 2021-05-31 19:43:01 +02:00
Speiger cbb5dd0ee2 Added Linked Enum Maps 2021-05-31 19:41:57 +02:00
Speiger 57baeb261e Added Implementation specific functions to speed up logic. 2021-05-28 22:10:30 +02:00
Speiger bbcb290560 List Documentation cleanup & added Primitive Parallel Streams 2021-05-28 20:20:45 +02:00
Speiger 17886dde62 Fixes to SubSets.
-Fixed: ToArray implementation works now.
-Fixed: Creating SubSets from subsets is now no longer 1 element to small.
2021-05-28 20:08:04 +02:00
Speiger 998272c8d5 Added TrimAndClear function into ITrimmable 2021-05-26 13:06:52 +02:00
Speiger 13b2c727fc Added Identity HashMap support via Strategies 2021-05-22 06:08:27 +02:00
Speiger 7fcfecf308 New Features.
-Added: removeOrDefault function
-Added: New functions into implementations
2021-05-22 05:50:40 +02:00
Speiger a319e0136a Added New Utility methods.
-Added: bulk putIfAbsent & AddTo function
-Added: ArrayPut method simplify adding arrays into a map.
-Added: Bulk Replace function that uses a "Map" instead of a lambda
-Added: Bulk Merge function
2021-05-22 05:26:44 +02:00
336 changed files with 81489 additions and 23796 deletions
+1 -1
View File
@@ -38,7 +38,7 @@
<attribute name="gradle_used_by_scope" value="builder"/> <attribute name="gradle_used_by_scope" value="builder"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8/"/>
<classpathentry kind="con" path="org.eclipse.buildship.core.gradleclasspathcontainer"/> <classpathentry kind="con" path="org.eclipse.buildship.core.gradleclasspathcontainer"/>
<classpathentry kind="output" path="bin/default"/> <classpathentry kind="output" path="bin/default"/>
</classpath> </classpath>
+33
View File
@@ -0,0 +1,33 @@
name: Latest Build
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
strategy:
fail-fast: false
matrix:
jdk: [8, 11, 16, 17, 18, 19, 20]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up JDK ${{ matrix.jdk }}
uses: actions/setup-java@v3
with:
distribution: 'temurin'
java-version: ${{ matrix.jdk }}
- name: Validate Gradle wrapper
uses: gradle/wrapper-validation-action@v1
- name: Make gradlew executable
run: chmod +x ./gradlew
- name: Build with Gradle
run: ./gradlew build
+84
View File
@@ -0,0 +1,84 @@
name: Unit Tests
on:
push:
branches: [ master ]
jobs:
build:
name: Unit Tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up JDK 11
uses: actions/setup-java@v3
with:
distribution: temurin
java-version: 11
cache: gradle
- name: Make gradlew executable
run: chmod +x ./gradlew
- name: Build and Test
run: |
./gradlew generateTestSource test jacocoTestReport --info -Dfull_test_suite=true
./gradlew --stop
- name: Publish Test Result
uses: EnricoMi/publish-unit-test-result-action@v2
id: test-results
if: always()
with:
junit_files: build/test-results/**/*.xml
fail_on: nothing
ignore_runs: true
json_thousands_separator: .
time_unit: milliseconds
- name: Create Badge Color
shell: bash
run: |
case ${{ fromJSON( steps.test-results.outputs.json ).conclusion }} in
success)
echo "BADGE_COLOR=31c653" >> $GITHUB_ENV
;;
failure)
echo "BADGE_COLOR=800000" >> $GITHUB_ENV
;;
neutral)
echo "BADGE_COLOR=696969" >> $GITHUB_ENV
;;
esac
- name: Create Test Badge
uses: emibcn/badge-action@v1.2.4
with:
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 }}'
color: ${{ env.BADGE_COLOR }}
path: tests.svg
- name: Create Coverage Badge
id: jacoco
uses: cicirello/jacoco-badge-generator@v2
with:
jacoco-csv-file: build/reports/jacoco/test/jacocoTestReport.csv
badges-directory: null
intervals: 95 80 70 60 50 0
- name: Upload Test Badge
uses: exuanbo/actions-deploy-gist@v1
with:
token: ${{ secrets.GIST_TOKEN }}
gist_id: 280257cd19cbe1dda3789bebd4ff65cf
file_path: tests.svg
- name: Upload Coverage Badge
uses: exuanbo/actions-deploy-gist@v1
with:
token: ${{ secrets.GIST_TOKEN }}
gist_id: 280257cd19cbe1dda3789bebd4ff65cf
file_path: jacoco.svg
+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@v3
with:
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
- name: Set up JDK 11
uses: actions/setup-java@v3
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
@@ -0,0 +1,39 @@
name: Unit Tests
on:
pull_request:
branches: [ master ]
jobs:
build:
name: Unit Tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Set up JDK 11
uses: actions/setup-java@v3
with:
distribution: temurin
java-version: 11
cache: gradle
- name: Make gradlew executable
run: chmod +x ./gradlew
- name: Build and Test
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: ./gradlew generateTestSource test jacocoTestReport --info -Dfull_test_suite=true
- name: Publish Test Result
uses: EnricoMi/publish-unit-test-result-action@v2
id: test-results
if: always()
with:
junit_files: build/test-results/**/*.xml
fail_on: nothing
ignore_runs: true
json_thousands_separator: .
time_unit: milliseconds
+15 -5
View File
@@ -5,9 +5,6 @@
# Ignore Gradle GUI config # Ignore Gradle GUI config
gradle-app.setting gradle-app.setting
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar
# Cache of project # Cache of project
.gradletasknamecache .gradletasknamecache
@@ -16,7 +13,6 @@ gradle-app.setting
.classpath .classpath
.project .project
gradle-wrapper.jar
---> Custom ---> Custom
!/libs/ !/libs/
@@ -34,5 +30,19 @@ gradle-wrapper.jar
/src/main/java/speiger/src/collections/doubles/* /src/main/java/speiger/src/collections/doubles/*
/src/main/java/speiger/src/collections/objects/* /src/main/java/speiger/src/collections/objects/*
#Generated Tests
/src/test/java/speiger/src/testers/booleans/*
/src/test/java/speiger/src/testers/bytes/*
/src/test/java/speiger/src/testers/shorts/*
/src/test/java/speiger/src/testers/chars/*
/src/test/java/speiger/src/testers/ints/*
/src/test/java/speiger/src/testers/longs/*
/src/test/java/speiger/src/testers/floats/*
/src/test/java/speiger/src/testers/doubles/*
/src/test/java/speiger/src/testers/objects/*
/src/test/java/speiger/src/tests/*
#Cache result #Cache result
/src/builder/resources/speiger/assets/collections/cache.bin /src/builder/resources/speiger/assets/collections/cache.bin
/src/builder/resources/speiger/assets/testers/cache.bin
/src/builder/resources/speiger/assets/tests/cache.bin
+296
View File
@@ -0,0 +1,296 @@
# Changelog of versions
### Version 0.9.0
- Added: getFirst/getLast/removeFirst/removeLast to List.class.
- Added: Dedicated Set toArray implementations.
- Added: ToArray/pushTop functions to Stack.class.
- 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: List.reversed, which returns a SubList that has all elements in reversed order and also inserts reversed.
- Added: Iterators.infinite as an option that will create a Infinite Iterator based on the inputed one.
- 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)
- Fixed: SetValue wasn't working on forEach implementations.
- Fixed: Compute functions now perform with primitives more java compliant. Meaning that getDefaultReturnValue function no longer is seen as null.
- Fixed: Supplier was using the wrong dataType in their function name.
- Updated: SimpleCodeGenerator 1.3.0 is now being used which allows for iterative code support.
- 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!
### Version 0.8.1
- Added: getFirst/getLast/removeFirst/removeLast to List.class.
- Added: Dedicated Set toArray implementations.
- Added: ToArray/pushTop functions to Stack.class.
- 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: List.reversed, which returns a SubList that has all elements in reversed order and also inserts reversed.
- Added: Iterators.infinite as an option that will create a Infinite Iterator based on the inputed one.
- 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)
- Fixed: SetValue wasn't working on forEach implementations.
- Fixed: Compute functions now perform with primitives more java compliant. Meaning that getDefaultReturnValue function no longer is seen as null.
- Fixed: Supplier was using the wrong dataType in their function name.
- Updated: SimpleCodeGenerator 1.3.0 is now being used which allows for iterative code support.
### Version 0.8.0
- Added: getFirst/getLast/removeFirst/removeLast to Lists
- Added: Dedicated implementations for toArray into TreeSets
- Fixed: forEach methods in Maps now can use "setValue" functions.
### Version 0.8.0
- Added: ISizeProvider interface (Optimization Helper)
- Added: ISizeProvider into most Iterable implementations (Distinct/Filter/FlatMap/ArrayFlatMap don't support it, for obvious reasons)
- Added: ToArray function into Iterable which uses ISizeProvider to reduce overhead of duplicating arrays.
- Added: Functions that have the same type, Int2IntFunction as example, have now a identity function.
- Added: Functions of a BooleanValue have now alwaysTrue/False function.
- Added: ForEachIndexed for all Iterable implementations
- Added: RandomGenerator support (Java17), though requires self compilation
- Added: Optimizations for HashUtils next power of function.
- Added: toArray() now returns a cached empty array if the collection is empty.
- Added: toArray function for AsyncBuilder
- Added: Modularization to the library where feature can be disabled as needed. (Requires Self-Compilation)
- Fixed: putIfAbsent now replaces defaultValues
- Fixed: OpenHashSet/Map and their Custom Variants no longer rely on List implementations.
- Fixed: ObjectCopyOnWriteList.of did create a ObjectArrayList instead of the CopyOnWrite variant.
- 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
- Breaking Change: Classes that used PrimitiveCollection functions now default to java functions where applicable, this is to increase compat.
- Breaking Change: Some function classes now get closer to javas terms. (Predicate/UnaryOperator etc)
### 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
- Added: EnumMap specialized forEach implementation.
- Added: AbstractMap.remove now delegates to its primitive counterpart.
- Added: ConcurrentHashMap now implements ITrimmable
- Refactor: Removed a lot of disabled code from ArraySet.
- Removed: LinkedList.addAll(index, List) now delegates to LinkedList.addAll(index, Collection) due to no special optimization required.
- Fixed: AbstractList.SubList.get/set/swapRemove didn't calculate their List index Properly
- Fixed: AbstractList.SubList chains now properly if you create SubLists within SubLists.
- 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.
- Fixed: CopyOnWriteArrayList.extract/removeElements(int, int) does now proper range checks and remove elements properly.
- Fixed: CopyOnWriteArrayList.SubList now works properly. (Reimplemented entirely)
- Fixed: CopyOnWriteArrayList.Iterator.previous() was returning the wrong values.
- 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.
- Fixed: LinkedList had an edge case where the entire reverse iterator would break if the wrong element was removed.
- Fixed: LinkedList.extractElement now returns the correct values.
- Fixed: AbstractMap.entrySet().remove(Object) now returns true if defaultReturnValue elements were removed.
- Fixed: ConcurrentHashMap.remove(Object, Object) checks if the type matches before comparing against null Values.
- 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.
- Fixed: ImmutableMap now compares empty values (0) against nullKeys when Object Variants of the type are used.
- Fixed: ArrayMap.iterator(key) now throws NoSuchElementException when the element wasn't found.
- Fixed: Linked/EnumMap array constructor was creating the wrong size values array.
- 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.
- Fixed: Map.Builder wasn't throwing a IllegalStateException when creating a negative size builder.
- Fixed: AVL/RBTreeSet.DecendingSet.subSet(from, fromInclusive, to, toInclusive) was creating a corrupt asending subset.
- Fixed: ArraySet throws now a IllegalStateException when trying to create it with a negative size.
- Fixed: ArraySet.addMoveToLast(key) was crashing when a key was already present.
- Fixed: Immutable/LinkedHashSet now keep track of their iteration index properly.
- Fixed: LinkedHashSet.moveToFirst/Last(key) would crash if the Set was empty.
- 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.6.2
- 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: Iterator Wrappers are now a bit more in Compliance with Java Standards.
- Added: AsyncBuilders now Support Array Inputs to create cleaner code.
- Changed: LinkedList.addBulk variable definition was triggering a false positive.
- Fixed: TreeMap.subMap().entrySet().remove() wouldn't check primitives properly.
- Fixed: SortedMap.sub/tail/headMap were looping into themselves.
- 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.
- Fixed: SubList didn't check for ranges properly or didn't use parent list to validate changes.
- Fixed: ArrayList.addElements didn't check input array fully and used the wrong variable to move the elements around.
- Fixed: LinkedList.addElements(EmptyInput) would crash.
- 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.
- Fixed: LinkedHashSet.addAndMoveToFirst wouldn't move elements to the first place.
- Fixed: ArrayList/LinkedList extractElements crashing when 0 or less elements are desired.
- Fixed: TreeMap pollFirst/LastKey should return the defaultMin/max value instead of a Empty value.
- Fixed: TreeMap keySet implementation was missing the class type implementations to pass keySet tests.
- Fixed: TreeMap.SubMap Iterator (primitive Keys) was crashing because a Null was set on to a primitive.
### Version 0.6.1
- Fixed: FIFO queue crashing when the last index is before the first index when peek is called.
- Fixed: FIFO queue only clears the array if it was in use.
- Added: Sorted Method for the stream replacing functions.
### Version 0.6.0
- Added: addOrGet for sets.
- Added: Async API which allows to easily execute Iterables/Collections offthread without the complexity.
- Added: CopyOnWriteArrayList and tests for it
- Added: Support up to Java17.
- Added: Build System now adds module-info if the Running JVM is 9 or higher
- 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: A ConcurrentHashMap implementation.
- Fixed: containsValue in the HashMap wouldn't check the nullKey
- Removed: Deprecated functions from SortedMaps/Sets
### Version 0.5.3
- Added: OrderedMap/Set
- Added: Deprecation to Functions that are specific to Ordered interfaces in the SortedMap/Set
- Added: subFrom to Maps which is the counterpart of the addTo method
- Added: pourAsList and pourAsSet (booleans excluded for sets) to Iterable
- Fixed: ArrayList.grow had a small bug where it would trigger to early causing performance problems with exact sized collections.
- Fixed: FIFOQueue size constructor had a small bug where it would trigger a array enlargement when all elements were inserted.
### Version 0.5.2
- Fixed: Bugs with Queues starting with the wrong size
- Fixed: ArrayGrowth for Queues was +1 instead of +50%
- Added: Benchmarks with java and FastUtil
### Version 0.5.1
- Fixed: Reworked the NavigableSet/Map implementations of RBTree/AVLTree/Array Sets/Maps so they are now deemed stable.
- Added: Another 150k Unit tests.
- 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: Bugs with null values for primitive collections.
- Removed: ArraySet/Map subSet/subMap implementation was removed.
### Version 0.5.0
- Added: 2 Helper functions to find out how many bits are required to store a Number.
- Added: pour function directly into Iterable which allows to collect all elements in the Iterable directly.
- Added: The new ToArray method from Java9 and newer into the library. Using a functional interface. (Just a backport)
- 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.
- Added: Unmodifiable and Synchronize wrapper functions direclty into Collection Interfaces. This is mostly a quality of life thing.
- 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: A boxed putAll array variant.
- 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: 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.
- Added: Guava TestSuit
- Fixed: HashCode and toString method would crash if the Object Key/Value was null
- 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.
- Fixed: Set.hashCode now is the sum of the elements instead of a Unique HashCode based on the elements.
- Fixed: Added missing NonNull Checks.
- Fixed: Custom/OpenHashMap.containsValue implementation was wrong.
- 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
- Fixed: Custom/Linked/OpenHashMap.keySet.remove was causing a infinite loop.
- Fixed: Custom/Linked/OpenHashMap.entrySet.contains was not correctly comparing the entry.
- 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
- Fixed: CustomOpenHashMap.keySet.forEach was basically putting out keys even if they were present
- Fixed: ImmutableMaps issues thanks to the tests. Roughly the same as the rest of the maps
- Fixed: RB/AVLTreeMaps issues. Roughly the same as the rest of the maps
- Fixed: SubLists are now properly implemented.
- Fixed: HashSet Iterator bugs now fixed... That was Painful.
- Added: Tests for Lists and Sets
### Version 0.4.5
- Added: removeAll/retainAll(Collection c, Consumer r) which receives all the elements that got deleted from the collection
- Fixed: Supplier get function wasn't referencing original function.
- Added: addIfPresent/Absent to lists
- Added: distinct, limit and peek iterators
- Added: Iterable's can now reduce its contents
- Added: Better ForEach support for IterableWrappers so a Iterator chain is not created
- Added: SwapRemove to Lists which moves the last element into the desired space to be deleted
- Added: More Test cases
### Version 0.4.4
- Fixed: ObjectArrayList.of was causing crashes because of a Poor implementation.
- Added: Unsorted HashMaps/Sets now throw Concurrent exceptions if they were modified during a rehash.
- Added: Array/Collection version of enqueue and enqueueFirst to PriorityQueues.
- Added: fillBuffer function into PrimitiveLists which allow to optimize JavaNio buffers if needed.
### Version 0.4.3
- Added: Wrapper now support the Optimized Lambda replacer functions to improve performance.
- Added: FIFO Queue has now a minimum capacity and that is now checked more consistently.
### Version 0.4.2
- Added: Lists/Sets/Maps/PriorityQueues are now copy-able. with the new copy() function.
Note: subLists/subMaps/subSets or synchronize/unmodifyable wrappers do not support that function.
- Fixed: PriorityQueues didn't implement: hashCode/equals/toString
### Version 0.4.1
- Changed: ForEach with input now provides input, value instead of value, input, this improves the usage of method references greatly
- Added: addAll with Array-types in collections.
- Added: Java Iterator/Iterable support for Stream replacing methods
- Added: Suppliers.
- Added: SupplyIfAbsent. It is ComputeIfAbsent but using suppliers
- Added: Count feature into Iterable
- Fixed: A couple bugs with the new StreamReplacing functions in LinkedCollections Iterating to Infinity
### Version 0.4.0
- Changed: Iterable specific helper functions were moved out of Iterators and moved into Iterables
- Added: New Stream replacing functions: findFirst, matchesAny/All/None
- Fixed: Compute/ComputeIfAbsent/ComputeIfPresent/Merge/BulkMerge in maps now behave like they should.
- Added: Implementations for New Stream replacing functions.
- Changed: Removed a lot of duplicated forEach implementations
- Added: Flat/Mapping functions (to object) are now accessible to primitive maps.
- Added: Filter function to Iterators/Iterables (Iterable implements it by default)
- Changed: Cleanup of some variables/mappers
- Added/Fixed: AVL/RBTreeMap got reworked and SubMaps work more properly now. Also forEach support got improved a lot
- Added/Fixed: TreeSubSets (RB/AVL) got their functional implementations improved too.
- Added: Pairs are now a thing. In Mutable/Immutable Form
### Version 0.3.6
- Fixed: addAll non Type Specific Lists was causing crashes.
- Fixed/Changed: clearAndTrim's implementation was all over the place. In some cases causing crash scenarios.
- Fixed: Wrappers didn't implement toString/equals/hashCode
- Added: Tests for addAll Bug
- Changed: Cleaned up CodeStyle as bugs were fixed.
### Version 0.3.5
- 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)
- Fixed: LinkedLists didn't implement add(Object)
- Fixed: Object Collections did have the JavaCollections deprecated as the Constructor. This should only be deprecated for Primitives
- Added: Tests with 5k Random names for Object sorting.
- 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.4
- Fixed: ArrayLists didn't resize properly if they were empty.
### Version 0.3.3
- Added: Flat/Mapping function for Iterables/Iterators to help avoid streams for cleaner looking code
- Fixed: AVLTrees pollFirst/Last is now keeping orders and is fixed
- Fixed: AbstractCollection bulk adding methods now link to the specialized implementations.
- Fixed: A bug with getElements in ArrayList.
- 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
+44
View File
@@ -0,0 +1,44 @@
### Extra Features
Primitive Collections comes with a few extra features that are disabled by default.
These will be enabled as soon they become relevant or never at all.
But some of these can be already unlocked when the target version changes.
If you compile the library for yourself you will automatically gain access to said features.
### Java17 Exclusive Features
Java17 has some new features that can sadly not really be back-ported but the library still supports them if it is compiled with java17
- RandomGenerator: Java17 has added [RandomGenerator.class](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/random/RandomGenerator.html).
This allows to use custom random implementations without having to re-implement them yourselves.
### ModuleSettings
Primitive Collections is a huge library.
But maybe you only use like 5-10 different classes.
Normally you would use tools like "Proguard" to get rid of classes that you don't use.
But since a lot of classes have dependencies on each other this would only do so much.
This is where the [ModuleSettings](ModuleSettings.json) come into play.
It allows you to turn of implementations as you wish and adjusts the code that everything still works.
There is 3 layers of control inside of the ModuleSettings.
- Modules directly at the top that turn off everything.
- Type Specific configurations, where you can for example turn of everything thats "Long" based.
- And then there is each type specific module settings.
Allowing for greater control without having to edit hundreds of lines of code.
On top of that:
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.
It will still work as the same.
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:
```
/gradlew.bat generateLimitSource build -x test
```
+168 -175
View File
@@ -1,208 +1,201 @@
Apache License Apache License
Version 2.0, December 2021
http://www.apache.org/licenses/
Version 2.0, January 2021 TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION,
AND DISTRIBUTION
1. Definitions. 1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"License" shall mean the terms and conditions for use, reproduction, and distribution "Licensor" shall mean the copyright owner or entity authorized by
as defined by Sections 1 through 9 of this document. the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"Licensor" shall mean the copyright owner or entity authorized by the copyright "You" (or "Your") shall mean an individual or Legal Entity
owner that is granting the License. exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Legal Entity" shall mean the union of the acting entity and all other entities "Object" form shall mean any form resulting from mechanical
that control, are controlled by, or are under common control with that entity. transformation or translation of a Source form, including but
For the purposes of this definition, "control" means (i) the power, direct not limited to compiled object code, generated documentation,
or indirect, to cause the direction or management of such entity, whether and conversions to other media types.
by contract or otherwise, or (ii) ownership of fifty percent (50%) or more
of the outstanding shares, or (iii) beneficial ownership of such entity.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions "Derivative Works" shall mean any work, whether in Source or Object
granted by this License. form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Source" form shall mean the preferred form for making modifications, including "Contributor" shall mean Licensor and any individual or Legal Entity
but not limited to software source code, documentation source, and configuration on behalf of whom a Contribution has been received by Licensor and
files. subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
"Object" form shall mean any form resulting from mechanical transformation 3. Grant of Patent License. Subject to the terms and conditions of
or translation of a Source form, including but not limited to compiled object this License, each Contributor hereby grants to You a perpetual,
code, generated documentation, and conversions to other media types. worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
"Work" shall mean the work of authorship, whether in Source or Object form, (a) You must give any other recipients of the Work or
made available under the License, as indicated by a copyright notice that Derivative Works a copy of this License; and
is included in or attached to the work (an example is provided in the Appendix
below).
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
"Derivative Works" shall mean any work, whether in Source or Object form, (c) You must retain, in the Source form of any Derivative Works
that is based on (or derived from) the Work and for which the editorial revisions, that You distribute, all copyright, patent, trademark, and
annotations, elaborations, or other modifications represent, as a whole, an attribution notices from the Source form of the Work,
original work of authorship. For the purposes of this License, Derivative excluding those notices that do not pertain to any part of
Works shall not include works that remain separable from, or merely link (or the Derivative Works; and
bind by name) to the interfaces of, the Work and Derivative Works thereof.
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
"Contribution" shall mean any work of authorship, including the original version You may add Your own copyright statement to Your modifications and
of the Work and any modifications or additions to that Work or Derivative may provide additional or different license terms and conditions
Works thereof, that is intentionally submitted to Licensor for inclusion in for use, reproduction, or distribution of Your modifications, or
the Work by the copyright owner or by an individual or Legal Entity authorized for any such Derivative Works as a whole, provided Your use,
to submit on behalf of the copyright owner. For the purposes of this definition, reproduction, and distribution of the Work otherwise complies with
"submitted" means any form of electronic, verbal, or written communication the conditions stated in this License.
sent to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor
for the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as "Not a Contribution."
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf 6. Trademarks. This License does not grant permission to use the trade
of whom a Contribution has been received by Licensor and subsequently incorporated names, trademarks, service marks, or product names of the Licensor,
within the Work. except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
2. Grant of Copyright License. Subject to the terms and conditions of this 7. Disclaimer of Warranty. Unless required by applicable law or
License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, agreed to in writing, Licensor provides the Work (and each
no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Contributor provides its Contributions) on an "AS IS" BASIS,
Derivative Works of, publicly display, publicly perform, sublicense, and distribute WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
the Work and such Derivative Works in Source or Object form. implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
3. Grant of Patent License. Subject to the terms and conditions of this License, 8. Limitation of Liability. In no event and under no legal theory,
each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, whether in tort (including negligence), contract, or otherwise,
no-charge, royalty-free, irrevocable (except as stated in this section) patent unless required by applicable law (such as deliberate and grossly
license to make, have made, use, offer to sell, sell, import, and otherwise negligent acts) or agreed to in writing, shall any Contributor be
transfer the Work, where such license applies only to those patent claims liable to You for damages, including any direct, indirect, special,
licensable by such Contributor that are necessarily infringed by their Contribution(s) incidental, or consequential damages of any character arising as a
alone or by combination of their Contribution(s) with the Work to which such result of this License or out of the use or inability to use the
Contribution(s) was submitted. If You institute patent litigation against Work (including but not limited to damages for loss of goodwill,
any entity (including a cross-claim or counterclaim in a lawsuit) alleging work stoppage, computer failure or malfunction, or any and all
that the Work or a Contribution incorporated within the Work constitutes direct other commercial damages or losses), even if such Contributor
or contributory patent infringement, then any patent licenses granted to You has been advised of the possibility of such damages.
under this License for that Work shall terminate as of the date such litigation
is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or 9. Accepting Warranty or Additional Liability. While redistributing
Derivative Works thereof in any medium, with or without modifications, and the Work or Derivative Works thereof, You may choose to offer,
in Source or Object form, provided that You meet the following conditions: and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
(a) You must give any other recipients of the Work or Derivative Works a copy END OF TERMS AND CONDITIONS
of this License; and
(b) You must cause any modified files to carry prominent notices stating that APPENDIX: How to apply the Apache License to your work.
You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, To apply the Apache License to your work, attach the following
all copyright, patent, trademark, and attribution notices from the Source boilerplate notice, with the fields enclosed by brackets "[]"
form of the Work, excluding those notices that do not pertain to any part replaced with your own identifying information. (Don't include
of the Derivative Works; and the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
(d) If the Work includes a "NOTICE" text file as part of its distribution, Copyright 2021 Speiger
then any Derivative Works that You distribute must include a readable copy
of the attribution notices contained within such NOTICE file, excluding those
notices that do not pertain to any part of the Derivative Works, in at least
one of the following places: within a NOTICE text file distributed as part
of the Derivative Works; within the Source form or documentation, if provided
along with the Derivative Works; or, within a display generated by the Derivative
Works, if and wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and do not modify the
License. You may add Your own attribution notices within Derivative Works
that You distribute, alongside or as an addendum to the NOTICE text from the
Work, provided that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and may provide Licensed under the Apache License, Version 2.0 (the "License");
additional or different license terms and conditions for use, reproduction, you may not use this file except in compliance with the License.
or distribution of Your modifications, or for any such Derivative Works as You may obtain a copy of the License at
a whole, provided Your use, reproduction, and distribution of the Work otherwise
complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any http://www.apache.org/licenses/LICENSE-2.0
Contribution intentionally submitted for inclusion in the Work by You to the
Licensor shall be under the terms and conditions of this License, without
any additional terms or conditions. Notwithstanding the above, nothing herein
shall supersede or modify the terms of any separate license agreement you
may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, Unless required by applicable law or agreed to in writing, software
trademarks, service marks, or product names of the Licensor, except as required distributed under the License is distributed on an "AS IS" BASIS,
for reasonable and customary use in describing the origin of the Work and WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
reproducing the content of the NOTICE file. See the License for the specific language governing permissions and
limitations under the License.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to
in writing, Licensor provides the Work (and each Contributor provides its
Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied, including, without limitation, any warranties
or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR
A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness
of using or redistributing the Work and assume any risks associated with Your
exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether
in tort (including negligence), contract, or otherwise, unless required by
applicable law (such as deliberate and grossly negligent acts) or agreed to
in writing, shall any Contributor be liable to You for damages, including
any direct, indirect, special, incidental, or consequential damages of any
character arising as a result of this License or out of the use or inability
to use the Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all other commercial
damages or losses), even if such Contributor has been advised of the possibility
of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work
or Derivative Works thereof, You may choose to offer, and charge a fee for,
acceptance of support, warranty, indemnity, or other liability obligations
and/or rights consistent with this License. However, in accepting such obligations,
You may act only on Your own behalf and on Your sole responsibility, not on
behalf of any other Contributor, and only if You agree to indemnify, defend,
and hold each Contributor harmless for any liability incurred by, or claims
asserted against, such Contributor by reason of your accepting any such warranty
or additional liability. END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets "[]" replaced with your own identifying
information. (Don't include the brackets!) The text should be enclosed in
the appropriate comment syntax for the file format. We also recommend that
a file or class name and description of purpose be included on the same "printed
page" as the copyright notice for easier identification within third-party
archives.
Copyright 2021 Speiger
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+2625
View File
File diff suppressed because it is too large Load Diff
+86 -15
View File
@@ -1,22 +1,93 @@
# Primitive-Collections (To be Renamed) ![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)
![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)
![GitHub commit activity](https://img.shields.io/github/commit-activity/m/Speiger/Primitive-Collections)
![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)
[![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)
# Primitive-Collections
This is a Simple Primitive Collections Library aimed to outperform Java's Collection Library and FastUtil.
Both in Performance and Quality of Life Features.
This is a Simple Primitive Collections Library i started as a hobby Project. ## Benchmarks
It is based on Java's Collection Library and FastUtil. Benchmarks can be found here: [[Charts]](https://github.com/Speiger/Primitive-Collections-Benchmarks/blob/master/BENCHMARKS-CHARTS.md), [[Tables]](https://github.com/Speiger/Primitive-Collections-Benchmarks/blob/master/BENCHMARKS.md)
But its focus is a different one.
## Main Features: ## Special Features
ArraysList, HashSet/Map (Linked & HashControl), TreeSet/Map (RB & AVL), Priority Queue. [Here](features.md) you find a set of features added to Primitive Collections.
These are designed to improve performance or to provide Quality of Life.
[Here](EXTRAS.md) you also find features that can be used when you compile the library for yourself.
These features are not used by default to have a wider range of compat, or require self compilation.
Such as pruning classes that are not needed in your code.
## Main Features:
- ArrayLists / LinkedLists / CopyOnWriteLists
- HashSets/Maps (Linked & HashControl)
- TreeSets/Maps (RB & AVL)
- EnumMaps
- Immutable Maps/Lists/Sets
- ConcurrentHashMaps
- Priority Queues
- Streams & Functional Queries
- Split/Iterators
- Pairs
- Unary/Functions
- Suppliers
- Bi/Consumers
- AsyncBuilders
# Notes about Versions
Any 0.x.0 version (Minor) can be reason for massive changes including API.
To ensure that problems can be dealt with even if it is breaking the current API.
# How to install
Using Jitpack Gradle
```groovy
repositories {
maven {
url = "https://jitpack.io"
}
}
dependencies {
implementation 'com.github.Speiger:Primitive-Collections:0.9.0'
}
```
Using Maven Central
```groovy
dependencies {
implementation 'io.github.speiger:Primitive-Collections:0.9.0'
}
```
# SourceCode
The generated Sourcecode can be automatically build,
but if you want to just browse around in it.
Check out the [Debug Branch](https://github.com/Speiger/Primitive-Collections/tree/debug/src/main/java/speiger/src/collections), which has the entire up to date code.
# Contributing
If you want to contribute.
This project is created using gradle and java and my Template Library only. Nothing extra.
If you setup gradle the library will be downloaded automatically.
Where is everything stored?
- Variables and ClassNames are define [here](src/builder/java/speiger/src/builder/GlobalVariables.java)
- Templates are stored [here](src/builder/resources/speiger/assets/collections/templates)
- Tests can be found [here](src/test/java/speiger/src/collections)
Please if you want to contribute follow the [Rule-Sheet](RuleSheet.md). It keeps everything in line.
# Guide # How to Build
The SourceCode can be already generated via: The SourceCode can be generated via:
```
/gradlew.bat generateSource /gradlew.bat generateSource
to build the jar ```
/gradlew.bat build
do not combine the commands because they can not be executed at the same time.
## Current Down Sides (Random order) to generate SourceCode and build the jar:
- EnumMaps are only normal maps no Linked Support yet ```
- Testing for Sub Maps/Sets/Lists are only in a very basic way tested /gradlew.bat build
- Documentation is only present at the lowest level for most cases and needs a typo fixing. ```
+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.
+320 -30
View File
@@ -1,5 +1,7 @@
plugins { plugins {
id 'java-library' id 'java-library'
id "jacoco"
// id "com.vanniktech.maven.publish" version "0.28.0"
} }
tasks.withType(JavaCompile) { tasks.withType(JavaCompile) {
@@ -8,18 +10,27 @@ tasks.withType(JavaCompile) {
apply plugin: 'java' apply plugin: 'java'
apply plugin: 'eclipse' apply plugin: 'eclipse'
apply plugin: 'maven-publish'
apply plugin: 'signing'
repositories { repositories {
jcenter() mavenCentral()
flatDir { maven {
dirs 'libs' url = "https://maven.speiger.com/repository/main"
} }
} }
archivesBaseName = 'Primitive Collections' archivesBaseName = 'Primitive Collections'
version = 'Beta'; version = RELEASE_VERSION;
sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = '1.8' sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = JavaVersion.current();
System.out.println("Java Version: "+compileJava.sourceCompatibility)
java {
withJavadocJar()
withSourcesJar()
}
javadoc { javadoc {
options.tags = [ "implSpec", "note" ] options.tags = [ "implSpec", "note" ]
@@ -29,21 +40,9 @@ eclipse {
classpath { classpath {
downloadJavadoc = true downloadJavadoc = true
downloadSources = true downloadSources = true
file {
whenMerged {
//Enforce a custom container and allowing access to the sun.misc package which is nessesary for EnumMaps
entries.find{ it.kind == 'con' && it.path.startsWith('org.eclipse.jdt')}.path = 'org.eclipse.jdt.launching.JRE_CONTAINER';
}
}
} }
} }
compileJava {
options.compilerArgs << '-XDignore.symbol.file'
options.fork = true // may not needed on 1.8
options.forkOptions.executable = 'javac' // may not needed on 1.8
}
sourceSets { sourceSets {
builder builder
} }
@@ -53,8 +52,11 @@ configurations {
} }
dependencies { dependencies {
compile 'SimpleCodeGenerator:Simple Code Generator:1.0.1' builderImplementation 'com.google.code.gson:gson:2.10'
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'
} }
task generateSource(type: JavaExec) { task generateSource(type: JavaExec) {
@@ -64,26 +66,314 @@ task generateSource(type: JavaExec) {
main = 'speiger.src.builder.PrimitiveCollectionsBuilder' main = 'speiger.src.builder.PrimitiveCollectionsBuilder'
} }
task javadocJar(type: Jar) { task generateGithubSource(type: JavaExec) {
from javadoc group = 'internal'
classifier = 'javadoc' description = 'Builds the sourcecode for Github Actions'
classpath = sourceSets.builder.runtimeClasspath
main = 'speiger.src.builder.PrimitiveCollectionsBuilder'
args = ['silent']
} }
task srcJar(type: Jar) { task forceGenerateSource(type: JavaExec) {
from sourceSets.main.allSource group = 'internal'
classifier = 'sources' description = 'Builds the sourcecode forceful'
classpath = sourceSets.builder.runtimeClasspath
main = 'speiger.src.builder.PrimitiveCollectionsBuilder'
args = ['force']
} }
task generateTestSource(type: JavaExec) {
group = 'internal'
description = 'Builds the sourcecode for the Tests'
classpath = sourceSets.builder.runtimeClasspath
main = 'speiger.src.builder.PrimitiveCollectionsBuilder'
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) {
group = 'internal'
description = 'Builds the Sourcecode with the ModuleSettings.json applied'
classpath = sourceSets.builder.runtimeClasspath
main = 'speiger.src.builder.PrimitiveCollectionsBuilder'
args = ['silent', 'load']
}
compileJava.dependsOn generateGithubSource
javadoc.failOnError = false javadoc.failOnError = false
javadoc.options.memberLevel = JavadocMemberLevel.PUBLIC javadoc.options.memberLevel = JavadocMemberLevel.PUBLIC
//javadoc.options.showAll()
javadoc.options.quiet() javadoc.options.quiet()
artifacts {
archives javadocJar task testBooleans(type: Test) {
archives srcJar group 'tests'
description 'Tests all Boolean Collections'
filter {
excludeTestsMatching "speiger.src.testers.**.*"
includeTestsMatching "speiger.src.tests.booleans.**.*"
}
useJUnit()
ignoreFailures = true
maxHeapSize = maxMemory
}
task testBytes(type: Test) {
group 'tests'
description 'Tests all Byte Collections'
filter {
excludeTestsMatching "speiger.src.testers.**.*"
includeTestsMatching "speiger.src.tests.bytes.**.*"
}
useJUnit()
ignoreFailures = true
maxHeapSize = maxMemory
maxParallelForks = testThreads as Integer
}
task testShorts(type: Test) {
group 'tests'
description 'Tests all Short Collections'
filter {
excludeTestsMatching "speiger.src.testers.**.*"
includeTestsMatching "speiger.src.tests.shorts.**.*"
}
useJUnit()
ignoreFailures = true
maxHeapSize = maxMemory
maxParallelForks = testThreads as Integer
}
task testChars(type: Test) {
group 'tests'
description 'Tests all Character Collections'
filter {
excludeTestsMatching "speiger.src.testers.**.*"
includeTestsMatching "speiger.src.tests.chars.**.*"
}
useJUnit()
ignoreFailures = true
maxHeapSize = maxMemory
maxParallelForks = testThreads as Integer
}
task testInts(type: Test) {
group 'tests'
description 'Tests all Int Collections'
filter {
excludeTestsMatching "speiger.src.testers.**.*"
includeTestsMatching "speiger.src.tests.ints.**.*"
}
useJUnit()
ignoreFailures = true
maxHeapSize = maxMemory
maxParallelForks = testThreads as Integer
}
task testLongs(type: Test) {
group 'tests'
description 'Tests all Long Collections'
filter {
excludeTestsMatching "speiger.src.testers.**.*"
includeTestsMatching "speiger.src.tests.longs.**.*"
}
useJUnit()
ignoreFailures = true
maxHeapSize = maxMemory
maxParallelForks = testThreads as Integer
}
task testFloats(type: Test) {
group 'tests'
description 'Tests all Float Collections'
filter {
excludeTestsMatching "speiger.src.testers.**.*"
includeTestsMatching "speiger.src.tests.floats.**.*"
}
useJUnit()
ignoreFailures = true
maxHeapSize = maxMemory
maxParallelForks = testThreads as Integer
}
task testDoubles(type: Test) {
group 'tests'
description 'Tests all Double Collections'
filter {
excludeTestsMatching "speiger.src.testers.**.*"
includeTestsMatching "speiger.src.tests.doubles.**.*"
}
useJUnit()
ignoreFailures = true
maxHeapSize = maxMemory
maxParallelForks = testThreads as Integer
}
task testObjects(type: Test) {
group 'tests'
description 'Tests all Object Collections'
filter {
excludeTestsMatching "speiger.src.testers.**.*"
includeTestsMatching "speiger.src.tests.objects.**.*"
}
useJUnit()
ignoreFailures = true
maxHeapSize = maxMemory
maxParallelForks = testThreads as Integer
}
if(System.getProperty("full_test_suite", "false").toBoolean()) {
test.dependsOn testBooleans
test.dependsOn testBytes
test.dependsOn testShorts
test.dependsOn testChars
test.dependsOn testInts
test.dependsOn testLongs
test.dependsOn testFloats
test.dependsOn testDoubles
test.dependsOn testObjects
} }
test { test {
useJUnit() filter {
} excludeTestsMatching "speiger.src.testers.**.*"
excludeTestsMatching "speiger.src.tests.**.*"
excludeTestsMatching "tests.**.*"
}
useJUnit()
ignoreFailures = true
maxHeapSize = maxMemory
}
jacocoTestReport {
executionData fileTree(project.buildDir.absolutePath).include("jacoco/*.exec")
reports {
xml.required = true
html.required = true
csv.required = true
}
}
publishing {
publications {
personal(MavenPublication) {
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
artifactId = project.archivesBaseName.replace(" ", "-")
groupId = 'de.speiger'
from components.java
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 {
url = 'https://github.com/Speiger/Primitive-Collections'
}
issueManagement {
system = 'github'
url = 'https://github.com/Speiger/Primitive-Collections/issues'
}
}
}
}
repositories {
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"
credentials(PasswordCredentials) {
username auth?[0]
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'
// }
// }
//}
//
+402
View File
@@ -0,0 +1,402 @@
## Quality Of Life Features
New Specialized functions/classes that were added to increase performance and/or reduce allocations and/or for Quality of life.
# Functions
Functions that increase performance or are quality of life in their nature.
<details>
<summary>Iterable</summary>
<p>
## Functional Functions
Java adds themselves a lot of functional functions like,
- Stream:
- Map/FlatMap
- Filter/Distinct/Limit/Sorted
- Count/FindFirst/Collect
- Peek/ForEach/Reduce
- anyMatch/allMatch/NoneMatch
that allows to process a collection in a functional way.
But these require streams which have a lot of Overhead in their nature.
Luckly Primitive Collections adds replacement functions that provide the same functionality but with minimal overhead.
Here are some examples:
```java
public ObjectIterable<Path> toPath(ObjectIterable<String> iterable) {
return iterable.map(Paths::get).filter(Files::exist);
}
public Iterable<Path> toPath(Iterable<String> iterable) {
return ObjectIterables.map(iterable, Paths::get).filter(Files::exist);
}
public int sum(IntIterable iterable) {
return iterable.reduce(Integer::sum);
}
```
## AsyncAPI</summary>
The AsyncAPI is a Feature that simplifies the processing of Collections on a separate thread.
It uses the same concept as Javas Stream API but uses the light weight Functions from Primitive Collections to achieve the same thing.
Unlike Javas StreamAPI the AsyncAPI is always singleThreaded and more like Javas CompletableFuture, which you can await or let run Asynchronous.
The Goal is it to simplify the processing of Collections asynchronous.
Especially on tasks which don't have to be finished instantly but can be processed on the side.
Here is a example of how the API works.
```java
public void processFiles(ObjectCollection<String> potentialFiles) {
potentialFiles.asAsync()
.map(Paths::get).filter(Files::exists) //Modifies the collection (Optional)
.forEach(Files::delete) //Creates the action (Required)
.callback(T -> {}} //Callback on completion, still offthread (Optional)
.execute() //Starts the task. (Required)
}
```
</p>
</details>
<details>
<summary>Collection</summary>
<p>
These are functions specific to the Collections interface, stuff that everyone wished it was present to be in the first place.
## AddAll (Array)
Adding Elements to a Collection usually requires either a for loop or a Arrays.wrap().
This isn't an issue with Primitive Collections.
```java
public void addMonths(ObjectCollection<String> months) {
months.addAll("January", "February", "March", "April", "May", "June", "July", "August", "September, "October", November", "December");
}
public void addElements(ObjectCollection<String> result, String[] elements) {
result.addAll(elements, 0, 5); //elements, offset, length
}
```
## containsAny
Everyone hates comparing if 2 collections have part of each other included.
The solution usually requires for loops and keeping track if things were found or not.
And every Java Developer had this issue at least once and wished for a clean solution.
```java
public boolean hasMonths(ObjectCollection<Month> target, Collection<Month> toFind) {
return target.containsAny(toFind);
}
```
## Copy
Collections get copied every now and then. There is only 2 ways that this happens.
Javas Clone API or using Constructor that supports collections.
Javas Clone API is kinda in a Zombie state, where it is supported or not. Its not really clear if you should use it or not.
The Clone CloneNotSupportedException isn't helping either, causing more janky code.
While a Constructor can only support so much and testing for every case isn't really viable.
So the decision was made to straight out not support clone and instead add a copy function which doesn't use a checked exception.
It works exactly like the clone function. In a sense where it creates a shallow copy. (SubCollections do not work for obvious reasons)
```java
public IntCollection copy(IntCollection original) {
return original.copy();
}
```
## Primitive Streams
Since Javas Stream API is still really useful, even at its shortcomings, Primitive Collections provides easy access to it.
Generic Streams and the closest Primitive Stream will be provided. So a FloatCollection goes to a DoubleStream.
```java
public IntStream createStream(IntCollection source) {
return source.primitiveStream();
}
```
## RemoveAll/RetainAll with listener
Ever wanted use removeAll or retainAll and wanted to know what elements actually got deleted?
The usual solution is to create a copy and then apply it to the original and cross reference them.
Which leads to really messy code and just hasn't a clean solution.
Luckly Primitive Collections got you covered.
```java
public void removeInvalidFiles(ObjectCollections<Path> files, ObjectCollection<Path> toRemove) {
files.removeAll(toRemove, T -> System.out.println(T));
}
public void removeInvalidFiles(ObjectCollections<Path> files, ObjectCollection<Path> toKeep) {
files.retainFiles(toKeep, T -> System.out.println(T));
}
```
## ToArray
Primitive Collections supports primitive/generic toArray functions for its Primitive Collections.
On top of that the Object side gets a Java9 function ported back to java8, which uses a functional Interface to create the backing array.
```java
public Integer[] toArray(IntCollection c) {
return c.toArray(new Integer[c.size]);
}
public int[] toArray(IntCollection c) {
return c.toIntArray();
}
public String[] toArray(ObjectCollection<String> c) {
return c.toArray(String::new);
}
```
</p>
</details>
<details>
<summary>List</summary>
<p>
These functions are List specific functions, a couple of these are from FastUtil.
## add/get/remove/extractElements
These functions really useful helper functions. 3 of which are copied from FastUtil. (extract is from Primitive Collections)
They are basically array forms of addAll, getAll, removeRange and removeAndGetRange. This is the simplest way to describe it.
Here some example:
```java
public void addAll(DoubleList list) {
list.addElements(0D, 12.2D, 3.5D, 4.2D);
}
public double[] getAll(DoubleList list, int amount) {
double[] result = new double[amount];
list.getElements(0, result);
return result;
}
public void removeRange(FloatList list) {
list.removeElements(5, 14);
}
public float[] extractRange(FloatList list) {
return list.extractElements(5, 14); //Returns the removed elements
}
```
## addIfPresent/addIfAbsent
These two functions are simple helper functions that check internally if a element is present or absent before adding them to the List.
Removing the need for a contains or indexOf check every time you want to add a element.
While it is of course better to use a set, there is cases where this is still useful.
```java
public void addElements(IntList list, int... numbersToAdd) {
for(int e : numbersToAdd) {
list.addIfAbsent(e);
}
}
public void addExisting(ObjectList<String> list, String... textToAdd) {
for(String s : textToAdd) {
list.addIfPresent(s);
}
}
```
## SwapRemove
Lists when removing a Element shift usually the backing array to the left based to shrink the elements.
While that isn't computational expensive with LinkedLists, it is with ArrayLists.
Here comes swapRemove into play, which just removes the desired elements and instead of shifting left puts the last element in its place.
This reduces the data copying required down to 1 element instead of an array.
```java
public int remove(IntList elements, int indexToRemove) {
return elements.swapRemove(indexToRemove);
}
```
## Unstable Sort (From FastUtil)
Unstable Sort uses a Faster but not as stable sorting algorithm to sort the Collection.
Stable doesn't mean crashing, but more like that the result isn't exactly perfectly sorted.
```java
public void sort(List<Month> list, Comparator<Month> sorter) {
list.unstableSort(sorter);
}
```
</p>
</details>
<details>
<summary>Map</summary>
<p>
These functions are based on the Map interface. Useful functions you really would want.
## addTo/subFrom
addTo (from FastUtil) and subFrom are mathematically functions that either add or subtract from the value of a given key.
And if the key isn't present or would result in the default value it will either add or remove the entry from the Map. Given the circumstance.
This is a really useful function and I wish FastUtil made it accessible by default but sadly it isn't.
To simplify the explanation:
- addTo if no element is present puts in the desired number, otherwise it sums up the two values.
- subFrom if a element is present subtracts from it, if the element reaches the default value it removes the element from the map. If not present it will be ignored.
```java
public void addTo(Object2DoubleMap<Month> map, Month key, double averageTrainsRepaired) {
map.addTo(key, averageTrainsRepaired);
}
public void subFrom(Long2IntMap map, long key, double amount) {
map.subFrom(key, amount);
}
```
## addToAll
Simple bulk version of the addTo function since sometimes you want to merge 2 maps for summing.
Especially if your work is multi-threaded this can become useful.
```java
public void addTo(Object2DoubleMap<Month> map, Object2DoubleMap<Month> trainsRepaired) {
map.addToAll(trainsRepaired);
}
```
## mergeAll
This is a simple bulk version of merge since merging 2 maps is more frequent then people might think and leads to cleaner code too.
```java
public void merge(Long2ByteMap result, Long2ByteMap toMerge) {
result.mergeAll(toMerge);
}
```
## putAll (Array)
This allows to put keys and values as arrays instead of requiring a WrapperMap to insert the elements.
Not as useful as the Collections.addAll variant but still really useful.
```java
public void putAll(Int2DoubleMap map, int[] keys, double[] values) {
map.put(keys, values, 2, 15);
}
```
## putAllIfAbsent
putAll has this usual quirk where if a element is present it will replace the value, and sometimes this is not wanted.
While putIfAbsent exists it has no real mass form and makes iterative solutions really uneasy to use.
Here comes the helper function that gets rid of that problem.
```java
public void merge(Long2ObjectMap<String> regionFiles, Long2ObjectMap<String> toAdd) {
regionFiles.putAllIfAbsent(toAdd);
}
```
## removeOrDefault
getOrDefault is a really useful function that find use cases all the time.
Sadly by default there is no variant of removeOrDefault, while it has less cases still could be used every now and then.
This function basically tries to remove a element, if it is not present it will just return your desired default.
```java
public Path removeCache(Long2ObjectMap<Path> caches, long key) {
return caches.removeOrDefault(key, Paths.get("nuclearFun"));
}
```
## supplyIfAbsent
This one is one of my favorites. computeIfAbsent is a really useful function.
But in 90% of the cases I use it the value is a collection.
This becomes really annoying since methodReferences are faster/cleaner then Lambdas in my opinion.
supplyIfAbsent is basically computeIfAbsent but without a key, perfect for the default constructor of a collection.
This is the whole reason it exists.
```java
public void example(Int2ObjectMap<List<String>> map, Int2ObjectMap<String> toAdd) {
for(Entry<String> entry : toAdd.entrySet()) {
map.supplyIfAbsent(entry.getKey(), ObjectArrayList::new).add(entry.getValue());
}
}
```
</p>
</details>
# Interfaces
Interfaces that provide essential or quality of life features.
<details>
<summary>ITrimmable</summary>
<p>
The ITrimmable is Accessor interface that allows you to access a couple helper functions to control the size of your collections.
This was created for the constant casting requirement to implementations just to shrink collections which get annoying over time.
## trim
This function basically trims down the backing implementation to use as little memory as required to store the elements in the collection.
Optionally a desired minimum size can be provided as of how low it should go at worst.
## clearAndTrim
when you want to reset a Collection completely you have 2 options. Clear it and then call trim, or recreate the collection.
clearAndTrim solves this problem by clearing the collection and trimming it in one go, reducing overhead to achieve such a thing.
</p>
</details>
<details>
<summary>IArray</summary>
<p>
IArray is a Accessor interface that provides more access to collections by providing tools to grow your collection as needed.
While putAll/addAll try to ensure that you have enough room for your elements, this is not really a solution for all cases.
Sometimes you need to ensure the Collection is pre-initialized.
IArray grants you that control.
There is also a type specific that provides you access to the backing array implementation of Lists for faster Iteration but that is a really specific case.
## ensureCapacity
Ensures that your collection has enough storage for the elements you want to insert.
## elements (ITypeSpecificArray)
Allows you access to the backing array of a List which is for people who know what they are doing.
There is a lambda version of this function too which makes sure for synchronizedLists that you are the only one accessing the array.
</p>
</details>
<details>
<summary>OrderedMap</summary>
<p>
The OrderedMap is a real edge case interface that was born for a need.
FastUtil added functions that were like moveToFirst which were hardcoded to the implementation.
They didn't fit into something like a SortedMap because the Set wasn't sorted.
So OrderedMap was born, which isn't random but ordered in a specific way that can be changed.
## getAndMoveToFirst/getAndMoveToLast
Returns a desired element and removing it to the first/last spot in the Map. Moving the element that was at its spot after/before it.
## moveToFirst/moveToLast
Moves the element if present to the first/last spot in the Map. Moving the element that was at its spot after/before it.
Returns true if the element was actually moved.
## putAndMoveToFirst/putAndMoveToLast
Adds the desired element and moves it to first/last spot in the Map. Moving the element that was at its spot after/before it.
## firstKey/lastKey (Optional poll)
Provides access to the current first/last key of the Map.
Optionally can be polled if desired.
## firstValue/lastValue
Provides access to the current first/last value of the Map.
</p>
</details>
<details>
<summary>OrderedSet</summary>
<p>
The OrderedSet is a real edge case interface that was born for a need.
FastUtil added functions that were like moveToFirst which were hardcoded to the implementation.
They didn't fit into something like a SortedSet because the Set wasn't sorted.
So OrderedSet was born, which isn't random but ordered in a specific way that can be changed.
## addAndMoveToFirst/addAndMoveToLast
Adds the desired element and moves it to first/last spot in the Collection. Moving the element that was at its spot after/before it.
## moveToFirst/moveToLast
Moves the element if present to the first/last spot in the Collection. Moving the element that was at its spot after/before it.
Returns true if the element was actually moved.
## first/last (Optional poll)
Provides access to the current first/last element of the set.
Optionally can be polled if desired.
</p>
</details>
+6
View File
@@ -0,0 +1,6 @@
org.gradle.jvmargs=-Xmx3G
maxMemory = 1024m
testThreads = 4
RELEASE_VERSION = 0.9.0
Binary file not shown.
+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-6.0-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.1-bin.zip
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
+6
View File
@@ -0,0 +1,6 @@
jdk:
- openjdk9
install:
- chmod +x ./gradlew
- ./gradlew build publishToMavenLocal
Binary file not shown.
Binary file not shown.
@@ -3,15 +3,15 @@ package speiger.src.builder;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public enum ClassType public enum ClassType
{ {
BOOLEAN("boolean", "Boolean", "Boolean", "booleans", "BOOLEAN", "false"), BOOLEAN("boolean", "Boolean", "Boolean", "booleans", "BOOLEAN", "false", "false"),
BYTE("byte", "Byte", "Byte", "bytes", "BYTE", "(byte)0"), BYTE("byte", "Byte", "Byte", "bytes", "BYTE", "(byte)0", "(byte)-1"),
SHORT("short", "Short", "Short", "shorts", "SHORT", "(short)0"), SHORT("short", "Short", "Short", "shorts", "SHORT", "(short)0", "(short)-1"),
CHAR("char", "Character", "Char", "chars", "CHAR", "(char)0"), CHAR("char", "Character", "Char", "chars", "CHAR", "(char)0", "(char)-1"),
INT("int", "Integer", "Int", "ints", "INT", "0"), INT("int", "Integer", "Int", "ints", "INT", "0", "-1"),
LONG("long", "Long", "Long", "longs", "LONG", "0L"), LONG("long", "Long", "Long", "longs", "LONG", "0L", "-1L"),
FLOAT("float", "Float", "Float", "floats", "FLOAT", "0F"), FLOAT("float", "Float", "Float", "floats", "FLOAT", "0F", "-1F"),
DOUBLE("double", "Double", "Double", "doubles", "DOUBLE", "0D"), DOUBLE("double", "Double", "Double", "doubles", "DOUBLE", "0D", "-1D"),
OBJECT("T", "T", "Object", "objects", "OBJECT", "null"); OBJECT("T", "T", "Object", "objects", "OBJECT", "null", "null");
String keyType; String keyType;
String classType; String classType;
@@ -19,8 +19,9 @@ public enum ClassType
String pathType; String pathType;
String capType; String capType;
String emptyValue; String emptyValue;
String invalidValue;
private ClassType(String keyType, String classType, String fileType, String pathType, String capType, String emptyValue) private ClassType(String keyType, String classType, String fileType, String pathType, String capType, String emptyValue, String invalidValue)
{ {
this.keyType = keyType; this.keyType = keyType;
this.classType = classType; this.classType = classType;
@@ -28,6 +29,7 @@ public enum ClassType
this.pathType = pathType; this.pathType = pathType;
this.capType = capType; this.capType = capType;
this.emptyValue = emptyValue; this.emptyValue = emptyValue;
this.invalidValue = invalidValue;
} }
public String getKeyType() public String getKeyType()
@@ -50,6 +52,11 @@ public enum ClassType
return classType; return classType;
} }
public String getClassPath()
{
return this == OBJECT ? "Object" : classType;
}
public String getClassType(boolean value) public String getClassType(boolean value)
{ {
return value && this == OBJECT ? "V" : classType; return value && this == OBJECT ? "V" : classType;
@@ -90,6 +97,11 @@ public enum ClassType
return emptyValue; return emptyValue;
} }
public String getInvalidValue()
{
return invalidValue;
}
public boolean isObject() public boolean isObject()
{ {
return this == OBJECT; return this == OBJECT;
@@ -102,7 +114,7 @@ public enum ClassType
public boolean needsCustomJDKType() public boolean needsCustomJDKType()
{ {
return this == BYTE || this == SHORT || this == CHAR || this == FLOAT; return this == BOOLEAN || this == BYTE || this == SHORT || this == CHAR || this == FLOAT;
} }
public boolean needsCast() public boolean needsCast()
@@ -121,6 +133,12 @@ public enum ClassType
} }
} }
public String getApply(ClassType other) {
if(other == BOOLEAN) return "test";
if(other == ClassType.OBJECT) return "apply";
return "applyAs"+other.getFileType();
}
public String getEquals(boolean not) public String getEquals(boolean not)
{ {
switch(this) switch(this)
@@ -1,383 +0,0 @@
package speiger.src.builder;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.function.UnaryOperator;
import speiger.src.builder.mappers.ArgumentMapper;
import speiger.src.builder.mappers.IMapper;
import speiger.src.builder.mappers.InjectMapper;
import speiger.src.builder.mappers.LineMapper;
import speiger.src.builder.mappers.SimpleMapper;
import speiger.src.builder.processor.TemplateProcess;
@SuppressWarnings("javadoc")
public class GlobalVariables
{
List<IMapper> operators = new ArrayList<>();
Set<String> flags = new LinkedHashSet<>();
ClassType type;
ClassType valueType;
public GlobalVariables(ClassType type, ClassType subType)
{
this.type = type;
valueType = subType;
}
public GlobalVariables createVariables()
{
addSimpleMapper("VALUE_PACKAGE", valueType.getPathType());
addSimpleMapper("PACKAGE", type.getPathType());
addSimpleMapper("CLASS_TYPE", type.getClassType());
addSimpleMapper("CLASS_VALUE_TYPE", valueType.getClassValueType());
addSimpleMapper("KEY_TYPE", type.getKeyType());
addSimpleMapper("VALUE_TYPE", valueType.getValueType());
addSimpleMapper("EMPTY_KEY_VALUE", type.getEmptyValue());
addSimpleMapper("EMPTY_VALUE", valueType.getEmptyValue());
addSimpleMapper(" KEY_GENERIC_TYPE", type.isObject() ? "<"+type.getKeyType()+">" : "");
addSimpleMapper(" KEY_KEY_GENERIC_TYPE", type.isObject() ? "<"+type.getKeyType()+", "+type.getKeyType()+">" : "");
addSimpleMapper(" VALUE_GENERIC_TYPE", valueType.isObject() ? "<"+valueType.getValueType()+">" : "");
addSimpleMapper(" VALUE_VALUE_GENERIC_TYPE", valueType.isObject() ? "<"+valueType.getValueType()+", "+valueType.getValueType()+">" : "");
addSimpleMapper(" KEY_VALUE_GENERIC_TYPE", type.isObject() ? (valueType.isObject() ? "<"+type.getKeyType()+", "+valueType.getValueType()+">" : "<"+type.getKeyType()+">") : (valueType.isObject() ? "<"+valueType.getValueType()+">" : ""));
addSimpleMapper(" KEY_VALUE_VALUE_GENERIC_TYPE", type.isObject() ? (valueType.isObject() ? "<"+type.getKeyType()+", "+valueType.getValueType()+", "+valueType.getValueType()+">" : "<"+type.getKeyType()+">") : (valueType.isObject() ? "<"+valueType.getValueType()+", "+valueType.getValueType()+">" : ""));
addSimpleMapper(" NO_GENERIC_TYPE", type.isObject() ? "<?>" : "");
addSimpleMapper(" NO_KV_GENERIC_TYPE", type.isObject() ? (valueType.isObject() ? "<?, ?>" : "<?>") : valueType.isObject() ? "<?>" : "");
addSimpleMapper(" KEY_COMPAREABLE_TYPE", type.isObject() ? "<"+type.getKeyType()+" extends Comparable<T>>" : "");
addSimpleMapper(" KEY_SUPER_GENERIC_TYPE", type.isObject() ? "<? super "+type.getKeyType()+">" : "");
addSimpleMapper(" VALUE_SUPER_GENERIC_TYPE", valueType.isObject() ? "<? super "+valueType.getValueType()+">" : "");
addSimpleMapper(" KEY_VALUE_SUPER_GENERIC_TYPE", type.isObject() ? (valueType.isObject() ? "<? super "+type.getKeyType()+", ? super "+valueType.getValueType()+">" : "<? super "+type.getKeyType()+">") : (valueType.isObject() ? "<? super "+valueType.getValueType()+">" : ""));
addSimpleMapper(" KEY_ENUM_VALUE_GENERIC_TYPE", type.isObject() ? (valueType.isObject() ? "<"+type.getKeyType()+" extends Enum<"+type.getKeyType()+">, "+valueType.getValueType()+">" : "<"+type.getKeyType()+" extends Enum<"+type.getKeyType()+">>") : (valueType.isObject() ? "<"+valueType.getValueType()+">" : ""));
addSimpleMapper(" KEY_VALUE_ENUM_GENERIC_TYPE", type.isObject() ? (valueType.isObject() ? "<"+type.getKeyType()+", "+valueType.getValueType()+" extends Enum<"+valueType.getValueType()+">>" : "<"+type.getKeyType()+">") : (valueType.isObject() ? "<"+valueType.getValueType()+" extends Enum<"+valueType.getValueType()+">>" : ""));
addSimpleMapper(" GENERIC_KEY_BRACES", type.isObject() ? " <"+type.getKeyType()+">" : "");
addSimpleMapper(" GENERIC_VALUE_BRACES", type.isObject() ? " <"+valueType.getValueType()+">" : "");
addSimpleMapper(" GENERIC_KEY_VALUE_BRACES", type.isObject() ? (valueType.isObject() ? " <"+type.getKeyType()+", "+valueType.getValueType()+">" : " <"+type.getKeyType()+">") : (valueType.isObject() ? " <"+valueType.getValueType()+">" : ""));
addSimpleMapper(" COMPAREABLE_KEY_BRACES", type.isObject() ? " <"+type.getKeyType()+" extends Comparable<T>>" : "");
addSimpleMapper("KV_BRACES", type.isObject() || valueType.isObject() ? "<>" : "");
addSimpleMapper("BRACES", type.isObject() ? "<>" : "");
if(type.needsCustomJDKType())
{
addSimpleMapper("JAVA_TYPE", type.getCustomJDKType().getKeyType());
addSimpleMapper("SANITY_CAST", "castTo"+type.getFileType());
}
addSimpleMapper("JAVA_CLASS", type.getCustomJDKType().getClassType());
if(valueType.needsCustomJDKType())
{
addSimpleMapper("SANITY_CAST_VALUE", "castTo"+valueType.getFileType());
}
addComment("@ArrayType", "@param <%s> the type of array that the operation should be applied");
addComment("@Type", "@param <%s> the type of elements maintained by this Collection");
addValueComment("@ValueArrayType", "@param <%s> the type of array that the operation should be applied");
addValueComment("@ValueType", "@param <%s> the type of elements maintained by this Collection");
addAnnontion("@PrimitiveOverride", "@Override");
addSimpleMapper("@PrimitiveDoc", "");
addAnnontion("@Primitive", "@Deprecated");
return this;
}
public GlobalVariables createHelperVariables()
{
createHelperVars(type, false, "KEY");
createHelperVars(valueType, true, "VALUE");
return this;
}
private void createHelperVars(ClassType type, boolean value, String fix)
{
addArgumentMapper("EQUALS_"+fix+"_TYPE", "Objects.equals(%2$s, "+(type.isObject() ? "%1$s" : fix+"_TO_OBJ(%1$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();
addArgumentMapper(fix+"_EQUALS_NOT", type.getEquals(true)).removeBraces();
addArgumentMapper(fix+"_EQUALS", type.getEquals(false)).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();
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() ? "%s.hashCode()" : type.getClassType(value)+".hashCode(%s)").removeBraces();
addInjectMapper(fix+"_TO_STRING", type.isObject() ? "%s.toString()" : 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_CLASS"+(value ? "_VALUE" : "")+"_ARRAY", type.isObject() ? "(CLASS_TYPE[])new Object[%s]" : "new CLASS_TYPE[%s]").removeBraces();
}
public GlobalVariables createPreFunctions()
{
addSimpleMapper("ENTRY_SET", type.getFileType().toLowerCase()+"2"+valueType.getFileType()+"EntrySet");
return this;
}
public GlobalVariables createClassTypes()
{
addSimpleMapper("JAVA_PREDICATE", type.isPrimitiveBlocking() ? "" : type.getCustomJDKType().getFileType()+"Predicate");
addSimpleMapper("JAVA_CONSUMER", type.isPrimitiveBlocking() ? "" : "java.util.function."+type.getCustomJDKType().getFileType()+"Consumer");
addSimpleMapper("JAVA_FUNCTION", type.getFunctionClass(valueType));
addSimpleMapper("JAVA_BINARY_OPERATOR", type == ClassType.BOOLEAN ? "" : (type.isObject() ? "java.util.function.BinaryOperator" : "java.util.function."+type.getCustomJDKType().getFileType()+"BinaryOperator"));
addSimpleMapper("JAVA_UNARY_OPERATOR", type.isObject() ? "BinaryOperator" : type == ClassType.BOOLEAN ? "" : type.getCustomJDKType().getFileType()+"UnaryOperator");
addSimpleMapper("JAVA_SPLIT_ITERATOR", type.isPrimitiveBlocking() ? "Spliterator" : "Of"+type.getCustomJDKType().getFileType());
addSimpleMapper("JAVA_STREAM", type.isPrimitiveBlocking() ? "" : type.getCustomJDKType().getFileType()+"Stream");
//Final Classes
addClassMapper("ARRAY_LIST", "ArrayList");
addClassMapper("ARRAY_FIFO_QUEUE", "ArrayFIFOQueue");
addClassMapper("ARRAY_PRIORITY_QUEUE", "ArrayPriorityQueue");
addClassMapper("HEAP_PRIORITY_QUEUE", "HeapPriorityQueue");
addClassMapper("LINKED_CUSTOM_HASH_SET", "LinkedOpenCustomHashSet");
addClassMapper("LINKED_HASH_SET", "LinkedOpenHashSet");
addClassMapper("CUSTOM_HASH_SET", "OpenCustomHashSet");
addClassMapper("HASH_SET", "OpenHashSet");
addBiClassMapper("LINKED_CUSTOM_HASH_MAP", "LinkedOpenCustomHashMap", "2");
addBiClassMapper("LINKED_HASH_MAP", "LinkedOpenHashMap", "2");
addBiClassMapper("CUSTOM_HASH_MAP", "OpenCustomHashMap", "2");
addBiClassMapper("AVL_TREE_MAP", "AVLTreeMap", "2");
addBiClassMapper("RB_TREE_MAP", "RBTreeMap", "2");
addFunctionValueMappers("ENUM_MAP", valueType.isObject() ? "Enum2ObjectMap" : "Enum2%sMap");
addBiClassMapper("HASH_MAP", "OpenHashMap", "2");
addBiClassMapper("ARRAY_MAP", "ArrayMap", "2");
addClassMapper("RB_TREE_SET", "RBTreeSet");
addClassMapper("AVL_TREE_SET", "AVLTreeSet");
addClassMapper("ARRAY_SET", "ArraySet");
//Abstract Classes
addAbstractMapper("ABSTRACT_COLLECTION", "Abstract%sCollection");
addAbstractMapper("ABSTRACT_SET", "Abstract%sSet");
addAbstractMapper("ABSTRACT_LIST", "Abstract%sList");
addAbstractBiMapper("ABSTRACT_MAP", "Abstract%sMap", "2");
addClassMapper("SUB_LIST", "SubList");
//Helper Classes
addClassMapper("LISTS", "Lists");
addClassMapper("SETS", "Sets");
addClassMapper("COLLECTIONS", "Collections");
addClassMapper("ARRAYS", "Arrays");
addClassMapper("SPLIT_ITERATORS", "Splititerators");
addClassMapper("ITERATORS", "Iterators");
addBiClassMapper("MAPS", "Maps", "2");
//Interfaces
addClassMapper("LIST_ITERATOR", "ListIterator");
addClassMapper("BI_ITERATOR", "BidirectionalIterator");
addBiClassMapper("BI_CONSUMER", "Consumer", "");
addClassMapper("SPLIT_ITERATOR", "Splititerator");
addClassMapper("ITERATOR", "Iterator");
addClassMapper("ITERABLE", "Iterable");
addClassMapper("COLLECTION", "Collection");
addBiClassMapper("FUNCTION", "Function", "2");
addClassMapper("LIST_ITER", "ListIter");
addClassMapper("LIST", "List");
addBiClassMapper("NAVIGABLE_MAP", "NavigableMap", "2");
addBiClassMapper("SORTED_MAP", "SortedMap", "2");
addBiClassMapper("MAP", "Map", "2");
addClassMapper("NAVIGABLE_SET", "NavigableSet");
addClassMapper("PRIORITY_QUEUE", "PriorityQueue");
addClassMapper("PRIORITY_DEQUEUE", "PriorityDequeue");
addClassMapper("SORTED_SET", "SortedSet");
addClassMapper("SET", "Set");
addClassMapper("STRATEGY", "Strategy");
addClassMapper("STACK", "Stack");
addBiClassMapper("UNARY_OPERATOR", "UnaryOperator", "");
if(type.isObject())
{
if(!valueType.isObject())
{
addSimpleMapper("VALUE_CONSUMER", valueType.getFileType()+"Consumer");
}
addSimpleMapper("CONSUMER", "Consumer");
addSimpleMapper("COMPARATOR", "Comparator");
addSimpleMapper("IARRAY", "IObjectArray");
}
else
{
addClassMapper("CONSUMER", "Consumer");
addClassMapper("COMPARATOR", "Comparator");
addFunctionMappers("IARRAY", "I%sArray");
}
return this;
}
public GlobalVariables createFunctions()
{
addSimpleMapper("APPLY_VALUE", valueType.isObject() ? "apply" : "applyAs"+valueType.getNonFileType());
addSimpleMapper("APPLY_CAST", "applyAs"+type.getCustomJDKType().getNonFileType());
addSimpleMapper("APPLY", type.isObject() ? "apply" : "applyAs"+type.getNonFileType());
addFunctionValueMappers("COMPUTE_IF_ABSENT", "compute%sIfAbsent");
addFunctionValueMappers("COMPUTE_IF_PRESENT", "compute%sIfPresent");
addFunctionValueMapper("COMPUTE", "compute");
addFunctionMapper("ENQUEUE_FIRST", "enqueueFirst");
addFunctionMapper("ENQUEUE", "enqueue");
addFunctionMapper("DEQUEUE_LAST", "dequeueLast");
addFunctionMapper("DEQUEUE", "dequeue");
addFunctionMappers("POLL_FIRST_ENTRY_KEY", "pollFirst%sKey");
addFunctionMappers("POLL_LAST_ENTRY_KEY", "pollLast%sKey");
addFunctionMapper("POLL_FIRST_KEY", "pollFirst");
addFunctionMapper("POLL_LAST_KEY", "pollLast");
addFunctionMappers("FIRST_ENTRY_KEY", "first%sKey");
addFunctionValueMappers("FIRST_ENTRY_VALUE", "first%sValue");
addFunctionMapper("FIRST_KEY", "first");
addFunctionMappers("LAST_ENTRY_KEY", "last%sKey");
addFunctionValueMappers("LAST_ENTRY_VALUE", "last%sValue");
addFunctionMappers("ENTRY_KEY", "get%sKey");
addFunctionValueMappers("ENTRY_VALUE", "get%sValue");
addFunctionMapper("GET_KEY", "get");
addFunctionValueMapper("GET_VALUE", valueType.isObject() ? "getObject" : "get");
addFunctionMapper("LAST_KEY", "last");
addFunctionValueMapper("MERGE", "merge");
addFunctionMapper("NEXT", "next");
addFunctionMapper("PREVIOUS", "previous");
addFunctionMapper("PEEK", "peek");
addFunctionMapper("POP", "pop");
addFunctionMapper("PUSH", "push");
addFunctionMapper("REMOVE_KEY", "rem");
addFunctionMapper("REMOVE_LAST", "removeLast");
addFunctionMapper("REMOVE", "remove");
addFunctionValueMappers("REPLACE_VALUES", valueType.isObject() ? "replaceObjects" : "replace%ss");
addFunctionMappers("REPLACE", type.isObject() ? "replaceObjects" : "replace%ss");
addFunctionMappers("SORT", "sort%ss");
addSimpleMapper("NEW_STREAM", type.isPrimitiveBlocking() ? "" : type.getCustomJDKType().getKeyType()+"Stream");
addSimpleMapper("TO_ARRAY", "to"+type.getNonFileType()+"Array");
addFunctionMapper("TOP", "top");
return this;
}
public GlobalVariables createFlags()
{
flags.add("TYPE_"+type.getCapType());
flags.add("VALUE_"+valueType.getCapType());
if(type == valueType) flags.add("SAME_TYPE");
if(type.hasFunction(valueType)) flags.add("JDK_FUNCTION");
if(!type.needsCustomJDKType()) flags.add("JDK_TYPE");
if(!type.isPrimitiveBlocking()) flags.add("PRIMITIVES");
if(!valueType.isPrimitiveBlocking()) flags.add("VALUE_PRIMITIVES");
if(valueType.needsCustomJDKType()) flags.add("JDK_VALUE");
return this;
}
public TemplateProcess create(String fileName, String splitter, boolean valueOnly)
{
TemplateProcess process = new TemplateProcess(String.format(fileName+".java", (splitter != null ? type.getFileType()+splitter+valueType.getFileType() : (valueOnly ? valueType : type).getFileType())));
process.setPathBuilder(new PathBuilder(type.getPathType()));
process.addFlags(flags);
process.addMappers(operators);
return process;
}
public ClassType getType()
{
return type;
}
private void addClassMapper(String pattern, String replacement)
{
operators.add(new SimpleMapper(type.name()+"[VALUE_"+pattern+"]", "VALUE_"+pattern, valueType.getFileType()+replacement));
operators.add(new SimpleMapper(type.name()+"["+pattern+"]", pattern, type.getFileType()+replacement));
}
private void addBiClassMapper(String pattern, String replacement, String splitter)
{
operators.add(new SimpleMapper(type.name()+"[KEY_"+pattern+"]", "KEY_"+pattern, type.getFileType()+splitter+type.getFileType()+replacement));
operators.add(new SimpleMapper(type.name()+"[VALUE_"+pattern+"]", "VALUE_"+pattern, valueType.getFileType()+splitter+valueType.getFileType()+replacement));
operators.add(new SimpleMapper(type.name()+"["+pattern+"]", pattern, type.getFileType()+splitter+valueType.getFileType()+replacement));
}
private void addAbstractMapper(String pattern, String replacement)
{
operators.add(new SimpleMapper(type.name()+"[VALUE_"+pattern+"]", "VALUE_"+pattern, String.format(replacement, valueType.getFileType())));
operators.add(new SimpleMapper(type.name()+"["+pattern+"]", pattern, String.format(replacement, type.getFileType())));
}
private void addAbstractBiMapper(String pattern, String replacement, String splitter)
{
operators.add(new SimpleMapper(type.name()+"["+pattern+"]", pattern, String.format(replacement, type.getFileType()+splitter+valueType.getFileType())));
}
private void addFunctionMapper(String pattern, String replacement)
{
operators.add(new SimpleMapper(type.name()+"[VALUE_"+pattern+"]", "VALUE_"+pattern, replacement+valueType.getNonFileType()));
operators.add(new SimpleMapper(type.name()+"["+pattern+"]", pattern, replacement+type.getNonFileType()));
}
private void addFunctionValueMapper(String pattern, String replacement)
{
operators.add(new SimpleMapper(type.name()+"["+pattern+"]", pattern, replacement+valueType.getNonFileType()));
}
private void addFunctionMappers(String pattern, String replacement)
{
operators.add(new SimpleMapper(type.name()+"[VALUE_"+pattern+"]", "VALUE_"+pattern, String.format(replacement, valueType.getNonFileType())));
operators.add(new SimpleMapper(type.name()+"["+pattern+"]", pattern, String.format(replacement, type.getNonFileType())));
}
private void addFunctionValueMappers(String pattern, String replacement)
{
operators.add(new SimpleMapper(type.name()+"["+pattern+"]", pattern, String.format(replacement, valueType.getNonFileType())));
}
private void addSimpleMapper(String pattern, String replacement)
{
operators.add(new SimpleMapper(type.name()+"["+pattern+"]", pattern, replacement));
}
private void addAnnontion(String pattern, String value)
{
if(type == ClassType.OBJECT) operators.add(new LineMapper(type.name()+"["+pattern+"]", pattern));
else operators.add(new SimpleMapper(type.name()+"["+pattern+"]", pattern, value));
}
private void addComment(String pattern, String value)
{
if(type == ClassType.OBJECT) operators.add(new InjectMapper(type.name()+"["+pattern+"]", pattern, value).removeBraces());
else operators.add(new LineMapper(type.name()+"["+pattern+"]", pattern));
}
private void addValueComment(String pattern, String value)
{
if(valueType == ClassType.OBJECT) operators.add(new InjectMapper(valueType.name()+"["+pattern+"]", pattern, value).removeBraces());
else operators.add(new LineMapper(valueType.name()+"["+pattern+"]", pattern));
}
private InjectMapper addInjectMapper(String pattern, String replacement)
{
InjectMapper mapper = new InjectMapper(type.name()+"["+pattern+"]", pattern, replacement);
operators.add(mapper);
return mapper;
}
private ArgumentMapper addArgumentMapper(String pattern, String replacement)
{
return addArgumentMapper(pattern, replacement, ", ");
}
private ArgumentMapper addArgumentMapper(String pattern, String replacement, String splitter)
{
ArgumentMapper mapper = new ArgumentMapper(type.name()+"["+pattern+"]", pattern, replacement, splitter);
operators.add(mapper);
return mapper;
}
class PathBuilder implements UnaryOperator<Path>
{
String before;
public PathBuilder(String before)
{
this.before = before;
}
@Override
public Path apply(Path t)
{
return t.subpath(0, 6).resolve(before).resolve(t.subpath(6, t.getNameCount()));
}
}
}
@@ -0,0 +1,155 @@
package speiger.src.builder;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import speiger.src.builder.mappers.IMapper;
import speiger.src.builder.processor.TemplateProcess;
@SuppressWarnings("javadoc")
public class ModulePackage
{
private static final BiConsumer<String, RequiredType> VOID = (K, V) -> {};
public static final ClassType[] TYPE = ClassType.values();
final ClassType keyType;
final ClassType valueType;
Set<String> blocked = new HashSet<>();
Map<String, String> nameRemapper = new HashMap<>();
Map<String, String> splitters = new HashMap<>();
List<Predicate<String>> blockedFilters = new ArrayList<>();
List<IMapper> mappers = new ArrayList<>();
Set<String> flags = new LinkedHashSet<>();
Set<String> globalFlags;
Map<String, Integer> flaggedValues = new HashMap<>();
BiConsumer<String, RequiredType> requirements = VOID;
public ModulePackage(Set<String> globalFlags, ClassType keyType, ClassType valueType) {
this.globalFlags = globalFlags;
this.keyType = keyType;
this.valueType = valueType;
}
public void finish() {
requirements = VOID;
mappers.sort(Comparator.comparing(IMapper::getSearchValue, Comparator.comparingInt(String::length).reversed()));
mappers.sort(Comparator.comparing(IMapper::getSearchValue, this::sort));
}
public void setRequirements(BiConsumer<String, RequiredType> requirements) {
this.requirements = requirements;
}
public boolean isSame() {
return keyType == valueType;
}
public boolean isEnumValid() {
return keyType == ClassType.OBJECT;
}
public ClassType getKeyType() {
return keyType;
}
public ClassType getValueType() {
return valueType;
}
public void addFlag(String flag) {
flags.add(flag);
}
public void addGlobalFlag(String flag) {
globalFlags.add(flag);
}
public void addValue(String key, int value) {
flaggedValues.put(key, value);
}
public void addRequirement(String fileName, RequiredType type) {
requirements.accept(fileName, type);
}
public void addMapper(IMapper mapper) {
mappers.add(mapper);
}
public void addBlockedFilter(Predicate<String> filter) {
blockedFilters.add(filter);
}
public void addBlockedFiles(String... names) {
blocked.addAll(Arrays.asList(names));
}
public void addSplitter(String fileName, String splitter) {
splitters.put(fileName, splitter);
}
public void addRemapper(String fileName, String actualName) {
nameRemapper.put(fileName, actualName);
}
public void process(String fileName, Consumer<TemplateProcess> result) {
if(isBlocked(fileName)) return;
String splitter = String.format(splitters.getOrDefault(fileName, keyType.getFileType()), keyType.getFileType(), valueType.getFileType());
String newName = String.format(nameRemapper.getOrDefault(fileName, "%s"+fileName), splitter);
TemplateProcess process = new TemplateProcess(newName+".java");
process.setPathBuilder(new PathBuilder(keyType.getPathType()));
process.addFlags(flags);
process.addFlags(globalFlags);
process.addMappers(mappers);
process.addValues(flaggedValues);
result.accept(process);
}
private boolean isBlocked(String fileName) {
if(blocked.contains(fileName)) return true;
for(int i = 0,m=blockedFilters.size();i<m;i++) {
if(blockedFilters.get(i).test(fileName)) return true;
}
return false;
}
public static List<ModulePackage> createPackages(Set<String> globalFlags) {
List<ModulePackage> list = new ArrayList<>();
for(ClassType key : TYPE) {
for(ClassType value : TYPE) {
list.add(new ModulePackage(globalFlags, key, value));
}
}
return list;
}
private int sort(String key, String value) {
if(value.contains(key)) return 1;
else if(key.contains(value)) return -1;
return 0;
}
class PathBuilder implements UnaryOperator<Path> {
String before;
public PathBuilder(String before) {
this.before = before;
}
@Override
public Path apply(Path t) {
return t.subpath(0, 6).resolve(before).resolve(t.subpath(6, t.getNameCount()));
}
}
}
@@ -1,166 +1,230 @@
package speiger.src.builder; package speiger.src.builder;
import java.io.IOException; import java.io.BufferedWriter;
import java.nio.file.Path; import java.io.IOException;
import java.nio.file.Paths; import java.nio.file.Files;
import java.util.ArrayList; import java.nio.file.Path;
import java.util.EnumSet; import java.nio.file.Paths;
import java.util.HashMap; import java.util.ArrayList;
import java.util.HashSet; import java.util.Arrays;
import java.util.List; import java.util.Collections;
import java.util.Map; import java.util.HashMap;
import java.util.Set; import java.util.HashSet;
import java.util.function.Consumer; import java.util.List;
import java.util.Map;
import speiger.src.builder.processor.TemplateProcess; import java.util.Set;
import speiger.src.builder.processor.TemplateProcessor; import java.util.StringJoiner;
import java.util.function.Consumer;
@SuppressWarnings("javadoc") import java.util.stream.Stream;
public class PrimitiveCollectionsBuilder extends TemplateProcessor
{ import speiger.src.builder.modules.AsyncModule;
Map<String, EnumSet<ClassType>> blocked = new HashMap<>(); import speiger.src.builder.modules.BaseModule;
Map<String, String> nameRemapper = new HashMap<>(); import speiger.src.builder.modules.CollectionModule;
Map<String, String> biRequired = new HashMap<>(); import speiger.src.builder.modules.FunctionModule;
Set<String> enumRequired = new HashSet<>(); import speiger.src.builder.modules.JavaModule;
public static final ClassType[] TYPE = ClassType.values(); import speiger.src.builder.modules.ListModule;
List<GlobalVariables> variables = new ArrayList<>(); import speiger.src.builder.modules.MapModule;
List<GlobalVariables> biVariables = new ArrayList<>(); import speiger.src.builder.modules.PairModule;
List<GlobalVariables> enumVariables = new ArrayList<>(); import speiger.src.builder.modules.PrioQueueModule;
import speiger.src.builder.modules.SetModule;
public PrimitiveCollectionsBuilder() import speiger.src.builder.processor.TemplateProcess;
{ import speiger.src.builder.processor.TemplateProcessor;
super(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/"));
} @SuppressWarnings("javadoc")
public class PrimitiveCollectionsBuilder extends TemplateProcessor
public PrimitiveCollectionsBuilder(Path sourceFolder, Path outputFolder, Path dataFolder) {
{ private static final int SPECIAL = 0x1; //Detects if the Builder is generating tests
super(sourceFolder, outputFolder, dataFolder); private static final int LOAD = 0x2; //If Configs should be loaded
} private static final int ANTI_SAVE = SPECIAL | LOAD; //If save should be disabled since load/save shouldn't happen at the same time.
private static final int SAVE = 0x4; //if the configuration should be created
@Override Set<String> globalFlags = new HashSet<>();
protected boolean isFileValid(Path fileName) List<ModulePackage> simplePackages = new ArrayList<>();
{ List<ModulePackage> biPackages = new ArrayList<>();
return true; List<ModulePackage> enumPackages = new ArrayList<>();
} Map<String, RequiredType> requirements = new HashMap<>();
SettingsManager manager = new SettingsManager();
@Override int flags;
protected boolean relativePackages()
{ public PrimitiveCollectionsBuilder() {
return true; this(false);
} }
@Override public PrimitiveCollectionsBuilder(boolean silencedSuccess) {
protected boolean debugUnusedMappers() 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/"));
{ }
return false;
} public PrimitiveCollectionsBuilder(Path sourceFolder, Path outputFolder, Path dataFolder) {
this(false, sourceFolder, outputFolder, dataFolder);
@Override }
protected void init()
{ public PrimitiveCollectionsBuilder(boolean silencedSuccess, Path sourceFolder, Path outputFolder, Path dataFolder) {
variables.clear(); super(silencedSuccess, sourceFolder, outputFolder, dataFolder);
for(ClassType clzType : TYPE) }
{
for(ClassType subType : TYPE) private PrimitiveCollectionsBuilder setFlags(int flags) {
{ this.flags = flags;
create(clzType, subType); if((flags & ANTI_SAVE) != 0) {
} this.flags &= ~SAVE;
} }
enumRequired.add("EnumMap"); return this;
biRequired.put("BiConsumer", ""); }
biRequired.put("UnaryOperator", "");
addBiClass("Function", "Maps", "Map", "SortedMap", "NavigableMap", "AbstractMap", "OpenHashMap", "LinkedOpenHashMap", "OpenCustomHashMap", "LinkedOpenCustomHashMap", "ArrayMap", "RBTreeMap", "AVLTreeMap"); private static PrimitiveCollectionsBuilder createTests(boolean silent, int flags) {
nameRemapper.put("BiConsumer", "%sConsumer"); return new PrimitiveCollectionsBuilder(silent,
nameRemapper.put("IArray", "I%sArray"); Paths.get("src/builder/resources/speiger/assets/tests/templates/"),
nameRemapper.put("AbstractMap", "Abstract%sMap"); Paths.get("src/test/java/speiger/src/tests/"),
nameRemapper.put("AbstractCollection", "Abstract%sCollection"); Paths.get("src/builder/resources/speiger/assets/tests/")).setFlags(flags | SPECIAL);
nameRemapper.put("AbstractSet", "Abstract%sSet"); }
nameRemapper.put("AbstractList", "Abstract%sList");
nameRemapper.put("EnumMap", "Enum2%sMap"); private static PrimitiveCollectionsBuilder createTesters(boolean silent, int flags) {
addBlockage(ClassType.OBJECT, "Consumer", "Comparator", "Stack"); return new PrimitiveCollectionsBuilder(silent,
addBlockage(ClassType.BOOLEAN, "ArraySet", "AVLTreeSet", "RBTreeSet", "SortedSet", "NavigableSet", "OpenHashSet", "OpenCustomHashSet", "LinkedOpenHashSet", "LinkedOpenCustomHashSet"); Paths.get("src/builder/resources/speiger/assets/testers/templates/"),
addBlockage(ClassType.BOOLEAN, "SortedMap", "NavigableMap", "OpenHashMap", "LinkedOpenHashMap", "OpenCustomHashMap", "LinkedOpenCustomHashMap", "ArrayMap", "RBTreeMap", "AVLTreeMap"); Paths.get("src/test/java/speiger/src/testers/"),
} Paths.get("src/builder/resources/speiger/assets/testers/")).setFlags(flags | SPECIAL);
}
protected void create(ClassType mainType, ClassType subType)
{ @Override
GlobalVariables type = new GlobalVariables(mainType, subType); protected boolean isFileValid(Path fileName) { return true; }
type.createFlags(); @Override
type.createHelperVariables(); protected boolean relativePackages() { return true; }
type.createVariables(); @Override
type.createPreFunctions(); protected boolean debugUnusedMappers() { return false; }
type.createClassTypes();
type.createFunctions(); @Override
if(mainType == subType) variables.add(type); protected void afterFinish() {
biVariables.add(type); if((flags & SPECIAL) == 0 && getVersion() > 8) {
if(mainType.isObject()) enumVariables.add(type); Path basePath = Paths.get("src/main/java");
} try(BufferedWriter writer = Files.newBufferedWriter(basePath.resolve("module-info.java"))) {
writer.write(getModuleInfo(basePath));
protected void addBiClass(String...classNames) }
{ catch(Exception e) { e.printStackTrace(); }
for(String s : classNames) }
{ }
biRequired.put(s, "2");
} public List<BaseModule> createModules() {
} List<BaseModule> modules = new ArrayList<>();
modules.add(JavaModule.INSTANCE);
protected void addBlockage(ClassType type, String...args) modules.add(FunctionModule.INSTANCE);
{ modules.add(CollectionModule.INSTANCE);
for(String s : args) modules.add(PrioQueueModule.INSTANCE);
{ modules.add(ListModule.INSTANCE);
EnumSet<ClassType> set = blocked.get(s); modules.add(SetModule.INSTANCE);
if(set == null) modules.add(MapModule.INSTANCE);
{ modules.add(PairModule.INSTANCE);
set = EnumSet.noneOf(ClassType.class); modules.add(AsyncModule.INSTANCE);
blocked.put(s, set); return modules;
} }
set.add(type);
}
} @Override
protected void init() {
@Override prepPackages();
public void createProcesses(String name, Consumer<TemplateProcess> acceptor) //Init Modules here
{ addModules(createModules());
String splitter = biRequired.get(name); finishPackages();
boolean valueRequired = enumRequired.contains(name); }
List<GlobalVariables> vars = getVariablesByClass(name, splitter != null);
EnumSet<ClassType> types = blocked.get(name); public void addModules(List<BaseModule> modules) {
for(int i = 0,m=vars.size();i<m;i++) for(int i = 0,m=modules.size();i<m;i++) {
{ modules.get(i).setManager(manager);
GlobalVariables type = vars.get(i); }
if(types == null || !types.contains(type.getType())) manager.resolve();
{ for(int i = 0,m=modules.size();i<m;i++) {
acceptor.accept(type.create(nameRemapper.getOrDefault(name, "%s"+name), splitter, valueRequired)); biPackages.forEach(modules.get(i)::init);
} }
} modules.forEach(BaseModule::cleanup);
} }
protected List<GlobalVariables> getVariablesByClass(String name, boolean bi) { private void finishPackages() {
if(enumRequired.contains(name)) return enumVariables; biPackages.forEach(ModulePackage::finish);
if(bi) return biVariables; if((flags & SAVE) != 0) manager.save();
return variables; }
}
private void prepPackages() {
public static void main(String...args) if((flags & LOAD) != 0) manager.load();
{ for(ModulePackage entry : ModulePackage.createPackages(globalFlags)) {
try entry.setRequirements(requirements::put);
{ biPackages.add(entry);
if(args.length == 0) { if(entry.isSame()) simplePackages.add(entry);
new PrimitiveCollectionsBuilder().process(false); if(entry.isEnumValid()) enumPackages.add(entry);
} else if(args.length == 3) { }
new PrimitiveCollectionsBuilder(Paths.get(args[0]), Paths.get(args[1]), Paths.get(args[2])).process(false); }
} else {
System.out.println("Invalid argument count passed in"); @Override
System.exit(1); public void createProcesses(String fileName, Consumer<TemplateProcess> process) {
} List<ModulePackage> packages = getPackagesByRequirement(requirements.get(fileName));
} for(int i = 0,m=packages.size();i<m;i++) {
catch(InterruptedException e) packages.get(i).process(fileName, process);
{ }
e.printStackTrace(); }
}
catch(IOException e) protected List<ModulePackage> getPackagesByRequirement(RequiredType type) {
{ if(type == null) return simplePackages;
e.printStackTrace(); if(type == RequiredType.BI_CLASS) return biPackages;
} if(type == RequiredType.ENUM) return enumPackages;
} return Collections.emptyList();
} }
private String getModuleInfo(Path basePath) {
StringJoiner joiner = new StringJoiner("\n", "", "\n");
try(Stream<Path> stream = Files.walk(getOutputFolder())) {
stream.filter(Files::isDirectory)
.filter(this::containsFiles)
.map(basePath::relativize)
.map(Path::toString)
.map(this::sanitize)
.forEach(T -> joiner.add("\texports "+T+";"));
}
catch(Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
StringBuilder builder = new StringBuilder();
builder.append("/** @author Speiger */\n");
builder.append("module ").append(sanitize(basePath.relativize(getOutputFolder()).toString())).append(" {\n");
builder.append(joiner.toString()).append("}");
return builder.toString();
}
private String sanitize(String input) {
return input.replace("\\", ".").replace("/", ".");
}
private boolean containsFiles(Path path) {
try(Stream<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();
}
}
}
@@ -0,0 +1,8 @@
package speiger.src.builder;
@SuppressWarnings("javadoc")
public enum RequiredType
{
BI_CLASS,
ENUM
}
@@ -0,0 +1,217 @@
package speiger.src.builder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
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.TreeMap;
import java.util.TreeSet;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.internal.Streams;
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;
@SuppressWarnings("javadoc")
public class SettingsManager
{
boolean loaded;
Map<String, LoadingState> parsedData = new TreeMap<>();
JsonObject data = new JsonObject();
Set<String> moduleNames = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
Set<IDependency> allDependencies = new LinkedHashSet<>();
public void resolve() {
if(!loaded) return;
Set<IDependency> roots = new LinkedHashSet<>();
Set<IDependency> leafs = new LinkedHashSet<>();
for(IDependency entry : allDependencies) {
if(entry.isRoot()) {
roots.add(entry);
}
if(entry.isLeaf()) {
leafs.add(entry);
}
}
/**
* 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
*/
for(int i = 0;i<2;i++) {
for(ClassType keyType : ModulePackage.TYPE) {
for(ClassType valueType : ModulePackage.TYPE) {
for(IDependency entry : roots) {
entry.resolveRequirements(keyType, valueType);
}
}
}
}
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));
}
}
public void addModule(BaseModule module) {
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();
moduleNames.add(moduleName);
data.addProperty(moduleName, true);
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, true);
}
addModule(keyType, valueType, true, moduleName, obj);
}
}
return;
}
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, true);
}
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() {
try(BufferedReader reader = Files.newBufferedReader(Paths.get("ModulSettings.json"))) {
data = JsonParser.parseReader(reader).getAsJsonObject();
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(); }
}
public void save() {
data.asMap().keySet().removeAll(moduleNames);
JsonObject result = new JsonObject();
for(String s : moduleNames) {
result.addProperty(s, true);
}
result.asMap().putAll(data.asMap());
try(JsonWriter writer = new JsonWriter(Files.newBufferedWriter(Paths.get("ModulSettings.json")))) {
writer.setIndent("\t");
Streams.write(result, writer);
}
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) {
JsonObject result = getObject(data, keyType.getClassPath(), true);
if(bi) {
result = getObject(result, valueType.getClassPath(), true);
}
result.add(moduleName, obj);
}
private JsonObject getObject(JsonObject data, String name, boolean create) {
JsonObject obj = data.getAsJsonObject(name);
if(obj == null) {
obj = new JsonObject();
data.add(name, obj);
if(create) obj.addProperty("Enabled", true);
}
return obj;
}
}
@@ -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);
}
}
}
@@ -0,0 +1,53 @@
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")
public class AsyncModule extends BaseModule
{
public static final BaseModule INSTANCE = new AsyncModule();
public static final ModuleDependency MODULE = new ModuleDependency(INSTANCE, false).addKeyDependency(JavaModule.MODULE);
@Override
public String getModuleName() { return "Async"; }
@Override
protected void loadVariables() {}
@Override
protected void loadRemappers() {}
@Override
protected void loadTestClasses() {}
@Override
protected void loadFunctions() {}
@Override
public List<IDependency> getDependencies(ClassType keyType, ClassType valueType) { return Arrays.asList(MODULE); }
@Override
protected void loadBlockades() {
if(!MODULE.isEnabled()) {
addBlockedFiles("AsyncBuilder", "Task");
}
}
@Override
protected void loadFlags() {
if(MODULE.isEnabled()) {
addKeyFlag("ASYNC_MODULE");
}
}
@Override
protected void loadClasses()
{
//Implementation Classes
addClassMapper("ASYNC_BUILDER", "AsyncBuilder");
//Abstract Classes
addAbstractMapper("BASE_TASK", "Base%sTask");
//Interfaces
addClassMapper("TASK", "Task");
}
}
@@ -0,0 +1,198 @@
package speiger.src.builder.modules;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
import speiger.src.builder.ClassType;
import speiger.src.builder.ModulePackage;
import speiger.src.builder.RequiredType;
import speiger.src.builder.SettingsManager;
import speiger.src.builder.dependencies.IDependency;
import speiger.src.builder.mappers.ArgumentMapper;
import speiger.src.builder.mappers.InjectMapper;
import speiger.src.builder.mappers.LineMapper;
import speiger.src.builder.mappers.SimpleMapper;
@SuppressWarnings("javadoc")
public abstract class BaseModule
{
SettingsManager manager;
ModulePackage entry;
protected ClassType keyType;
protected ClassType valueType;
public final void setManager(SettingsManager manager) {
this.manager = manager;
manager.addModule(this);
}
public final void init(ModulePackage entry) {
this.entry = entry;
keyType = entry.getKeyType();
valueType = entry.getValueType();
for(IDependency dependency : getDependencies(keyType, valueType)) {
dependency.set(keyType, valueType);
}
loadVariables();
loadClasses();
loadTestClasses();
loadFunctions();
loadRemappers();
loadBlockades();
loadFlags();
}
public final void cleanup() {
entry = null;
keyType = null;
valueType = null;
manager = null;
}
protected abstract void loadVariables();
protected abstract void loadClasses();
protected abstract void loadTestClasses();
protected abstract void loadFunctions();
protected abstract void loadRemappers();
protected abstract void loadBlockades();
protected abstract void loadFlags();
public abstract String getModuleName();
public boolean isBiModule() { return false; }
public List<IDependency> getDependencies(ClassType keyType, ClassType valueType) { return Collections.emptyList(); }
public boolean isModuleValid(ClassType keyType, ClassType valueType) { return true; }
public ClassType keyType() { return keyType; }
public ClassType valueType() { return valueType; }
protected void addFlag(String name) {
entry.addFlag(name);
}
protected void addValue(String name, int value) {
entry.addValue(name, value);
}
protected void addKeyFlag(String name) {
entry.addFlag(name);
entry.addGlobalFlag(keyType.getCapType()+"_"+name);
}
protected void addBiRequirement(String fileName) {
entry.addRequirement(fileName, RequiredType.BI_CLASS);
entry.addSplitter(fileName, "%1$s2%2$s");
}
protected void addEnumRequirement(String fileName) {
entry.addRequirement(fileName, RequiredType.ENUM);
entry.addSplitter(fileName, "%2$s");
}
protected void addBiRequirement(String fileName, String splitter) {
entry.addRequirement(fileName, RequiredType.BI_CLASS);
entry.addSplitter(fileName, "%1$s"+splitter+"%2$s");
}
protected void addRequirement(String fileName, String splitter, RequiredType type) {
entry.addRequirement(fileName, type);
entry.addSplitter(fileName, splitter);
}
protected void addRemapper(String fileName, String actualName) {
entry.addRemapper(fileName, actualName);
}
protected void addBlockedFiles(String... name) {
entry.addBlockedFiles(name);
}
protected void addBlockedFilter(Predicate<String> filter) {
entry.addBlockedFilter(filter);
}
protected void addClassMapper(String pattern, String replacement) {
entry.addMapper(new SimpleMapper("VALUE_"+pattern, "VALUE_"+pattern, valueType.getFileType()+replacement));
entry.addMapper(new SimpleMapper(pattern, pattern, keyType.getFileType()+replacement));
}
protected void addBiClassMapper(String pattern, String replacement, String splitter) {
entry.addMapper(new SimpleMapper("KEY_"+pattern, "KEY_"+pattern, keyType.getFileType()+splitter+keyType.getFileType()+replacement));
entry.addMapper(new SimpleMapper("VALUE_"+pattern, "VALUE_"+pattern, valueType.getFileType()+splitter+valueType.getFileType()+replacement));
entry.addMapper(new SimpleMapper(pattern, pattern, keyType.getFileType()+splitter+valueType.getFileType()+replacement));
}
protected void addAbstractMapper(String pattern, String replacement) {
entry.addMapper(new SimpleMapper("VALUE_"+pattern, "VALUE_"+pattern, String.format(replacement, valueType.getFileType())));
entry.addMapper(new SimpleMapper(pattern, pattern, String.format(replacement, keyType.getFileType())));
}
protected void addAbstractBiMapper(String pattern, String replacement, String splitter) {
entry.addMapper(new SimpleMapper(pattern, pattern, String.format(replacement, keyType.getFileType()+splitter+valueType.getFileType())));
}
protected void addFunctionMapper(String pattern, String replacement) {
entry.addMapper(new SimpleMapper("VALUE_"+pattern, "VALUE_"+pattern, replacement+valueType.getNonFileType()));
entry.addMapper(new SimpleMapper(pattern, pattern, replacement+keyType.getNonFileType()));
}
protected void addFunctionValueMapper(String pattern, String replacement) {
entry.addMapper(new SimpleMapper(pattern, pattern, replacement+valueType.getNonFileType()));
}
protected void addFunctionMappers(String pattern, String replacement) {
entry.addMapper(new SimpleMapper("VALUE_"+pattern, "VALUE_"+pattern, String.format(replacement, valueType.getNonFileType())));
entry.addMapper(new SimpleMapper(pattern, pattern, String.format(replacement, keyType.getNonFileType())));
}
protected void addFunctionValueMappers(String pattern, String replacement) {
entry.addMapper(new SimpleMapper(pattern, pattern, String.format(replacement, valueType.getNonFileType())));
}
protected void addSimpleMapper(String pattern, String replacement) {
entry.addMapper(new SimpleMapper(pattern, pattern, replacement));
}
protected void addAnnontion(String pattern, String value) {
if(keyType == ClassType.OBJECT) entry.addMapper(new LineMapper(pattern, pattern));
else entry.addMapper(new SimpleMapper(pattern, pattern, value));
}
protected void addValueAnnontion(String pattern, String value) {
if(valueType == ClassType.OBJECT) entry.addMapper(new LineMapper(pattern, pattern));
else entry.addMapper(new SimpleMapper(pattern, pattern, value));
}
protected void addComment(String pattern, String value) {
if(keyType == ClassType.OBJECT) entry.addMapper(new InjectMapper(pattern, pattern, value).removeBraces());
else entry.addMapper(new LineMapper(pattern, pattern));
}
protected void addValueComment(String pattern, String value) {
if(valueType == ClassType.OBJECT) entry.addMapper(new InjectMapper(pattern, pattern, value).removeBraces());
else entry.addMapper(new LineMapper(pattern, pattern));
}
protected InjectMapper addInjectMapper(String pattern, String replacement) {
InjectMapper mapper = new InjectMapper(pattern, pattern, replacement);
entry.addMapper(mapper);
return mapper;
}
protected ArgumentMapper addArgumentMapper(String pattern, String replacement) {
return addArgumentMapper(pattern, replacement, ", ");
}
protected ArgumentMapper addArgumentMapper(String pattern, String replacement, String splitter) {
ArgumentMapper mapper = new ArgumentMapper(pattern, pattern, replacement, splitter);
entry.addMapper(mapper);
return mapper;
}
public static <T> T make(T input, Consumer<T> processor) {
processor.accept(input);
return input;
}
}
@@ -0,0 +1,135 @@
package speiger.src.builder.modules;
import java.util.Arrays;
import java.util.List;
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")
public class CollectionModule extends BaseModule
{
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
public String getModuleName() { return "Collection"; }
@Override
protected void loadVariables() {}
@Override
public List<IDependency> getDependencies(ClassType keyType, ClassType valueType) { return Arrays.asList(MODULE, STREAMS, SPLIT_ITERATORS, IARRAY, STRATEGY); }
@Override
protected void loadFlags() {
if(MODULE.isEnabled()) addKeyFlag("COLLECTION_MODULE");
if(STREAMS.isEnabled()) addKeyFlag("STREAM_FEATURE");
if(SPLIT_ITERATORS.isEnabled()) addKeyFlag("SPLIT_ITERATOR_FEATURE");
if(IARRAY.isEnabled()) addKeyFlag("IARRAY_FEATURE");
}
@Override
protected void loadBlockades() {
if(!MODULE.isEnabled()) {
addBlockedFiles("Iterable", "Iterables", "Iterator", "Iterators", "BidirectionalIterator", "ListIterator");
addBlockedFiles("Arrays", "Collection", "AbstractCollection", "Collections", "Stack");
}
if(!SPLIT_ITERATORS.isEnabled()) addBlockedFiles("Splititerator", "Splititerators");
if(!IARRAY.isEnabled()) addBlockedFiles("IArray");
if(!STRATEGY.isEnabled()) addBlockedFiles("Strategy");
if(keyType.isObject())
{
addBlockedFiles("Stack");
addBlockedFiles("CollectionStreamTester");
}
if(keyType == ClassType.BOOLEAN)
{
addBlockedFiles("CollectionRemoveIfTester", "CollectionStreamTester");
addBlockedFilter(T -> T.endsWith("Tester") && T.startsWith("Iterable"));
}
}
@Override
protected void loadRemappers()
{
//Main Classes
addRemapper("IArray", "I%sArray");
addRemapper("AbstractCollection", "Abstract%sCollection");
//Test Classes
addRemapper("AbstractIteratorTester", "Abstract%sIteratorTester");
addRemapper("MinimalCollection", "Minimal%sCollection");
addRemapper("TestCollectionGenerator", "Test%sCollectionGenerator");
addRemapper("AbstractContainerTester", "Abstract%sContainerTester");
addRemapper("AbstractCollectionTester", "Abstract%sCollectionTester");
addRemapper("SimpleTestGenerator", "Simple%sTestGenerator");
}
@Override
protected void loadFunctions()
{
addFunctionMapper("NEXT", "next");
addSimpleMapper("NEW_STREAM", keyType.isPrimitiveBlocking() ? "" : keyType.getCustomJDKType().getKeyType()+"Stream");
addFunctionMapper("PREVIOUS", "previous");
addFunctionMapper("REMOVE_KEY", "rem");
addSimpleMapper("TO_ARRAY", "to"+keyType.getNonFileType()+"Array");
addSimpleMapper("VALUE_TO_ARRAY", "to"+valueType.getNonFileType()+"Array");
}
@Override
protected void loadClasses()
{
//Abstract Classes
addAbstractMapper("ABSTRACT_COLLECTION", "Abstract%sCollection");
//Helper Classes
addClassMapper("ARRAYS", "Arrays");
addClassMapper("COLLECTIONS", "Collections");
addClassMapper("ITERABLES", "Iterables");
addClassMapper("SPLIT_ITERATORS", "Splititerators");
addClassMapper("ITERATORS", "Iterators");
//Interfaces
addClassMapper("COLLECTION", "Collection");
addClassMapper("ITERABLE", "Iterable");
addClassMapper("SPLIT_ITERATOR", "Splititerator");
addClassMapper("LIST_ITERATOR", "ListIterator");
addClassMapper("BI_ITERATOR", "BidirectionalIterator");
addClassMapper("ITERATOR", "Iterator");
if(keyType.isObject()) addSimpleMapper("STACK", "Stack");
else addClassMapper("STACK", "Stack");
addClassMapper("STRATEGY", "Strategy");
}
@Override
protected void loadTestClasses()
{
//Implementation Classes
addAbstractMapper("MINIMAL_COLLECTION", "Minimal%sCollection");
addClassMapper("BIDIRECTIONAL_ITERATOR_TESTER", "BidirectionalteratorTester");
addClassMapper("LIST_ITERATOR_TESTER", "ListIteratorTester");
addClassMapper("ITERATOR_TESTER", "IteratorTester");
addClassMapper("COLLECTION_TEST_BUILDER", "CollectionTestSuiteBuilder");
addClassMapper("COLLECTION_CONSTRUCTOR_TESTS", "CollectionConstructorTests");
//Abstract Classes
addAbstractMapper("ABSTRACT_COLLECTION_TESTER", "Abstract%sCollectionTester");
addAbstractMapper("ABSTRACT_CONTAINER_TESTER", "Abstract%sContainerTester");
addAbstractMapper("ABSTRACT_ITERATOR_TESTER", "Abstract%sIteratorTester");
//Helper Classes
addAbstractMapper("TEST_COLLECTION_GENERATOR", "Test%sCollectionGenerator");
addAbstractMapper("SIMPLE_TEST_GENERATOR", "Simple%sTestGenerator");
}
}
@@ -0,0 +1,119 @@
package speiger.src.builder.modules;
import java.util.Arrays;
import java.util.List;
import speiger.src.builder.ClassType;
import speiger.src.builder.RequiredType;
import speiger.src.builder.dependencies.IDependency;
import speiger.src.builder.dependencies.ModuleDependency;
@SuppressWarnings("javadoc")
public class FunctionModule extends BaseModule
{
public static final BaseModule INSTANCE = new FunctionModule();
public static final ModuleDependency MODULE = new ModuleDependency(INSTANCE, false).addKeyDependency(JavaModule.MODULE);
@Override
public String getModuleName() { return "Function"; }
@Override
public boolean isBiModule() { return true; }
@Override
protected void loadVariables() {}
@Override
protected void loadFlags() {}
@Override
protected void loadTestClasses() {}
@Override
public List<IDependency> getDependencies(ClassType keyType, ClassType valueType) {
return Arrays.asList(MODULE);
}
@Override
protected void loadBlockades()
{
if(keyType.isObject()) addBlockedFiles("Consumer", "Comparator");
if(!MODULE.isEnabled()) addBlockedFiles("Consumer", "BiConsumer", "Comparator", "Supplier", "Function", "UnaryOperator");
}
@Override
protected void loadRemappers()
{
addBiRequirement("BiConsumer", "");
addBiRequirement("UnaryOperator", "");
if(valueType == ClassType.BOOLEAN) {
addRequirement("Function", "%1$s", RequiredType.BI_CLASS);
addRemapper("Function", (keyType.isObject() ? "" : "%s")+"Predicate");
}
else if(keyType.isObject() && !valueType.isObject()) {
addRequirement("Function", "%2$s", RequiredType.BI_CLASS);
addRemapper("Function", "To%sFunction");
}
else if(keyType == valueType) {
addRequirement("Function", "%1$s", RequiredType.BI_CLASS);
addRemapper("Function", (keyType.isObject() ? "" : "%s")+"UnaryOperator");
}
else if(valueType.isObject()) {
addRequirement("Function", "%1$s", RequiredType.BI_CLASS);
addRemapper("Function", "%sFunction");
}
else addBiRequirement("Function");
addRemapper("BiConsumer", "%sConsumer");
}
@Override
protected void loadFunctions()
{
addSimpleMapper("APPLY", keyType.getApply(valueType));
addSimpleMapper("SUPPLY_GET", keyType.isObject() ? "get" : "getAs"+keyType.getNonFileType());
addSimpleMapper("VALUE_SUPPLY_GET", valueType.isObject() ? "get" : "getAs"+valueType.getNonFileType());
}
@Override
protected void loadClasses()
{
//Interfaces
addBiClassMapper("BI_CONSUMER", "Consumer", "");
addClassMapper("BI_TO_OBJECT_CONSUMER", "ObjectConsumer");
addAbstractMapper("BI_FROM_OBJECT_CONSUMER", "Object%sConsumer");
addAbstractMapper("BI_FROM_INT_CONSUMER", "Int%sConsumer");
if(keyType.isObject()) {
addSimpleMapper("TO_OBJECT_FUNCTION", keyType.getNonFileType()+"UnaryOperator");
addSimpleMapper("VALUE_TO_OBJECT_FUNCTION", valueType.isObject() ? "UnaryOperator" : valueType.getFileType()+"Function");
}
else {
addSimpleMapper("TO_OBJECT_FUNCTION", keyType.getNonFileType()+"Function");
addSimpleMapper("VALUE_TO_OBJECT_FUNCTION", valueType.isObject() ? "UnaryOperator" : valueType.getFileType()+"Function");
}
if(valueType == ClassType.BOOLEAN) addFunctionMappers("FUNCTION", "%sPredicate");
else if(keyType.isObject() && !valueType.isObject()) addFunctionValueMappers("FUNCTION", "To%sFunction");
else if(keyType == valueType) addFunctionMappers("FUNCTION", "%sUnaryOperator");
else if(valueType.isObject()) addFunctionMappers("FUNCTION", "%sFunction");
else addBiClassMapper("FUNCTION", "Function", "2");
addFunctionMappers("PREDICATE", "%sPredicate");
addClassMapper("SUPPLIER", "Supplier");
addAbstractMapper("SINGLE_UNARY_OPERATOR", "%1$s%1$sUnaryOperator");
addBiClassMapper("UNARY_OPERATOR", "UnaryOperator", "");
if(keyType.isObject())
{
if(!valueType.isObject()) addSimpleMapper("VALUE_CONSUMER", valueType.getFileType()+"Consumer");
else addSimpleMapper("VALUE_CONSUMER", "Consumer");
addSimpleMapper("CONSUMER", "Consumer");
addSimpleMapper("IARRAY", "IObjectArray");
}
else
{
if(valueType.isObject())
{
addSimpleMapper("VALUE_CONSUMER", "Consumer");
addSimpleMapper("CONSUMER", keyType.getFileType()+"Consumer");
}
else addClassMapper("CONSUMER", "Consumer");
addFunctionMappers("IARRAY", "I%sArray");
}
addSimpleMapper("VALUE_COMPARATOR", valueType.isObject() ? "Comparator" : String.format("%sComparator", valueType.getNonFileType()));
addSimpleMapper("COMPARATOR", keyType.isObject() ? "Comparator" : String.format("%sComparator", keyType.getNonFileType()));
}
}
@@ -0,0 +1,232 @@
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")
public class JavaModule extends BaseModule
{
public static final BaseModule INSTANCE = new JavaModule();
public static final ModuleDependency MODULE = new ModuleDependency(INSTANCE, false);
@Override
public String getModuleName() { return "Base"; }
@Override
protected void loadVariables()
{
createHelperVars(keyType, false, "KEY");
createHelperVars(valueType, true, "VALUE");
loadBaseVariables();
}
@Override
public List<IDependency> getDependencies(ClassType keyType, ClassType valueType) {
return Arrays.asList(MODULE);
}
@Override
protected void loadFlags()
{
addFlag("TYPE_"+keyType.getCapType());
addFlag("VALUE_"+valueType.getCapType());
addValue("JAVA_VERSION", getVersion());
if(keyType == valueType) addFlag("SAME_TYPE");
if(keyType.hasFunction(valueType)) addFlag("JDK_FUNCTION");
if(!keyType.needsCustomJDKType()) addFlag("JDK_TYPE");
if(!keyType.isPrimitiveBlocking()) addFlag("PRIMITIVES");
if(!valueType.isPrimitiveBlocking()) addFlag("VALUE_PRIMITIVES");
if(!valueType.needsCustomJDKType()) addFlag("JDK_VALUE");
}
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);
}
@Override
protected void loadRemappers() {}
@Override
protected void loadBlockades() {}
@Override
protected void loadFunctions()
{
addSimpleMapper("APPLY_KEY_VALUE", keyType.isObject() ? "apply" : "applyAs"+keyType.getNonFileType());
addSimpleMapper("APPLY_VALUE", valueType.isObject() ? "apply" : "applyAs"+valueType.getNonFileType());
addSimpleMapper("APPLY_CAST", "applyAs"+keyType.getCustomJDKType().getNonFileType());
//Shared by Maps and Pairs so moved to java.
addFunctionMappers("ENTRY_KEY", "get%sKey");
addFunctionValueMappers("ENTRY_VALUE", "get%sValue");
addFunctionMappers("KEY_ENTRY", "set%sKey");
addFunctionValueMappers("VALUE_ENTRY", "set%sValue");
}
@Override
protected void loadClasses()
{
if(getVersion() >= 17) addSimpleMapper("RANDOM", "RandomGenerator");
else addSimpleMapper("RANDOM", "Random");
addSimpleMapper("JAVA_PREDICATE", keyType.isPrimitiveBlocking() ? "" : keyType.getCustomJDKType().getFileType()+"Predicate");
addSimpleMapper("JAVA_CONSUMER", keyType.isPrimitiveBlocking() ? "" : "java.util.function."+keyType.getCustomJDKType().getFileType()+"Consumer");
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"));
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("JAVA_STREAM", keyType.isPrimitiveBlocking() ? "" : keyType.getCustomJDKType().getFileType()+"Stream");
addSimpleMapper("JAVA_BUFFER", keyType.getFileType()+"Buffer");
}
@Override
protected void loadTestClasses()
{
addClassMapper("HELPERS", "Helpers");
addClassMapper("SAMPLE_ELEMENTS", "Samples");
}
private void loadBaseVariables()
{
addSimpleMapper("VALUE_PACKAGE", valueType.getPathType());
addSimpleMapper("PACKAGE", keyType.getPathType());
addSimpleMapper("CLASS_TYPE", keyType.getClassType());
addSimpleMapper("CLASS_VALUE_TYPE", valueType.getClassValueType());
addSimpleMapper("KEY_TYPE", keyType.getKeyType());
addSimpleMapper("KEY_OBJECT_TYPE", keyType.isObject() ? "Object" : keyType.getKeyType());
addSimpleMapper("KEY_STRING_TYPE", keyType.isObject() ? "String" : keyType.getKeyType());
addSimpleMapper("KEY_SPECIAL_TYPE", keyType.isObject() ? "E" : keyType.getKeyType());
addSimpleMapper("CLASS_OBJECT_TYPE", keyType.getClassType());
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());
addSimpleMapper("VALUE_TYPE", valueType.getValueType());
addSimpleMapper("VALUE_OBJECT_TYPE", valueType.isObject() ? "Object" : valueType.getValueType());
addSimpleMapper("VALUE_STRING_TYPE", valueType.isObject() ? "String" : valueType.getValueType());
addSimpleMapper("VALUE_SPECIAL_TYPE", valueType.isObject() ? "E" : valueType.getKeyType());
addSimpleMapper("KEY_JAVA_TYPE", keyType.getCustomJDKType().getKeyType());
addSimpleMapper("VALUE_JAVA_TYPE", keyType.getCustomJDKType().getKeyType());
addSimpleMapper("EMPTY_KEY_VALUE", keyType.getEmptyValue());
addSimpleMapper("EMPTY_VALUE", valueType.getEmptyValue());
addSimpleMapper("INVALID_KEY_VALUE", keyType.getInvalidValue());
addSimpleMapper("INVALID_VALUE", valueType.getInvalidValue());
addSimpleMapper(" KEY_STRING_GENERIC_TYPE", keyType.isObject() ? "<String>" : "");
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_SAME_GENERIC_TYPE", keyType.isObject() ? "<T, T>" : "");
addSimpleMapper(" VALUE_SAME_GENERIC_TYPE", keyType.isObject() ? "<V, V>" : "");
addSimpleMapper(" KEY_GENERIC_TYPE", keyType.isObject() ? "<"+keyType.getKeyType()+">" : "");
addSimpleMapper(" KEY_KEY_GENERIC_TYPE", keyType.isObject() ? "<"+keyType.getKeyType()+", "+keyType.getKeyType()+">" : "");
addSimpleMapper(" KEY_CLASS_GENERIC_TYPE", keyType.isObject() ? "<"+keyType.getClassType()+">" : "");
addSimpleMapper(" VALUE_GENERIC_TYPE", valueType.isObject() ? "<"+valueType.getValueType()+">" : "");
addSimpleMapper(" VALUE_VALUE_GENERIC_TYPE", valueType.isObject() ? "<"+valueType.getValueType()+", "+valueType.getValueType()+">" : "");
addSimpleMapper(" VALUE_CLASS_GENERIC_TYPE", valueType.isObject() ? "<"+valueType.getClassValueType()+">" : "");
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()+">" : ""));
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(" NO_GENERIC_TYPE", keyType.isObject() ? "<?>" : "");
addSimpleMapper(" NO_KV_GENERIC_TYPE", keyType.isObject() ? (valueType.isObject() ? "<?, ?>" : "<?>") : valueType.isObject() ? "<?>" : "");
addSimpleMapper(" KEY_COMPAREABLE_TYPE", keyType.isObject() ? "<"+keyType.getKeyType()+" extends Comparable<T>>" : "");
addSimpleMapper(" KEY_SUPER_GENERIC_TYPE", keyType.isObject() ? "<? super "+keyType.getKeyType()+">" : "");
addSimpleMapper(" VALUE_SUPER_GENERIC_TYPE", valueType.isObject() ? "<? super "+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(" KEY_UNKNOWN_GENERIC_TYPE", keyType.isObject() ? "<? extends "+keyType.getKeyType()+">" : "");
addSimpleMapper(" VALUE_UNKNOWN_GENERIC_TYPE", valueType.isObject() ? "<? extends "+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_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()+">>" : ""));
addInjectMapper(" KEY_SPECIAL_GENERIC_TYPE", keyType.isObject() ? "<%s>" : "").removeBraces().setBraceType("<>");
addInjectMapper(" VALUE_SPECIAL_GENERIC_TYPE", valueType.isObject() ? "<%s>" : "").removeBraces().setBraceType("<>");
addInjectMapper(" KSK_GENERIC_TYPE", keyType.isObject() ? "<%s, "+keyType.getKeyType()+">" : "<%s>").removeBraces().setBraceType("<>");
addInjectMapper(" KKS_GENERIC_TYPE", keyType.isObject() ? "<"+keyType.getKeyType()+", %s>" : "<%s>").removeBraces().setBraceType("<>");
addArgumentMapper(" KSS_GENERIC_TYPE", keyType.isObject() ? "<%1$s, %2$s>" : "<%2$s>").removeBraces().setBraceType("<>");
addInjectMapper(" SK_GENERIC_TYPE", keyType.isObject() ? "<%s, "+keyType.getKeyType()+">" : "").removeBraces().setBraceType("<>");
addInjectMapper(" KS_GENERIC_TYPE", keyType.isObject() ? "<"+keyType.getKeyType()+", %s>" : "").removeBraces().setBraceType("<>");
addInjectMapper(" VSV_GENERIC_TYPE", valueType.isObject() ? "<%s, "+valueType.getValueType()+">" : "<%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("<>");
addInjectMapper(" SV_GENERIC_TYPE", valueType.isObject() ? "<%s, "+valueType.getValueType()+">" : "").removeBraces().setBraceType("<>");
addInjectMapper(" VS_GENERIC_TYPE", valueType.isObject() ? "<"+valueType.getValueType()+", %s>" : "").removeBraces().setBraceType("<>");
addSimpleMapper(" GENERIC_KEY_BRACES", keyType.isObject() ? " <"+keyType.getKeyType()+">" : "");
addSimpleMapper(" GENERIC_VALUE_BRACES", valueType.isObject() ? " <"+valueType.getValueType()+">" : "");
addInjectMapper(" GENERIC_SPECIAL_KEY_BRACES", keyType.isObject() ? " <%s>" : "").removeBraces().setBraceType("<>");
addInjectMapper(" GENERIC_SPECIAL_VALUE_BRACES", valueType.isObject() ? " <%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(" GENERIC_KEY_SPECIAL_BRACES", keyType.isObject() ? " <"+keyType.getKeyType()+", %s>" : " <%s>").removeBraces().setBraceType("<>");
addInjectMapper(" GENERIC_VALUE_SPECIAL_BRACES", valueType.isObject() ? " <"+valueType.getKeyType()+", %s>" : " <%s>").removeBraces().setBraceType("<>");
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("KV_BRACES", keyType.isObject() || valueType.isObject() ? "<>" : "");
addSimpleMapper("VALUE_BRACES", valueType.isObject() ? "<>" : "");
addSimpleMapper("BRACES", keyType.isObject() ? "<>" : "");
if(keyType.needsCustomJDKType())
{
addSimpleMapper("JAVA_TYPE", keyType.getCustomJDKType().getKeyType());
addSimpleMapper("SANITY_CAST", "castTo"+keyType.getFileType());
}
addSimpleMapper("JAVA_CLASS", keyType.getCustomJDKType().getClassType());
if(valueType.needsCustomJDKType())
{
addSimpleMapper("SANITY_CAST_VALUE", "castTo"+valueType.getFileType());
}
addSimpleMapper("[SPACE]", " ");
addComment("@ArrayType", "@param <%s> the keyType of array that the operation should be applied");
addComment("@Type", "@param <%s> the keyType of elements maintained by this Collection");
addValueComment("@ValueArrayType", "@param <%s> the keyType of array that the operation should be applied");
addValueComment("@ValueType", "@param <%s> the keyType of elements maintained by this Collection");
addAnnontion("@PrimitiveOverride", "@Override");
addSimpleMapper("@PrimitiveDoc", "");
addAnnontion("@Primitive", "@Deprecated");
addValueAnnontion("@ValuePrimitiveOverride", "@Override");
addValueAnnontion("@ValuePrimitive", "@Deprecated");
}
private void createHelperVars(ClassType type, boolean value, String fix)
{
addArgumentMapper("EQUALS_"+fix+"_TYPE", "Objects.equals(%2$s, "+(type.isObject() ? "%1$s" : fix+"_TO_OBJ(%1$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();
addArgumentMapper(fix+"_EQUALS_NOT", type.getEquals(true)).removeBraces();
addArgumentMapper(fix+"_EQUALS", type.getEquals(false)).removeBraces();
addSimpleMapper("FILE_"+fix+"_TYPE", type.getFileType());
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();
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();
}
}
@@ -0,0 +1,120 @@
package speiger.src.builder.modules;
import java.util.Arrays;
import java.util.List;
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")
public class ListModule extends BaseModule
{
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
public String getModuleName() { return "List"; }
@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() {}
@Override
protected void loadFlags() {
if(MODULE.isEnabled()) addKeyFlag("LIST_MODULE");
if(WRAPPERS.isEnabled()) addKeyFlag("LISTS_FEATURE");
if(ARRAY_LIST.isEnabled()) addKeyFlag("ARRAY_LIST_FEATURE");
if(LINKED_LIST.isEnabled()) addKeyFlag("LINKED_LIST_FEATURE");
if(IMMUTABLE_LIST.isEnabled()) addKeyFlag("IMMUTABLE_LIST_FEATURE");
if(COPY_ON_WRITE_LIST.isEnabled()) addKeyFlag("COPY_ON_WRITE_LIST_FEATURE");
}
@Override
protected void loadBlockades()
{
if(!WRAPPERS.isEnabled()) addBlockedFiles("Lists");
if(!ARRAY_LIST.isEnabled()) addBlockedFiles("ArrayList");
if(!LINKED_LIST.isEnabled()) addBlockedFiles("LinkedList");
if(!IMMUTABLE_LIST.isEnabled()) addBlockedFiles("ImmutableList");
if(!COPY_ON_WRITE_LIST.isEnabled()) addBlockedFiles("CopyOnWriteList");
if(!MODULE.isEnabled()) addBlockedFiles("List", "AbstractList");
if(keyType.isObject()) addBlockedFiles("ListFillBufferTester");
if(keyType == ClassType.BOOLEAN) addBlockedFiles("ListFillBufferTester", "ListReplaceAllTester");
}
@Override
protected void loadRemappers()
{
//Main Classes
addRemapper("AbstractList", "Abstract%sList");
addRemapper("ImmutableList", "Immutable%sList");
addRemapper("CopyOnWriteList", "CopyOnWrite%sArrayList");
//Test Classes
addRemapper("AbstractListTester", "Abstract%sListTester");
addRemapper("AbstractListIndexOfTester", "Abstract%sListIndexOfTester");
addRemapper("TestListGenerator", "Test%sListGenerator");
}
@Override
protected void loadFunctions()
{
addFunctionMapper("GET_KEY", "get");
addFunctionMapper("GET_FIRST_KEY", "getFirst");
addFunctionMapper("GET_LAST_KEY", "getLast");
addFunctionMapper("REMOVE_FIRST_KEY", "removeFirst");
addFunctionMapper("REMOVE_LAST_KEY", "removeLast");
addFunctionMapper("REMOVE_SWAP", "swapRemove");
addFunctionMappers("REPLACE", keyType.isObject() ? "replaceObjects" : "replace%ss");
addFunctionMappers("SORT", "sort%ss");
}
@Override
protected void loadClasses()
{
//Implementation Classes
addClassMapper("ARRAY_LIST", "ArrayList");
addAbstractMapper("COPY_ON_WRITE_LIST", "CopyOnWrite%sArrayList");
addClassMapper("LINKED_LIST", "LinkedList");
addAbstractMapper("IMMUTABLE_LIST", "Immutable%sList");
//Abstract Classes
addAbstractMapper("ABSTRACT_LIST", "Abstract%sList");
//SubClasses
addClassMapper("SUB_LIST", "SubList");
addClassMapper("LIST_ITER", "ListIter");
//Helper Classes
addClassMapper("LISTS", "Lists");
//Interfaces
addClassMapper("LIST", "List");
}
@Override
protected void loadTestClasses()
{
//Implementation Classes
addClassMapper("LIST_TEST_BUILDER", "ListTestSuiteBuilder");
addClassMapper("LIST_TESTS", "ListTests");
//Abstract Classes
addAbstractMapper("ABSTRACT_LIST_INDEX_OF_TESTER", "Abstract%sListIndexOfTester");
addAbstractMapper("ABSTRACT_LIST_TESTER", "Abstract%sListTester");
//Helper classes
addAbstractMapper("TEST_LIST_GENERATOR", "Test%sListGenerator");
}
}
@@ -0,0 +1,290 @@
package speiger.src.builder.modules;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
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")
public class MapModule extends BaseModule
{
public static final BaseModule INSTANCE = new MapModule();
public static final ModuleDependency MODULE = new ModuleDependency(INSTANCE, true)
.addKeyDependency(SetModule.MODULE)
.addValueDependency(CollectionModule.MODULE)
.addEntryDependency(SetModule.MODULE)
.addTypeDependency(SetModule.MODULE, ClassType.OBJECT);
public static final FunctionDependency IMPLEMENTATION = MODULE.createDependency("Implementations");
public static final FunctionDependency WRAPPERS = MODULE.createDependency("Wrappers").addKeyDependency(SetModule.WRAPPERS).addOptionalTypeDependency(SetModule.WRAPPERS, ClassType.OBJECT, true);
public static final FunctionDependency ORDERED_MAP = MODULE.createDependency("OrderedMap").addKeyDependency(SetModule.ORDERED_SET).addOptionalTypeDependency(SetModule.ORDERED_SET, ClassType.OBJECT, true);
public static final FunctionDependency SORTED_MAP = MODULE.createDependency("SortedMap").addKeyDependency(SetModule.SORTED_SET).addOptionalTypeDependency(SetModule.SORTED_SET, ClassType.OBJECT, true);
public static final FunctionDependency ARRAY_MAP = MODULE.createDependency("ArrayMap").addEntryDependency(ORDERED_MAP).addEntryDependency(IMPLEMENTATION);
public static final FunctionDependency IMMUTABLE_MAP = MODULE.createDependency("ImmutableMap").addEntryDependency(IMPLEMENTATION);
public static final FunctionDependency HASH_MAP = MODULE.createDependency("HashMap").addEntryDependency(IMPLEMENTATION);
public static final FunctionDependency LINKED_MAP = MODULE.createDependency("LinkedHashMap").addEntryDependency(HASH_MAP).addEntryDependency(ORDERED_MAP);
public static final FunctionDependency CUSTOM_MAP = MODULE.createDependency("CustomHashMap").addEntryDependency(IMPLEMENTATION).addKeyDependency(CollectionModule.STRATEGY);
public static final FunctionDependency LINKED_CUSTOM_MAP = MODULE.createDependency("LinkedCustomHashMap").addEntryDependency(CUSTOM_MAP).addEntryDependency(ORDERED_MAP);
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);
public static final FunctionDependency CONCURRENT_MAP = MODULE.createDependency("ConcurrentMap").addEntryDependency(IMPLEMENTATION);
public static final FunctionDependency AVL_TREE_MAP = MODULE.createDependency("AVLTreeMap").addEntryDependency(SORTED_MAP).addEntryDependency(IMPLEMENTATION);
public static final FunctionDependency RB_TREE_MAP = MODULE.createDependency("RBTreeMap").addEntryDependency(SORTED_MAP).addEntryDependency(IMPLEMENTATION);
@Override
public String getModuleName() { return "Map"; }
@Override
public boolean isBiModule() { return true; }
@Override
protected void loadVariables() {}
@Override
public boolean isModuleValid(ClassType keyType, ClassType valueType) { return keyType != ClassType.BOOLEAN; }
@Override
public List<IDependency> getDependencies(ClassType keyType, ClassType valueType) {
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(keyType == ClassType.OBJECT) dependencies.addAll(Arrays.asList(ENUM_MAP, LINKED_ENUM_MAP));
return dependencies;
}
@Override
protected void loadFlags()
{
if(MODULE.isEnabled()) addFlag("MAP_MODULE");
if(WRAPPERS.isEnabled()) addFlag("MAPS_FEATURE");
if(ORDERED_MAP.isEnabled()) addFlag("ORDERED_MAP_FEATURE");
if(ARRAY_MAP.isEnabled()) addFlag("ARRAY_MAP_FEATURE");
if(LINKED_MAP.isEnabled()) addFlag("LINKED_MAP_FEATURE");
if(LINKED_CUSTOM_MAP.isEnabled()) addFlag("LINKED_CUSTOM_MAP_FEATURE");
if(LINKED_ENUM_MAP.isEnabled()) addFlag("LINKED_ENUM_MAP_FEATURE");
if(SORTED_MAP.isEnabled()) addFlag("SORTED_MAP_FEATURE");
if(AVL_TREE_MAP.isEnabled()) addFlag("AVL_TREE_MAP_FEATURE");
if(RB_TREE_MAP.isEnabled()) addFlag("RB_TREE_MAP_FEATURE");
if(CONCURRENT_MAP.isEnabled()) addFlag("CONCURRENT_MAP_FEATURE");
if(IMMUTABLE_MAP.isEnabled()) addFlag("IMMUTABLE_MAP_FEATURE");
if(HASH_MAP.isEnabled()) addFlag("MAP_FEATURE");
if(CUSTOM_MAP.isEnabled()) addFlag("CUSTOM_MAP_FEATURE");
if(ENUM_MAP.isEnabled()) addFlag("ENUM_MAP_FEATURE");
}
@Override
protected void loadBlockades()
{
if(!MODULE.isEnabled()) addBlockedFiles("Map", "AbstractMap");
if(!WRAPPERS.isEnabled()) addBlockedFiles("Maps");
if(!IMMUTABLE_MAP.isEnabled()) addBlockedFiles("ImmutableOpenHashMap");
if(!CONCURRENT_MAP.isEnabled()) addBlockedFiles("ConcurrentMap", "ConcurrentOpenHashMap");
if(!ORDERED_MAP.isEnabled()) addBlockedFiles("OrderedMap");
if(!HASH_MAP.isEnabled()) addBlockedFiles("OpenHashMap");
if(!LINKED_MAP.isEnabled()) addBlockedFiles("LinkedOpenHashMap");
if(!CUSTOM_MAP.isEnabled()) addBlockedFiles("OpenCustomHashMap");
if(!LINKED_CUSTOM_MAP.isEnabled()) addBlockedFiles("LinkedOpenCustomHashMap");
if(!ENUM_MAP.isEnabled()) addBlockedFiles("EnumMap");
if(!LINKED_ENUM_MAP.isEnabled()) addBlockedFiles("LinkedEnumMap");
if(!ARRAY_MAP.isEnabled()) addBlockedFiles("ArrayMap");
if(!SORTED_MAP.isEnabled()) addBlockedFiles("SortedMap", "NavigableMap");
if(!AVL_TREE_MAP.isEnabled()) addBlockedFiles("AVLTreeMap");
if(!RB_TREE_MAP.isEnabled()) addBlockedFiles("RBTreeMap");
if(keyType == ClassType.BOOLEAN)
{
//Main Classes
addBlockedFiles("SortedMap", "NavigableMap", "RBTreeMap", "AVLTreeMap");
addBlockedFiles("OrderedMap", "ArrayMap", "LinkedOpenHashMap", "LinkedOpenCustomHashMap");
addBlockedFiles("ConcurrentMap", "ConcurrentOpenHashMap");
addBlockedFiles("Map", "Maps", "AbstractMap", "ImmutableOpenHashMap", "OpenHashMap", "OpenCustomHashMap");
//Test Classes
addBlockedFiles("TestMap", "MapTests", "MapTestSuiteBuilder", "MapConstructorTests", "TestMapGenerator", "SimpleMapTestGenerator", "DerivedMapGenerators", "AbstractMapTester");
addBlockedFiles("TestSortedMapGenerator", "OrderedMapTestSuiteBuilder", "NavigableMapTestSuiteBuilder", "SortedMapTestSuiteBuilder");
addBlockedFiles("TestOrderedMapGenerator");
addBlockedFilter(T -> T.endsWith("Tester") && (T.startsWith("Map") || T.startsWith("OrderedMap") || T.startsWith("SortedMap") || T.startsWith("NavigableMap")));
}
if(valueType == ClassType.OBJECT) {
addBlockedFiles("MapComputeIfAbsentNonDefaultTester", "MapComputeIfPresentNonDefaultTester", "MapComputeNonDefaultTester", "MapSupplyIfAbsentNonDefaultTester");
}
}
@Override
protected void loadRemappers()
{
//Main Classes
addBiRequirement("Map");
addBiRequirement("SortedMap");
addBiRequirement("OrderedMap");
addBiRequirement("NavigableMap");
addBiRequirement("ConcurrentMap");
addBiRequirement("AbstractMap");
addEnumRequirement("EnumMap");
addEnumRequirement("LinkedEnumMap");
addBiRequirement("ConcurrentOpenHashMap");
addBiRequirement("ImmutableOpenHashMap");
addBiRequirement("OpenHashMap");
addBiRequirement("LinkedOpenHashMap");
addBiRequirement("OpenCustomHashMap");
addBiRequirement("LinkedOpenCustomHashMap");
addBiRequirement("ArrayMap");
addBiRequirement("RBTreeMap");
addBiRequirement("AVLTreeMap");
addBiRequirement("Maps");
addRemapper("AbstractMap", "Abstract%sMap");
addRemapper("EnumMap", "Enum2%sMap");
addRemapper("LinkedEnumMap", "LinkedEnum2%sMap");
addRemapper("ImmutableOpenHashMap", "Immutable%sOpenHashMap");
//Test Classes
addBiRequirement("TestMapGenerator");
addBiRequirement("TestSortedMapGenerator");
addBiRequirement("TestOrderedMapGenerator");
addBiRequirement("SimpleMapTestGenerator");
addBiRequirement("DerivedMapGenerators");
addBiRequirement("AbstractMapTester");
addBiRequirement("MapTestSuiteBuilder");
addBiRequirement("SortedMapTestSuiteBuilder");
addBiRequirement("NavigableMapTestSuiteBuilder");
addBiRequirement("OrderedMapTestSuiteBuilder");
addBiRequirement("MapTests");
addBiRequirement("MapConstructorTests");
addBiRequirement("TestMap");
addBiRequirement("MapAddToTester");
addBiRequirement("MapSubFromTester");
addBiRequirement("MapClearTester");
addBiRequirement("MapComputeIfAbsentTester");
addBiRequirement("MapComputeIfPresentTester");
addBiRequirement("MapComputeTester");
addBiRequirement("MapComputeIfAbsentNonDefaultTester");
addBiRequirement("MapComputeIfPresentNonDefaultTester");
addBiRequirement("MapComputeNonDefaultTester");
addBiRequirement("MapCopyTester");
addBiRequirement("MapContainsTester");
addBiRequirement("MapContainsKeyTester");
addBiRequirement("MapContainsValueTester");
addBiRequirement("MapCreatorTester");
addBiRequirement("MapEntrySetTester");
addBiRequirement("MapEqualsTester");
addBiRequirement("MapForEachTester");
addBiRequirement("MapGetOrDefaultTester");
addBiRequirement("MapGetTester");
addBiRequirement("MapHashCodeTester");
addBiRequirement("MapIsEmptyTester");
addBiRequirement("MapMergeTester");
addBiRequirement("MapMergeBulkTester");
addBiRequirement("MapPutAllArrayTester");
addBiRequirement("MapPutAllTester");
addBiRequirement("MapPutIfAbsentTester");
addBiRequirement("MapPutTester");
addBiRequirement("MapRemoveEntryTester");
addBiRequirement("MapRemoveOrDefaultTester");
addBiRequirement("MapRemoveTester");
addBiRequirement("MapReplaceAllTester");
addBiRequirement("MapReplaceEntryTester");
addBiRequirement("MapReplaceTester");
addBiRequirement("MapSizeTester");
addBiRequirement("MapSupplyIfAbsentTester");
addBiRequirement("MapSupplyIfAbsentNonDefaultTester");
addBiRequirement("MapToStringTester");
addBiRequirement("NavigableMapNavigationTester");
addBiRequirement("SortedMapNavigationTester");
addBiRequirement("OrderedMapNavigationTester");
addBiRequirement("OrderedMapMoveTester");
addBiRequirement("MapConstructorTester");
addRemapper("TestMapGenerator", "Test%sMapGenerator");
addRemapper("TestSortedMapGenerator", "Test%sSortedMapGenerator");
addRemapper("TestOrderedMapGenerator", "Test%sOrderedMapGenerator");
addRemapper("SimpleMapTestGenerator", "Simple%sMapTestGenerator");
addRemapper("DerivedMapGenerators", "Derived%sMapGenerators");
addRemapper("AbstractMapTester", "Abstract%sMapTester");
addRemapper("TestMap", "Test%sMap");
}
@Override
protected void loadFunctions()
{
addFunctionValueMapper("BULK_MERGE", "mergeAll");
addFunctionValueMappers("COMPUTE_IF_ABSENT", "compute%sIfAbsent");
addFunctionValueMappers("COMPUTE_IF_PRESENT", "compute%sIfPresent");
addFunctionValueMapper("COMPUTE", "compute");
addFunctionMapper("DEQUEUE_LAST", "dequeueLast");
addFunctionMapper("DEQUEUE", "dequeue");
addSimpleMapper("ENTRY_SET", keyType.getFileType().toLowerCase()+"2"+valueType.getFileType()+"EntrySet");
addFunctionMappers("FIRST_ENTRY_KEY", "first%sKey");
addFunctionValueMappers("FIRST_ENTRY_VALUE", "first%sValue");
if(keyType.isObject()) addFunctionValueMapper("GET_VALUE", valueType.isObject() ? "getObject" : "get");
else addSimpleMapper("GET_VALUE", "get");
addFunctionMappers("LAST_ENTRY_KEY", "last%sKey");
addFunctionValueMappers("LAST_ENTRY_VALUE", "last%sValue");
addFunctionValueMapper("MERGE", "merge");
addFunctionMappers("POLL_FIRST_ENTRY_KEY", "pollFirst%sKey");
addFunctionMappers("POLL_LAST_ENTRY_KEY", "pollLast%sKey");
if(keyType.isObject()) addFunctionMapper("REMOVE_VALUE", "rem");
else addSimpleMapper("REMOVE_VALUE", "remove");
addFunctionMapper("REMOVE", "remove");
addFunctionValueMappers("REPLACE_VALUES", valueType.isObject() ? "replaceObjects" : "replace%ss");
addFunctionValueMappers("SUPPLY_IF_ABSENT", "supply%sIfAbsent");
}
@Override
protected void loadClasses()
{
//Implementation Classes
addAbstractBiMapper("IMMUTABLE_HASH_MAP", "Immutable%sOpenHashMap", "2");
addBiClassMapper("LINKED_CUSTOM_HASH_MAP", "LinkedOpenCustomHashMap", "2");
addBiClassMapper("LINKED_HASH_MAP", "LinkedOpenHashMap", "2");
addBiClassMapper("CUSTOM_HASH_MAP", "OpenCustomHashMap", "2");
addBiClassMapper("CONCURRENT_HASH_MAP", "ConcurrentOpenHashMap", "2");
addBiClassMapper("AVL_TREE_MAP", "AVLTreeMap", "2");
addBiClassMapper("RB_TREE_MAP", "RBTreeMap", "2");
addFunctionValueMappers("LINKED_ENUM_MAP", valueType.isObject() ? "LinkedEnum2ObjectMap" : "LinkedEnum2%sMap");
addFunctionValueMappers("ENUM_MAP", valueType.isObject() ? "Enum2ObjectMap" : "Enum2%sMap");
addBiClassMapper("HASH_MAP", "OpenHashMap", "2");
addBiClassMapper("ARRAY_MAP", "ArrayMap", "2");
//Abstract Classes
addAbstractBiMapper("ABSTRACT_MAP", "Abstract%sMap", "2");
//Helper Classes
addBiClassMapper("MAPS", "Maps", "2");
//Interfaces
addBiClassMapper("NAVIGABLE_MAP", "NavigableMap", "2");
addBiClassMapper("ORDERED_MAP", "OrderedMap", "2");
addBiClassMapper("SORTED_MAP", "SortedMap", "2");
addBiClassMapper("CONCURRENT_MAP", "ConcurrentMap", "2");
addBiClassMapper("MAP", "Map", "2");
}
@Override
protected void loadTestClasses()
{
//Implementation Classes
addAbstractBiMapper("SIMPLE_TEST_MAP", "Test%sMap", "2");
addBiClassMapper("MAP_TESTS", "MapTests", "2");
addAbstractBiMapper("NAVIGABLE_MAP_TEST_BUILDER", "%sNavigableMapTestSuiteBuilder", "2");
addAbstractBiMapper("SORTED_MAP_TEST_BUILDER", "%sSortedMapTestSuiteBuilder", "2");
addAbstractBiMapper("ORDERED_MAP_TEST_BUILDER", "%sOrderedMapTestSuiteBuilder", "2");
addAbstractBiMapper("MAP_TEST_BUILDER", "%sMapTestSuiteBuilder", "2");
//Abstract Classes
addAbstractBiMapper("ABSTRACT_MAP_TESTER", "Abstract%sMapTester", "2");
//Helper Classes
addAbstractBiMapper("MAP_CONSTRUCTOR_TESTS", "%sMapConstructorTests", "2");
addAbstractBiMapper("SIMPLE_MAP_TEST_GENERATOR", "Simple%sMapTestGenerator", "2");
addAbstractBiMapper("DERIVED_MAP_GENERATORS", "Derived%sMapGenerators", "2");
addAbstractBiMapper("TEST_ORDERED_MAP_GENERATOR", "Test%sOrderedMapGenerator", "2");
addAbstractBiMapper("TEST_SORTED_MAP_GENERATOR", "Test%sSortedMapGenerator", "2");
addAbstractBiMapper("TEST_MAP_GENERATOR", "Test%sMapGenerator", "2");
}
}
@@ -0,0 +1,71 @@
package speiger.src.builder.modules;
import java.util.Arrays;
import java.util.List;
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")
public class PairModule extends BaseModule
{
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
public String getModuleName() { return "Pair"; }
@Override
public boolean isBiModule() { return true; }
@Override
protected void loadVariables() {}
@Override
protected void loadFunctions() {}
@Override
protected void loadTestClasses() {}
@Override
public List<IDependency> getDependencies(ClassType keyType, ClassType valueType) { return Arrays.asList(MODULE, IMMUTABLE, MUTABLE); }
@Override
protected void loadFlags() {
if(MODULE.isEnabled()) addFlag("PAIR_MODULE");
if(MUTABLE.isEnabled()) addFlag("MUTABLE_PAIR");
if(IMMUTABLE.isEnabled()) addFlag("IMMUTABLE_PAIR");
}
@Override
protected void loadBlockades() {
if(!MODULE.isEnabled()) addBlockedFiles("Pair");
if(!MUTABLE.isEnabled()) addBlockedFiles("MutablePair");
if(!IMMUTABLE.isEnabled()) addBlockedFiles("ImmutablePair");
}
@Override
protected void loadRemappers() {
//Main Classes
addBiRequirement("Pair", "");
addBiRequirement("MutablePair", "");
addBiRequirement("ImmutablePair", "");
//Test Classes
addBiRequirement("PairTester", "");
}
@Override
protected void loadClasses() {
//Implementations
addBiClassMapper("IMMUTABLE_PAIR", "ImmutablePair", "");
addBiClassMapper("MUTABLE_PAIR", "MutablePair", "");
//Interfaces
addBiClassMapper("PAIR", "Pair", "");
}
}
@@ -0,0 +1,102 @@
package speiger.src.builder.modules;
import java.util.Arrays;
import java.util.List;
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")
public class PrioQueueModule extends BaseModule
{
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
public String getModuleName() { return "PriorityQueue"; }
@Override
protected void loadVariables() {}
@Override
protected void loadFunctions() {}
@Override
public List<IDependency> getDependencies(ClassType keyType, ClassType valueType) { return Arrays.asList(MODULE, WRAPPERS, IMPLEMENTATION, DEQUEUE, FIFO_QUEUE, HEAP_QUEUE, ARRAY_PRIO_QUEUE); }
@Override
protected void loadFlags() {
if(MODULE.isEnabled()) addFlag("QUEUE_MODULE");
if(WRAPPERS.isEnabled()) addKeyFlag("QUEUES_FEATURE");
if(DEQUEUE.isEnabled()) addKeyFlag("DEQUEUE_FEATURE");
if(FIFO_QUEUE.isEnabled()) addKeyFlag("FIFO_QUEUE_FEATURE");
if(HEAP_QUEUE.isEnabled()) addKeyFlag("HEAP_QUEUE_FEATURE");
if(ARRAY_PRIO_QUEUE.isEnabled()) addKeyFlag("ARRAY_QUEUE_FEATURE");
}
@Override
protected void loadBlockades() {
if(!MODULE.isEnabled()) addBlockedFiles("PriorityQueue", "AbstractPriorityQueue");
if(!WRAPPERS.isEnabled()) addBlockedFiles("PriorityQueues");
if(!DEQUEUE.isEnabled()) addBlockedFiles("PriorityDequeue");
if(!FIFO_QUEUE.isEnabled()) addBlockedFiles("ArrayFIFOQueue");
if(!HEAP_QUEUE.isEnabled()) addBlockedFiles("HeapPriorityQueue");
if(!ARRAY_PRIO_QUEUE.isEnabled()) addBlockedFiles("ArrayPriorityQueue");
if(keyType == ClassType.BOOLEAN) {
addBlockedFiles("QueueTests");
}
}
@Override
protected void loadRemappers() {
//Main Classes
addRemapper("AbstractPriorityQueue", "Abstract%sPriorityQueue");
//Test Classes
addRemapper("TestQueueGenerator", "Test%sQueueGenerator");
addRemapper("AbstractQueueTester", "Abstract%sQueueTester");
addRemapper("SimpleQueueTestGenerator", "Simple%sQueueTestGenerator");
}
@Override
protected void loadClasses() {
//Implementation Classes
addClassMapper("ARRAY_FIFO_QUEUE", "ArrayFIFOQueue");
addClassMapper("ARRAY_PRIORITY_QUEUE", "ArrayPriorityQueue");
addClassMapper("HEAP_PRIORITY_QUEUE", "HeapPriorityQueue");
//Abstract Classes
addAbstractMapper("ABSTRACT_PRIORITY_QUEUE", "Abstract%sPriorityQueue");
//Helper Classes
addClassMapper("PRIORITY_QUEUES", "PriorityQueues");
//Interfaces
addClassMapper("PRIORITY_QUEUE", "PriorityQueue");
addClassMapper("PRIORITY_DEQUEUE", "PriorityDequeue");
}
@Override
protected void loadTestClasses()
{
//Implementation Classes
addClassMapper("DEQUEUE_TEST_BUILDER", "DequeueTestSuiteBuilder");
addClassMapper("QUEUE_TEST_BUILDER", "QueueTestSuiteBuilder");
addClassMapper("QUEUE_TESTS", "QueueTests");
//Abstract Classes
addAbstractMapper("ABSTRACT_QUEUE_TESTER", "Abstract%sQueueTester");
//Helper Classes
addAbstractMapper("SIMPLE_QUEUE_TEST_GENERATOR", "Simple%sQueueTestGenerator");
addAbstractMapper("TEST_QUEUE_GENERATOR", "Test%sQueueGenerator");
}
}
@@ -0,0 +1,161 @@
package speiger.src.builder.modules;
import java.util.Arrays;
import java.util.List;
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")
public class SetModule extends BaseModule
{
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
public String getModuleName() { return "Set"; }
@Override
protected void loadVariables() {}
@Override
public boolean isModuleValid(ClassType keyType, ClassType valueType) { return keyType != ClassType.BOOLEAN; }
@Override
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
protected void loadFlags()
{
if(MODULE.isEnabled()) addFlag("SET_MODULE");
if(WRAPPERS.isEnabled()) addFlag("SETS_FEATURE");
if(ORDERED_SET.isEnabled()) addFlag("ORDERED_SET_FEATURE");
if(SORTED_SET.isEnabled()) addFlag("SORTED_SET_FEATURE");
if(IMMUTABLE_SET.isEnabled()) addFlag("IMMUTABLE_SET_FEATURE");
if(ARRAY_SET.isEnabled()) addFlag("ARRAY_SET_FEATURE");
if(HASH_SET.isEnabled()) addFlag("HASH_SET_FEATURE");
if(LINKED_SET.isEnabled()) addFlag("LINKED_SET_FEATURE");
if(CUSTOM_SET.isEnabled()) addFlag("CUSTOM_HASH_SET_FEATURE");
if(LINKED_CUSTOM_SET.isEnabled()) 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");
}
@Override
protected void loadBlockades()
{
if(!MODULE.isEnabled()) addBlockedFiles("Set", "AbstractSet");
if(!WRAPPERS.isEnabled()) addBlockedFiles("Sets");
if(!IMMUTABLE_SET.isEnabled()) addBlockedFiles("ImmutableOpenHashSet");
if(!ORDERED_SET.isEnabled()) addBlockedFiles("OrderedSet");
if(!HASH_SET.isEnabled()) addBlockedFiles("OpenHashSet");
if(!LINKED_SET.isEnabled()) addBlockedFiles("LinkedOpenHashSet");
if(!CUSTOM_SET.isEnabled()) addBlockedFiles("OpenCustomHashSet");
if(!LINKED_CUSTOM_SET.isEnabled()) addBlockedFiles("LinkedOpenCustomHashSet");
if(!ARRAY_SET.isEnabled()) addBlockedFiles("ArraySet");
if(!SORTED_SET.isEnabled()) addBlockedFiles("SortedSet", "NavigableSet");
if(!AVL_TREE_SET.isEnabled()) addBlockedFiles("AVLTreeSet");
if(!RB_TREE_SET.isEnabled()) addBlockedFiles("RBTreeSet");
if(keyType == ClassType.BOOLEAN)
{
//Main Classes
addBlockedFiles("SortedSet", "NavigableSet", "AVLTreeSet", "RBTreeSet");
addBlockedFiles("OrderedSet", "ArraySet", "LinkedOpenHashSet", "LinkedOpenCustomHashSet");
addBlockedFiles("Set", "Sets", "AbstractSet", "OpenHashSet", "OpenCustomHashSet", "ImmutableOpenHashSet");
//Test Classes
addBlockedFiles("SetTests", "SetTestSuiteBuilder", "TestSetGenerator");
addBlockedFiles("OrderedSetTestSuiteBuilder", "TestOrderedSetGenerator", "OrderedSetMoveTester", "OrderedSetNavigationTester", "OrderedSetIterationTester");
addBlockedFiles("SortedSetTestSuiteBuilder", "TestSortedSetGenerator", "SortedSetNaviationTester", "SortedSetSubsetTestSetGenerator", "SortedSetIterationTester", "SortedSetNaviationTester");
addBlockedFiles("NavigableSetTestSuiteBuilder", "TestNavigableSetGenerator", "NavigableSetNavigationTester");
addBlockedFiles("MinimalSet", "AbstractSetTester", "SetAddAllTester", "SetAddTester", "SetCreationTester", "SetEqualsTester", "SetRemoveTester");
}
}
@Override
protected void loadRemappers()
{
//Main Classes
addRemapper("AbstractSet", "Abstract%sSet");
addRemapper("ImmutableOpenHashSet", "Immutable%sOpenHashSet");
//Test Classes
addRemapper("MinimalSet", "Minimal%sSet");
addRemapper("TestNavigableSetGenerator", "Test%sNavigableSetGenerator");
addRemapper("TestSortedSetGenerator", "Test%sSortedSetGenerator");
addRemapper("TestOrderedSetGenerator", "Test%sOrderedSetGenerator");
addRemapper("TestSetGenerator", "Test%sSetGenerator");
addRemapper("AbstractSetTester", "Abstract%sSetTester");
}
@Override
protected void loadFunctions()
{
addFunctionMapper("POLL_FIRST_KEY", "pollFirst");
addFunctionMapper("POLL_LAST_KEY", "pollLast");
addFunctionMapper("FIRST_KEY", "first");
addFunctionMapper("LAST_KEY", "last");
}
@Override
protected void loadTestClasses()
{
//Implementation Classes
addAbstractMapper("MINIMAL_SET", "Minimal%sSet");
addClassMapper("ORDERED_SET_TEST_BUILDER", "OrderedSetTestSuiteBuilder");
addClassMapper("SORTED_SET_TEST_BUILDER", "SortedSetTestSuiteBuilder");
addClassMapper("NAVIGABLE_SET_TEST_BUILDER", "NavigableSetTestSuiteBuilder");
addClassMapper("SET_TEST_BUILDER", "SetTestSuiteBuilder");
addClassMapper("SET_TESTS", "SetTests");
//Abstract Classes
addAbstractMapper("ABSTRACT_SET_TESTER", "Abstract%sSetTester");
//Helper Classes
addClassMapper("SUB_SORTED_SET_CLASS_GENERATOR", "SortedSetSubsetTestSetGenerator");
addClassMapper("SUB_NAVIGABLE_SET_CLASS_GENERATOR", "NavigableSetSubsetTestSetGenerator");
addAbstractMapper("TEST_NAVIGABLE_SET_GENERATOR", "Test%sNavigableSetGenerator");
addAbstractMapper("TEST_SORTED_SET_GENERATOR", "Test%sSortedSetGenerator");
addAbstractMapper("TEST_ORDERED_SET_GENERATOR", "Test%sOrderedSetGenerator");
addAbstractMapper("TEST_SET_GENERATOR", "Test%sSetGenerator");
}
@Override
protected void loadClasses()
{
//Implementation Classes
addClassMapper("LINKED_CUSTOM_HASH_SET", "LinkedOpenCustomHashSet");
addClassMapper("LINKED_HASH_SET", "LinkedOpenHashSet");
addAbstractMapper("IMMUTABLE_HASH_SET", "Immutable%sOpenHashSet");
addClassMapper("CUSTOM_HASH_SET", "OpenCustomHashSet");
addClassMapper("HASH_SET", "OpenHashSet");
addClassMapper("RB_TREE_SET", "RBTreeSet");
addClassMapper("AVL_TREE_SET", "AVLTreeSet");
addClassMapper("ARRAY_SET", "ArraySet");
//Abstract Classes
addAbstractMapper("ABSTRACT_SET", "Abstract%sSet");
//Helper Classes
addClassMapper("SETS", "Sets");
//Interfaces
addClassMapper("NAVIGABLE_SET", "NavigableSet");
addClassMapper("SORTED_SET", "SortedSet");
addClassMapper("ORDERED_SET", "OrderedSet");
addClassMapper("SET", "Set");
}
}
@@ -1,210 +1,266 @@
package speiger.src.collections.PACKAGE.collections; package speiger.src.collections.PACKAGE.collections;
import java.util.Collection; import java.util.Collection;
import java.util.Objects; import java.util.Objects;
import java.util.AbstractCollection; import java.util.AbstractCollection;
#if TYPE_OBJECT
import speiger.src.collections.PACKAGE.collections.COLLECTION; import java.util.function.Consumer;
#if !TYPE_OBJECT #endif
import speiger.src.collections.PACKAGE.utils.ITERATORS;
#endif #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.CONSUMER;
/** import speiger.src.collections.PACKAGE.utils.ITERATORS;
* Abstract Type Specific Collection that reduces boxing/unboxing import speiger.src.collections.PACKAGE.utils.ARRAYS;
* @Type(T) #endif
*/
public abstract class ABSTRACT_COLLECTION KEY_GENERIC_TYPE extends AbstractCollection<CLASS_TYPE> implements COLLECTION KEY_GENERIC_TYPE /**
{ * Abstract Type Specific Collection that reduces boxing/unboxing
@Override * @Type(T)
public abstract ITERATOR KEY_GENERIC_TYPE iterator(); */
public abstract class ABSTRACT_COLLECTION KEY_GENERIC_TYPE extends AbstractCollection<CLASS_TYPE> implements COLLECTION KEY_GENERIC_TYPE
#if !TYPE_OBJECT {
/** {@inheritDoc} @Override
* <p>This default implementation delegates to the corresponding type-specific function. public abstract ITERATOR KEY_GENERIC_TYPE iterator();
* @deprecated Please use the corresponding type-specific function instead.
*/ #if !TYPE_OBJECT
@Override /** {@inheritDoc}
@Deprecated * <p>This default implementation delegates to the corresponding type-specific function.
public boolean add(CLASS_TYPE e) { return COLLECTION.super.add(e); } * @deprecated Please use the corresponding type-specific function instead.
*/
#endif @Override
@Override @Deprecated
public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) { public boolean add(CLASS_TYPE e) { return COLLECTION.super.add(e); }
boolean modified = false;
for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();modified |= add(iter.NEXT())); #endif
return modified; @Override
} public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) {
boolean modified = false;
#if !TYPE_OBJECT for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();modified |= add(iter.NEXT()));
/** {@inheritDoc} return modified;
* <p>This default implementation delegates to the corresponding type-specific function. }
* @deprecated Please use the corresponding type-specific function instead.
*/ @Override
@Override public COLLECTION KEY_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); }
@Deprecated
public boolean contains(Object e) { return COLLECTION.super.contains(e); } #if !TYPE_OBJECT
/** {@inheritDoc}
/** * <p>This default implementation delegates to the corresponding type-specific function.
* A Type-Specific implementation of contains. This implementation iterates over the elements and returns true if the value match. * @deprecated Please use the corresponding type-specific function instead.
* @param e the element that should be searched for. */
* @return true if the value was found. @Override
*/ @Deprecated
@Override public boolean contains(Object e) { return COLLECTION.super.contains(e); }
public boolean contains(KEY_TYPE e) {
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { if(KEY_EQUALS(iter.NEXT(), e)) return true; } /**
return false; * A Type-Specific implementation of contains. This implementation iterates over the elements and returns true if the value match.
} * @param e the element that should be searched for.
* @return true if the value was found.
#endif */
@Override
/** {@inheritDoc} public boolean contains(KEY_TYPE e) {
* <p>This default implementation delegates to the corresponding type-specific function. for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { if(KEY_EQUALS(iter.NEXT(), e)) return true; }
* @deprecated Please use the corresponding type-specific function instead. return false;
*/ }
@Override
@Deprecated /** {@inheritDoc}
public boolean addAll(Collection<? extends CLASS_TYPE> c) * <p>This default implementation delegates to the corresponding type-specific function.
{ * @deprecated Please use the corresponding type-specific function instead.
return c instanceof COLLECTION ? addAll((COLLECTION KEY_GENERIC_TYPE)c) : super.addAll(c); */
} @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.
for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();) * @return true if all elements were found in the collection
if(!contains(iter.NEXT())) * @throws java.lang.NullPointerException if the collection is null
return false; */
return true; @Override
} public boolean containsAll(COLLECTION KEY_GENERIC_TYPE c) {
Objects.requireNonNull(c);
/** if(c.isEmpty()) return true;
* This implementation iterates over the elements of the collection and checks if they are stored in this collection for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();)
* @param c the elements that should be checked for if(!contains(iter.NEXT()))
* @return true if any element is in this collection return false;
* @deprecated if this is a primitive collection return true;
* @throws java.lang.NullPointerException if the collection is null }
*/
@Override @Override
@Primitive public boolean containsAll(Collection<?> c) {
public boolean containsAny(Collection<?> c) { Objects.requireNonNull(c);
Objects.requireNonNull(c); return c instanceof COLLECTION ? containsAll((COLLECTION KEY_GENERIC_TYPE)c) : super.containsAll(c);
for(Object e : c) }
if(contains(e))
return true; /**
return false; * This implementation iterates over the elements of the collection and checks if they are stored in this collection
} * @param c the elements that should be checked for
* @return true if any element is in this collection
/** * @throws java.lang.NullPointerException if the collection is null
* This implementation iterates over the elements of the collection and checks if they are stored in this collection. */
* @param c the elements that should be checked for @Override
* @return true if any element is in this collection @Primitive
* @throws java.lang.NullPointerException if the collection is null public boolean containsAny(Collection<?> c) {
*/ Objects.requireNonNull(c);
@Override if(c.isEmpty()) return false;
public boolean containsAny(COLLECTION KEY_GENERIC_TYPE c) { for(Object e : c)
Objects.requireNonNull(c); if(contains(e))
for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();) return true;
if(contains(iter.NEXT())) return false;
return true; }
return false;
} /**
* This implementation iterates over the elements of the collection and checks if they are stored in this collection.
#if !TYPE_OBJECT * @param c the elements that should be checked for
/** {@inheritDoc} * @return true if any element is in this collection
* <p>This default implementation delegates to the corresponding type-specific function. * @throws java.lang.NullPointerException if the collection is null
* @deprecated Please use the corresponding type-specific function instead. */
*/ @Override
@Override public boolean containsAny(COLLECTION KEY_GENERIC_TYPE c) {
@Deprecated Objects.requireNonNull(c);
public boolean remove(Object e) { return COLLECTION.super.remove(e); } if(c.isEmpty()) return false;
for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();)
/** if(contains(iter.NEXT()))
* 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. return true;
* It stops after finding the first element return false;
* @param e the element that is searched for }
* @return true if the element was found and removed.
*/ #if !TYPE_OBJECT
@Override /** {@inheritDoc}
public boolean REMOVE_KEY(KEY_TYPE e) { * <p>This default implementation delegates to the corresponding type-specific function.
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { * @deprecated Please use the corresponding type-specific function instead.
if(KEY_EQUALS(iter.NEXT(), e)) { */
iter.remove(); @Override
return true; @Deprecated
} public boolean remove(Object e) { return COLLECTION.super.remove(e); }
}
return false; /**
} * 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
#endif * @param e the element that is searched for
/** * @return true if the element was found and removed.
* 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 @Override
* @return true if the collection was modified. public boolean REMOVE_KEY(KEY_TYPE e) {
* @throws java.lang.NullPointerException if the collection is null for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
*/ if(KEY_EQUALS(iter.NEXT(), e)) {
@Override iter.remove();
public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) { return true;
Objects.requireNonNull(c); }
boolean modified = false; }
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { return false;
if(c.contains(iter.NEXT())) { }
iter.remove();
modified = true; #endif
} /**
} * A Type-Specific implementation of removeAll. This Implementation iterates over all elements and removes them as they were found in the other collection.
return modified; * @param c the elements that should be deleted
} * @return true if the collection was modified.
* @throws java.lang.NullPointerException if the collection is null
/** */
* A Type-Specific implementation of retainAll. This Implementation iterates over all elements and removes them as they were not found in the other collection. @Override
* @param c the elements that should be kept public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) {
* @return true if the collection was modified. Objects.requireNonNull(c);
* @throws java.lang.NullPointerException if the collection is null if(c.isEmpty()) return false;
*/ boolean modified = false;
@Override for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) { if(c.contains(iter.NEXT())) {
Objects.requireNonNull(c); iter.remove();
if(c.isEmpty()) { modified = true;
boolean modified = !isEmpty(); }
clear(); }
return modified; return modified;
} }
boolean modified = false;
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { @Override
if(!c.contains(iter.NEXT())) { public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) {
iter.remove(); Objects.requireNonNull(c);
modified = true; if(c.isEmpty()) return false;
} Objects.requireNonNull(r);
} boolean modified = false;
return modified; for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
} KEY_TYPE e = iter.NEXT();
if(c.contains(e)) {
#if !TYPE_OBJECT r.accept(e);
/** iter.remove();
* A Type-Specific implementation of toArray that links to {@link #TO_ARRAY(KEY_TYPE[])} with a newly created array. modified = true;
* @return an array containing all of the elements in this collection }
*/ }
@Override return modified;
public KEY_TYPE[] TO_ARRAY() { }
return TO_ARRAY(new KEY_TYPE[size()]);
} /**
* 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
* A Type-Specific implementation of toArray. This implementation iterates over all elements and unwraps them into primitive type. * @return true if the collection was modified.
* @param a array that the elements should be injected to. If null or to small a new array with the right size is created * @throws java.lang.NullPointerException if the collection is null
* @return an array containing all of the elements in this collection */
*/ @Override
@Override public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) {
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) { Objects.requireNonNull(c);
if(a == null || a.length < size()) a = new KEY_TYPE[size()]; if(c.isEmpty()) {
ITERATORS.unwrap(a, iterator()); boolean modified = !isEmpty();
return a; clear();
} return modified;
#endif }
boolean modified = false;
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
if(!c.contains(iter.NEXT())) {
iter.remove();
modified = true;
}
}
return modified;
}
@Override
public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) {
Objects.requireNonNull(c);
Objects.requireNonNull(r);
if(c.isEmpty()) {
boolean modified = !isEmpty();
forEach(r);
clear();
return modified;
}
boolean modified = false;
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
KEY_TYPE e = iter.NEXT();
if(!c.contains(e)) {
r.accept(e);
iter.remove();
modified = true;
}
}
return modified;
}
#if !TYPE_OBJECT
/**
* A Type-Specific implementation of toArray that links to {@link #TO_ARRAY(KEY_TYPE[])} with a newly created array.
* @return an array containing all of the elements in this collection
*/
@Override
public KEY_TYPE[] TO_ARRAY() {
if(isEmpty()) return ARRAYS.EMPTY_ARRAY;
return TO_ARRAY(new KEY_TYPE[size()]);
}
/**
* A Type-Specific implementation of toArray. This implementation iterates over all elements and unwraps them into primitive type.
* @param a array that the elements should be injected to. If null or to small a new array with the right size is created
* @return an array containing all of the elements in this collection
*/
@Override
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) {
if(a == null || a.length < size()) a = new KEY_TYPE[size()];
ITERATORS.unwrap(a, iterator());
if (a.length > size()) a[size()] = EMPTY_KEY_VALUE;
return a;
}
#endif
} }
@@ -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());
@@ -57,7 +49,7 @@ public interface BI_ITERATOR KEY_GENERIC_TYPE extends ITERATOR KEY_GENERIC_TYPE
public default int back(int amount) { public default int back(int amount) {
if(amount < 0) throw new IllegalStateException("Can't go forward"); if(amount < 0) throw new IllegalStateException("Can't go forward");
int i = 0; int i = 0;
for(;i<amount && hasPrevious();previous(),i++); for(;i<amount && hasPrevious();PREVIOUS(),i++);
return i; return i;
} }
} }
@@ -1,198 +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;
import java.util.stream.JAVA_STREAM; #if SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
import java.util.stream.StreamSupport; import java.util.stream.JAVA_STREAM;
#endif import java.util.stream.StreamSupport;
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS; #endif
#endif
#if TYPE_BYTE || TYPE_SHORT || TYPE_CHAR || TYPE_FLOAT #if TYPE_OBJECT
import speiger.src.collections.utils.SanityChecks; import java.util.function.Consumer;
import java.util.function.IntFunction;
#endif #else
/** import speiger.src.collections.PACKAGE.functions.CONSUMER;
* A Type-Specific {@link Collection} that reduces (un)boxing #endif
* @Type(T) #if SPLIT_ITERATOR_FEATURE
*/ import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
public interface COLLECTION KEY_GENERIC_TYPE extends Collection<CLASS_TYPE>, ITERABLE KEY_GENERIC_TYPE #endif
{ import speiger.src.collections.PACKAGE.utils.COLLECTIONS;
#if !TYPE_OBJECT import speiger.src.collections.utils.ISizeProvider;
/** import speiger.src.collections.utils.SanityChecks;
* A Type-Specific add function to reduce (un)boxing
* @param o the element that should be added /**
* @return true if the element was added to the collection * A Type-Specific {@link Collection} that reduces (un)boxing
*/ * @Type(T)
public boolean add(KEY_TYPE o); */
public interface COLLECTION KEY_GENERIC_TYPE extends Collection<CLASS_TYPE>, ITERABLE KEY_GENERIC_TYPE, ISizeProvider
#endif {
/** #if !TYPE_OBJECT
* A Type-Specific addAll function to reduce (un)boxing /**
* @param c the collection of elements that should be added * A Type-Specific add function to reduce (un)boxing
* @return true if elements were added into the collection * @param o the element that should be added
*/ * @return true if the element was added to the collection
public boolean addAll(COLLECTION KEY_GENERIC_TYPE c); */
public boolean add(KEY_TYPE o);
#if !TYPE_OBJECT
/** #endif
* A Type-Specific contains function to reduce (un)boxing /**
* @param o the element that is checked for * A Type-Specific addAll function to reduce (un)boxing
* @return true if the element is found in the collection * @param c the collection of elements that should be added
*/ * @return true if elements were added into the collection
public boolean contains(KEY_TYPE o); */
public boolean addAll(COLLECTION KEY_GENERIC_TYPE c);
#endif
/** /**
* A Type-Specific containsAll function to reduce (un)boxing * A Type-Specific Array based addAll method to reduce the amount of Wrapping
* @param c the collection of elements that should be tested for * @param e the elements that should be added
* @return true if all the element is found in the collection * @return if the collection was modified
*/ */
public boolean containsAll(COLLECTION KEY_GENERIC_TYPE c); public default boolean addAll(KEY_TYPE... e) { return addAll(e, 0, e.length); }
/** /**
* A Type-Specific containsAny function to reduce (un)boxing * A Type-Specific Array based addAll method to reduce the amount of Wrapping
* @param c the collection of elements that should be tested for * @param e the elements that should be added
* @return true if any element was found * @param length how many elements of the array should be added
*/ * @return if the collection was modified
public boolean containsAny(COLLECTION KEY_GENERIC_TYPE c); */
public default boolean addAll(KEY_TYPE[] e, int length) { return addAll(e, 0, length); }
/**
* 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 Type-Specific Array based addAll method to reduce the amount of Wrapping
* @param c the collection of elements that should be tested for * @param e the elements that should be added
* @return true if any element was found. * @param offset where to start within the array
*/ * @param length how many elements of the array should be added
@Primitive * @return if the collection was modified
public boolean containsAny(Collection<?> c); */
public default boolean addAll(KEY_TYPE[] e, int offset, int length) {
#if !TYPE_OBJECT if(length <= 0) return false;
/** SanityChecks.checkArrayCapacity(e.length, offset, length);
* A Type-Specific remove function that reduces (un)boxing. boolean added = false;
* @param o the element that should be removed for(int i = 0;i<length;i++) {
* @return true if the element was removed if(add(e[offset+i])) added = true;
* @see Collection#remove(Object) }
*/ return added;
public boolean REMOVE_KEY(KEY_TYPE o); }
#endif #if !TYPE_OBJECT
/** /**
* A Type-Specific removeAll function that reduces (un)boxing. * A Type-Specific contains function to reduce (un)boxing
* @param c the collection of elements that should be removed * @param o the element that is checked for
* @return true if any element was removed * @return true if the element is found in the collection
* @see Collection#removeAll(Collection) */
*/ public boolean contains(KEY_TYPE o);
public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c);
#endif
/** /**
* A Type-Specific retainAll function that reduces (un)boxing. * A Type-Specific containsAll function to reduce (un)boxing
* @param c the collection of elements that should be kept * @param c the collection of elements that should be tested for
* @return true if any element was removed * @return true if all the element is found in the collection
* @see Collection#retainAll(Collection) */
*/ public boolean containsAll(COLLECTION KEY_GENERIC_TYPE c);
public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c);
/**
#if !TYPE_OBJECT * A Type-Specific containsAny function to reduce (un)boxing
/** * @param c the collection of elements that should be tested for
* A Type-Specific toArray function that delegates to {@link #TO_ARRAY(KEY_TYPE[])} with a newly created array. * @return true if any element was found
* @return an array containing all of the elements in this collection */
* @see Collection#toArray() public boolean containsAny(COLLECTION KEY_GENERIC_TYPE c);
*/
public KEY_TYPE[] TO_ARRAY(); /**
* 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 Type-Specific toArray function that reduces (un)boxing. * @param c the collection of elements that should be tested for
* @param a array that the elements should be injected to. If null or to small a new array with the right size is created * @return true if any element was found.
* @return an array containing all of the elements in this collection */
* @see Collection#toArray(Object[]) @Primitive
*/ public boolean containsAny(Collection<?> c);
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a);
#if !TYPE_OBJECT
#if PRIMITIVES /**
/** {@inheritDoc} * A Type-Specific remove function that reduces (un)boxing.
* <p>This default implementation delegates to the corresponding type-specific function. * @param o the element that should be removed
* @deprecated Please use the corresponding type-specific function instead. * @return true if the element was removed
*/ * @see Collection#remove(Object)
@Override */
@Deprecated public boolean REMOVE_KEY(KEY_TYPE o);
public default boolean removeIf(Predicate<? super CLASS_TYPE> filter) {
Objects.requireNonNull(filter); #endif
#if TYPE_BYTE || TYPE_SHORT || TYPE_CHAR || TYPE_FLOAT /**
return remIf(v -> filter.test(KEY_TO_OBJ(SanityChecks.SANITY_CAST(v)))); * A Type-Specific removeAll function that reduces (un)boxing.
#else * @param c the collection of elements that should be removed
return remIf(v -> filter.test(KEY_TO_OBJ(v))); * @return true if any element was removed
#endif * @see Collection#removeAll(Collection)
} */
public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c);
/**
* A Type-Specific removeIf function to reduce (un)boxing. /**
* <p>Removes elements that were selected by the filter * A Type-Specific removeAll function that reduces (un)boxing.
* @see Collection#removeIf(Predicate) * It also notifies the remover of which exact element is going to be removed.
* @param filter Filters the elements that should be removed * @param c the collection of elements that should be removed
* @return true if the collection was modified * @param r elements that got removed
* @throws java.lang.NullPointerException if filter is null * @return true if any element was removed
*/ * @see Collection#removeAll(Collection)
public default boolean remIf(JAVA_PREDICATE filter) { */
Objects.requireNonNull(filter); public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r);
boolean removed = false;
final ITERATOR each = iterator(); /**
while (each.hasNext()) { * A Type-Specific retainAll function that reduces (un)boxing.
if (filter.test(each.NEXT())) { * @param c the collection of elements that should be kept
each.remove(); * @return true if any element was removed
removed = true; * @see Collection#retainAll(Collection)
} */
} public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c);
return removed;
} /**
* A Type-Specific retainAll function that reduces (un)boxing.
#endif * It also notifies the remover of which exact element is going to be removed.
/** {@inheritDoc} * @param c the collection of elements that should be kept
* <p>This default implementation delegates to the corresponding type-specific function. * @param r elements that got removed
* @deprecated Please use the corresponding type-specific function instead. * @return true if any element was removed
*/ * @see Collection#retainAll(Collection)
@Override */
@Deprecated public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r);
public default boolean add(CLASS_TYPE o) { return add(OBJ_TO_KEY(o)); }
/**
/** {@inheritDoc} * A Helper function to reduce the usage of Streams and allows to collect all elements
* <p>This default implementation delegates to the corresponding type-specific function. * @param collection that the elements should be inserted to
* @deprecated Please use the corresponding type-specific function instead. * @param <E> the collection type
*/ * @return the input with the desired elements
@Override */
@Deprecated default <E extends COLLECTION KEY_GENERIC_TYPE> E pour(E collection) {
public default boolean contains(Object o) { return o != null && contains(CLASS_TO_KEY(o)); } collection.addAll(this);
return collection;
/** {@inheritDoc} }
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead. /**
*/ * A Function that does a shallow clone of the Collection itself.
@Override * This function is more optimized then a copy constructor since the Collection does not have to be unsorted/resorted.
@Deprecated * It can be compared to Cloneable but with less exception risk
public default boolean remove(Object o) { return o != null && REMOVE_KEY(CLASS_TO_KEY(o)); } * @return a Shallow Copy of the collection
* @note Wrappers and view collections will not support this feature
#endif */
/** public COLLECTION KEY_GENERIC_TYPE copy();
* Returns a Type-Specific Iterator to reduce (un)boxing
* @return a iterator of the collection #if TYPE_OBJECT
* @see Collection#iterator() /**
*/ * A Helper function that simplifies the process of creating a new Array.
@Override * @param action the array creation function
public ITERATOR KEY_GENERIC_TYPE iterator(); * @param <E> the returning arrayType
* @return an array containing all of the elements in this collection
#if PRIMITIVES * @see Collection#toArray(Object[])
/** */
* Returns a Java-Type-Specific Stream to reduce boxing/unboxing. default <E> E[] TO_ARRAY(IntFunction<E[]> action) {
* @return a Stream of the closest java type return TO_ARRAY(action.apply(size()));
*/ }
default JAVA_STREAM primitiveStream() { return StreamSupport.NEW_STREAM(SPLIT_ITERATORS.createJavaSplititerator(this, 0), false); }
#else
#endif /**
/** * A Type-Specific toArray function that delegates to {@link #TO_ARRAY(KEY_TYPE[])} with a newly created array.
* A Type Specific Type Splititerator to reduce boxing/unboxing * @return an array containing all of the elements in this collection
* @return type specific splititerator * @see Collection#toArray()
*/ */
@Override public KEY_TYPE[] TO_ARRAY();
default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createSplititerator(this, 0); }
/**
* A Type-Specific toArray function that reduces (un)boxing.
* @param a array that the elements should be injected to. If null or to small a new array with the right size is created
* @return an array containing all of the elements in this collection
* @see Collection#toArray(Object[])
*/
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a);
#if PRIMITIVES
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public default boolean removeIf(Predicate<? super CLASS_TYPE> filter) {
Objects.requireNonNull(filter);
#if TYPE_BYTE || TYPE_SHORT || TYPE_CHAR || TYPE_FLOAT
return remIf(v -> filter.test(KEY_TO_OBJ(SanityChecks.SANITY_CAST(v))));
#else
return remIf(v -> filter.test(KEY_TO_OBJ(v)));
#endif
}
/**
* A Type-Specific removeIf function to reduce (un)boxing.
* <p>Removes elements that were selected by the filter
* @see Collection#removeIf(Predicate)
* @param filter Filters the elements that should be removed
* @return true if the collection was modified
* @throws java.lang.NullPointerException if filter is null
*/
public default boolean remIf(JAVA_PREDICATE filter) {
Objects.requireNonNull(filter);
boolean removed = false;
final ITERATOR each = iterator();
while (each.hasNext()) {
if (filter.test(each.NEXT())) {
each.remove();
removed = true;
}
}
return removed;
}
#endif
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public default boolean add(CLASS_TYPE o) { return add(OBJ_TO_KEY(o)); }
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public default boolean contains(Object o) { return o != null && contains(CLASS_TO_KEY(o)); }
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public default boolean remove(Object o) { return o != null && REMOVE_KEY(CLASS_TO_KEY(o)); }
#endif
/**
* Returns a Type-Specific Iterator to reduce (un)boxing
* @return a iterator of the collection
* @see Collection#iterator()
*/
@Override
public ITERATOR KEY_GENERIC_TYPE iterator();
/**
* Creates a Wrapped Collection that is Synchronized
* @return a new Collection that is synchronized
* @see COLLECTIONS#synchronize
*/
public default COLLECTION KEY_GENERIC_TYPE synchronize() { return COLLECTIONS.synchronize(this); }
/**
* Creates a Wrapped Collection that is Synchronized
* @param mutex is the controller of the synchronization block
* @return a new Collection Wrapper that is synchronized
* @see COLLECTIONS#synchronize
*/
public default COLLECTION KEY_GENERIC_TYPE synchronize(Object mutex) { return COLLECTIONS.synchronize(this, mutex); }
/**
* Creates a Wrapped Collection that is unmodifiable
* @return a new Collection Wrapper that is unmodifiable
* @see COLLECTIONS#unmodifiable
*/
public default COLLECTION KEY_GENERIC_TYPE unmodifiable() { return COLLECTIONS.unmodifiable(this); }
#if SPLIT_ITERATOR_FEATURE
#if PRIMITIVES
/**
* Returns a Java-Type-Specific Stream to reduce boxing/unboxing.
* @return a Stream of the closest java type
*/
default JAVA_STREAM primitiveStream() { return StreamSupport.NEW_STREAM(SPLIT_ITERATORS.createJavaSplititerator(this, 0), false); }
/**
* Returns a Java-Type-Specific Parallel Stream to reduce boxing/unboxing.
* @return a Stream of the closest java type
*/
default JAVA_STREAM parallelPrimitiveStream() { return StreamSupport.NEW_STREAM(SPLIT_ITERATORS.createJavaSplititerator(this, 0), true); }
#endif
#if STREAM_FEATURE
/**
* A Type Specific Type Splititerator to reduce boxing/unboxing
* @return type specific splititerator
*/
@Override
default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createSplititerator(this, 0); }
#endif
#endif
} }
@@ -1,63 +1,490 @@
package speiger.src.collections.PACKAGE.collections; package speiger.src.collections.PACKAGE.collections;
#if !TYPE_OBJECT import java.util.Objects;
import java.util.Objects; import java.util.function.Consumer;
import java.util.function.Consumer; #if JDK_FUNCTION
import java.util.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.CONSUMER; #endif
#endif
import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR; #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
/** import speiger.src.collections.PACKAGE.functions.COMPARATOR;
* A Type-Specific {@link Iterable} that reduces (un)boxing import speiger.src.collections.objects.collections.ObjectIterable;
* @Type(T) #else
*/ import java.util.function.BiFunction;
public interface ITERABLE KEY_GENERIC_TYPE extends Iterable<CLASS_TYPE> import java.util.function.IntFunction;
{ import java.util.Comparator;
/**
* Returns an iterator over elements of type {@code T}. #if BOOLEAN_COLLECTION_MODULE
* import speiger.src.collections.booleans.collections.BooleanIterable;
* @return an Iterator. #endif
*/ #iterate
@Override #argument OUTPUT_ITERABLE ByteIterable ShortIterable IntIterable LongIterable FloatIterable DoubleIterable
ITERATOR KEY_GENERIC_TYPE iterator(); #argument MAPPER ToByteFunction ToShortFunction ToIntFunction ToLongFunction ToFloatFunction ToDoubleFunction
#if !TYPE_OBJECT #argument PACKAGE bytes shorts ints longs floats doubles
#argument FILTER_TYPE BYTE_COLLECTION_MODULE SHORT_COLLECTION_MODULE INT_COLLECTION_MODULE LONG_COLLECTION_MODULE FLOAT_COLLECTION_MODULE DOUBLE_COLLECTION_MODULE
/** #if FILTER_TYPE
* A Type Specific foreach function that reduces (un)boxing import speiger.src.collections.objects.functions.function.MAPPER;
* import speiger.src.collections.PACKAGE.collections.OUTPUT_ITERABLE;
* @implSpec #endif
* <p>The default implementation behaves as if: #enditerate
* <pre>{@code #endif
* iterator().forEachRemaining(action); import speiger.src.collections.PACKAGE.functions.function.TO_OBJECT_FUNCTION;
* }</pre> import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER;
* import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
* @param action The action to be performed for each element #if !JDK_FUNCTION
* @throws NullPointerException if the specified action is null import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
* @see Iterable#forEach(Consumer) #endif
*/ import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
default void forEach(CONSUMER action) { #if ARRAY_LIST_FEATURE || LINKED_LIST_FEATURE
Objects.requireNonNull(action); import speiger.src.collections.PACKAGE.lists.LIST;
iterator().forEachRemaining(action); #if ARRAY_LIST_FEATURE
} import speiger.src.collections.PACKAGE.lists.ARRAY_LIST;
#else
/** {@inheritDoc} import speiger.src.collections.PACKAGE.lists.LINKED_LIST;
* <p>This default implementation delegates to the corresponding type-specific function. #endif
* @deprecated Please use the corresponding type-specific function instead. #endif
*/ #if SET_MODULE && !TYPE_BOOLEAN
@Deprecated #if LINKED_SET_FEATURE || LINKED_CUSTOM_SET_FEATURE || SET_FEATURE || CUSTOM_SET_FEATURE || RB_TREE_SET_FEATURE || AVL_TREE_SET_FEATURE || ARRAY_SET_FEATURE
@Override import speiger.src.collections.PACKAGE.sets.SET;
default void forEach(Consumer<? super CLASS_TYPE> action) { #if LINKED_SET_FEATURE
Objects.requireNonNull(action); import speiger.src.collections.PACKAGE.sets.LINKED_HASH_SET;
iterator().forEachRemaining(action); #else if LINKED_CUSTOM_SET_FEATURE
} import speiger.src.collections.PACKAGE.sets.LINKED_CUSTOM_HASH_SET;
#endif #else if SET_FEATURE
import speiger.src.collections.PACKAGE.sets.HASH_SET;
/** #else if CUSTOM_SET_FEATURE
* A Type Specific Type Splititerator to reduce boxing/unboxing import speiger.src.collections.PACKAGE.sets.CUSTOM_HASH_SET;
* @return type specific splititerator #else if RB_TREE_SET_FEATURE
*/ import speiger.src.collections.PACKAGE.sets.RB_TREE_SET;
@Override #else if AVL_TREE_SET_FEATURE
default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createUnknownSplititerator(iterator(), 0); } import speiger.src.collections.PACKAGE.sets.AVL_TREE_SET;
#else if ARRAY_SET_FEATURE
import speiger.src.collections.PACKAGE.sets.ARRAY_SET;
#endif
#endif
#endif
import speiger.src.collections.PACKAGE.utils.ARRAYS;
#if ASYNC_MODULE
import speiger.src.collections.PACKAGE.utils.ASYNC_BUILDER;
#endif
#if SPLIT_ITERATOR_FEATURE
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
#endif
import speiger.src.collections.PACKAGE.utils.ITERABLES;
import speiger.src.collections.PACKAGE.utils.ITERATORS;
#if !LINKED_HASH_SET_FEATURE && LINKED_CUSTOM_HASH_SET_FEATURE
import speiger.src.collections.PACKAGE.utils.STRATEGY;
#endif
import speiger.src.collections.utils.ISizeProvider;
/**
* A Type-Specific {@link Iterable} that reduces (un)boxing
* @Type(T)
*/
public interface ITERABLE KEY_GENERIC_TYPE extends Iterable<CLASS_TYPE>
{
/**
* Returns an iterator over elements of type {@code T}.
*
* @return an Iterator.
*/
@Override
ITERATOR KEY_GENERIC_TYPE iterator();
#if !TYPE_OBJECT
/**
* A Type Specific foreach function that reduces (un)boxing
*
* @implSpec
* <p>The default implementation behaves as if:
* <pre>{@code
* iterator().forEachRemaining(action);
* }</pre>
*
* @param action The action to be performed for each element
* @throws NullPointerException if the specified action is null
* @see Iterable#forEach(Consumer)
*/
default void forEach(CONSUMER action) {
Objects.requireNonNull(action);
iterator().forEachRemaining(action);
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Deprecated
@Override
default void forEach(Consumer<? super CLASS_TYPE> action) {
Objects.requireNonNull(action);
iterator().forEachRemaining(action);
}
#endif
/**
* A Indexed forEach implementation that allows you to keep track of how many elements were already iterated over.
* @param action The action to be performed for each element
* @throws java.lang.NullPointerException if the specified action is null
*/
public default void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) {
Objects.requireNonNull(action);
int index = 0;
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();action.accept(index++, iter.NEXT()));
}
/**
* Helper function to reduce Lambda usage and allow for more method references, since these are faster/cleaner.
* @param input the object that should be included
* @param action The action to be performed for each element
* @param <E> the generic type of the Object
* @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) {
Objects.requireNonNull(action);
iterator().forEachRemaining(input, action);
}
#if SPLIT_ITERATOR_FEATURE
/**
* A Type Specific Type Splititerator to reduce boxing/unboxing
* @return type specific splititerator
*/
@Override
default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createUnknownSplititerator(iterator(), 0); }
#endif
#if ASYNC_MODULE
/**
* Creates a Async Builder for moving work of the thread.
* It is not designed to split the work to multithreaded work, so using this keep it singlethreaded, but it allows to be moved to another thread.
* @see ASYNC_BUILDER
* @return a AsyncBuilder
*/
default ASYNC_BUILDER KEY_GENERIC_TYPE asAsync() {
return new ASYNC_BUILDERBRACES(this);
}
#endif
/**
* A Helper function to reduce the usage of Streams and allows to convert a Iterable to something else.
* @param mapper the mapping function
* @param <E> The return type.
* @return a new Iterable that returns the desired result
*/
default <E> ObjectIterable<E> map(TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<E> mapper) {
return ITERABLES.map(this, mapper);
}
#if TYPE_OBJECT
#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
#argument FILTER_TYPE BOOLEAN_COLLECTION_MODULE BYTE_COLLECTION_MODULE SHORT_COLLECTION_MODULE INT_COLLECTION_MODULE LONG_COLLECTION_MODULE FLOAT_COLLECTION_MODULE DOUBLE_COLLECTION_MODULE
#if FILTER_TYPE
/**
* A Helper function to reduce the usage of Streams and allows to convert a Iterable to something else.
* @param mapper the mapping function
* @return a new Iterable that returns the desired result
*/
default OUTPUT_ITERABLE mapToDATA_TYPE(MAPPER<T> mapper) {
return ITERABLES.mapToDATA_TYPE(this, mapper);
}
#endif
#enditerate
#endif
/**
* 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.
* @return a new Iterable that returns the desired result
* @note does not support TO_ARRAY optimizations.
*/
default <E, V extends Iterable<E>> ObjectIterable<E> flatMap(TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<V> mapper) {
return ITERABLES.flatMap(this, mapper);
}
/**
* A Helper function to reduce the usage of Streams and allows to convert a Iterable to something else.
* @param mapper the flatMapping function
* @param <E> The return type.
* @return a new Iterable that returns the desired result
* @note does not support TO_ARRAY optimizations.
*/
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 filter out unwanted elements
* @param filter the elements that should be kept.
* @return a Iterable that filtered out all unwanted elements
* @note does not support TO_ARRAY optimizations.
*/
default ITERABLE KEY_GENERIC_TYPE filter(PREDICATE KEY_GENERIC_TYPE filter) {
return ITERABLES.filter(this, filter);
}
/**
* A Helper function to reduce the usage of Streams and allows to filter out duplicated elements
* @return a Iterable that filtered out all duplicated elements
* @note does not support TO_ARRAY optimizations.
*/
default ITERABLE KEY_GENERIC_TYPE distinct() {
return ITERABLES.distinct(this);
}
/**
* A Helper function to reduce the usage of Streams and allows to repeat elements a desired amount of times
* @param repeats how many times the elements should be repeated
* @return a Iterable that is repeating multiple times
*/
default ITERABLE KEY_GENERIC_TYPE repeat(int repeats) {
return ITERABLES.repeat(this, repeats);
}
/**
* A Helper function to reduce the usage of Streams and allows to limit the amount of elements
* @param limit the amount of elements it should be limited to
* @return a Iterable that is limited in length
*/
default ITERABLE KEY_GENERIC_TYPE limit(long limit) {
return ITERABLES.limit(this, limit);
}
/**
* A Helper function to reduce the usage of Streams and allows to sort the elements
* @param sorter that sorts the elements.
* @return a Iterable that is sorted
*/
default ITERABLE KEY_GENERIC_TYPE sorted(COMPARATOR KEY_GENERIC_TYPE sorter) {
return ITERABLES.sorted(this, sorter);
}
/**
* A Helper function to reduce the usage of Streams and allows to preview elements before they are iterated through
* @param action the action that should be applied
* @return a Peeked Iterable
*/
default ITERABLE KEY_GENERIC_TYPE peek(CONSUMER KEY_GENERIC_TYPE action) {
return ITERABLES.peek(this, action);
}
/**
* A Helper function to reduce the usage of Streams and allows to collect all elements
* @param collection that the elements should be inserted to
* @param <E> the collection type
* @return the input with the desired elements
*/
default <E extends COLLECTION KEY_GENERIC_TYPE> E pour(E collection) {
ITERATORS.pour(iterator(), collection);
return collection;
}
#if ARRAY_LIST_FEATURE || LINKED_LIST_FEATURE
/**
* A Helper function that reduces the usage of streams and allows to collect all elements as a ArrayList
* @return a new ArrayList of all elements
*/
default LIST KEY_GENERIC_TYPE pourAsList() {
#if ARRAY_LIST_FEATURE
return pour(new ARRAY_LISTBRACES());
#else
return pour(new LINKED_LISTBRACES());
#endif
}
#endif
#if !TYPE_BOOLEAN && SET_MODULE
#if LINKED_SET_FEATURE || LINKED_CUSTOM_SET_FEATURE || SET_FEATURE || CUSTOM_SET_FEATURE || RB_TREE_SET_FEATURE || AVL_TREE_SET_FEATURE || ARRAY_SET_FEATURE
/**
* A Helper function that reduces the usage of streams and allows to collect all elements as a LinkedHashSet
* @return a new LinkedHashSet of all elements
*/
default SET KEY_GENERIC_TYPE pourAsSet() {
#if LINKED_SET_FEATURE
return pour(new LINKED_HASH_SETBRACES());
#else if LINKED_CUSTOM_SET_FEATURE
return pour(new LINKED_CUSTOM_HASH_SETBRACES(STRATEGY.normalStrategy()));
#else if SET_FEATURE
return pour(new HASH_SETBRACES());
#else if CUSTOM_SET_FEATURE
return pour(new CUSTOM_HASH_SETBRACES(STRATEGY.normalStrategy()));
#else if RB_TREE_SET_FEATURE
return pour(new RB_Tree_SETBRACES());
#else if AVL_TREE_SET_FEATURE
return pour(new AVL_Tree_SETBRACES());
#else if ARRAY_SET_FEATURE
return pour(new ARRAY_SETBRACES());
#endif
}
#endif
#endif
#if TYPE_OBJECT
/**
* A Helper function that reduces the usage of streams and allows to collect all elements as a Array
* @param action is the creator function of said Array to ensure type is kept.
* @param <E> the returning arrayType
* @return a new Array of all elements
*/
default <E> E[] TO_ARRAY(IntFunction<E[]> action) {
ISizeProvider prov = ISizeProvider.of(this);
if(prov != null) {
int size = prov.size();
if(size >= 0) {
E[] array = action.apply(size);
ITERATORS.unwrap(array, iterator());
return array;
}
}
return ARRAYS.pour(iterator(), action);
}
#else
/**
* A Helper function that reduces the usage of streams and allows to collect all elements as a Array
* @return a new Array of all elements
*/
default KEY_TYPE[] TO_ARRAY() {
ISizeProvider prov = ISizeProvider.of(this);
if(prov != null) {
int size = prov.size();
if(size >= 0) {
KEY_TYPE[] array = NEW_KEY_ARRAY(size);
ITERATORS.unwrap(array, iterator());
return array;
}
}
return ARRAYS.pour(iterator());
}
#endif
/**
* Helper function to reduce stream usage that allows to filter for any matches.
* @param filter that should be applied
* @return true if any matches were found
*/
default boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
if(filter.test(iter.NEXT())) return true;
}
return false;
}
/**
* Helper function to reduce stream usage that allows to filter for no matches.
* @param filter that should be applied
* @return true if no matches were found
*/
default boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
if(filter.test(iter.NEXT())) return false;
}
return true;
}
/**
* Helper function to reduce stream usage that allows to filter for all matches.
* @param filter that should be applied
* @return true if all matches.
*/
default boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
if(!filter.test(iter.NEXT())) return false;
}
return true;
}
/**
* Helper function to reduce stream usage that allows to filter for the first match.
* @param filter that should be applied
* @return the found value or the null equivalent variant.
*/
default KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
KEY_TYPE entry = iter.NEXT();
if(filter.test(entry)) return entry;
}
return EMPTY_VALUE;
}
#if !TYPE_OBJECT
/**
* Performs a <a href="package-summary.html#Reduction">reduction</a> on the
* elements of this Iterable
* @param operator the operation that should be applied
* @param identity the start value
* @return the reduction result, returns identity if nothing was found
*/
default KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
state = operator.APPLY_VALUE(state, iter.NEXT());
}
return state;
}
#else
/**
* Performs a <a href="package-summary.html#Reduction">reduction</a> on the
* elements of this Iterable
* @param operator the operation that should be applied
* @param identity the start value
* @Type(E)
* @return the reduction result, returns identity if nothing was found
*/
default <KEY_SPECIAL_TYPE> 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;
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 KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_VALUE;
boolean empty = true;
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
if(empty) {
empty = false;
state = iter.NEXT();
continue;
}
state = operator.APPLY_VALUE(state, iter.NEXT());
}
return state;
}
/**
* Helper function to reduce stream usage that allows to count the valid elements.
* @param filter that should be applied
* @return the amount of Valid Elements
*/
default int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int result = 0;
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
if(filter.test(iter.NEXT())) result++;
}
return result;
}
} }
@@ -1,13 +1,14 @@
package speiger.src.collections.PACKAGE.collections; package speiger.src.collections.PACKAGE.collections;
import java.util.Iterator; import java.util.Iterator;
#if !TYPE_OBJECT
import java.util.Objects; import java.util.Objects;
#if !TYPE_OBJECT
import java.util.function.Consumer; import java.util.function.Consumer;
import speiger.src.collections.PACKAGE.functions.CONSUMER; import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif #endif
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
/** /**
* A Type-Specific {@link Iterator} that reduces (un)boxing * A Type-Specific {@link Iterator} that reduces (un)boxing
@@ -33,25 +34,25 @@ public interface ITERATOR KEY_GENERIC_TYPE extends Iterator<CLASS_TYPE>
@Deprecated @Deprecated
public default CLASS_TYPE next() { return KEY_TO_OBJ(NEXT()); } public default CLASS_TYPE next() { return KEY_TO_OBJ(NEXT()); }
/** /**
* Performs the given action for each remaining element until all elements * Performs the given action for each remaining element until all elements
* have been processed or the action throws an exception. Actions are * have been processed or the action throws an exception. Actions are
* performed in the order of iteration, if that order is specified. * performed in the order of iteration, if that order is specified.
* Exceptions thrown by the action are relayed to the caller. * Exceptions thrown by the action are relayed to the caller.
* *
* @implSpec * @implSpec
* <p>The default implementation behaves as if: * <p>The default implementation behaves as if:
* <pre>{@code * <pre>{@code
* while (hasNext()) action.accept(NEXT()); * while (hasNext()) action.accept(NEXT());
* }</pre> * }</pre>
* *
* @param action The action to be performed for each element * @param action The action to be performed for each element
* @throws java.lang.NullPointerException if the specified action is null * @throws java.lang.NullPointerException if the specified action is null
* @see Iterator#forEachRemaining(Consumer) * @see Iterator#forEachRemaining(Consumer)
*/ */
public default void forEachRemaining(CONSUMER action) { public default void forEachRemaining(CONSUMER action) {
Objects.requireNonNull(action); Objects.requireNonNull(action);
while(hasNext()) { action.accept(NEXT()); } while(hasNext()) { action.accept(NEXT()); }
} }
/** {@inheritDoc} /** {@inheritDoc}
@@ -61,11 +62,23 @@ public interface ITERATOR KEY_GENERIC_TYPE extends Iterator<CLASS_TYPE>
@Deprecated @Deprecated
@Override @Override
default void forEachRemaining(Consumer<? super CLASS_TYPE> action) { default void forEachRemaining(Consumer<? super CLASS_TYPE> action) {
Objects.requireNonNull(action); Objects.requireNonNull(action);
forEachRemaining(action::accept); forEachRemaining(action::accept);
} }
#endif #endif
/**
* Helper function to reduce Lambda usage and allow for more method references, since these are faster/cleaner.
* @param input the object that should be included
* @param action The action to be performed for each element
* @param <E> the generic type of the Object
* @throws java.lang.NullPointerException if the specified action is null
*/
default <E> void forEachRemaining(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
while(hasNext()) { action.accept(input, NEXT()); }
}
/** /**
* Skips the Given amount of elements if possible. A Optimization function to skip elements faster if the implementation allows it. * Skips the Given amount of elements if possible. A Optimization function to skip elements faster if the implementation allows it.
* @param amount the amount of elements that should be skipped * @param amount the amount of elements that should be skipped
@@ -1,18 +1,28 @@
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;
/** /**
* A Type-Specific {@link Stack} that reduces (un)boxing * A Type-Specific {@link Stack} that reduces (un)boxing
*/ */
public interface STACK extends Stack<CLASS_TYPE> public interface STACK
{ {
/** /**
* Inserts a given Object on top of the stack * Inserts a given Object on top of the stack
* @param e the Object to insert * @param e the Object to insert
* @see Stack#push(Object) * @see Stack#push(Object)
*/ */
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.
@@ -20,7 +30,7 @@ public interface STACK extends Stack<CLASS_TYPE>
* @throws ArrayIndexOutOfBoundsException if the stack is empty * @throws ArrayIndexOutOfBoundsException if the stack is empty
* @see Stack#pop() * @see Stack#pop()
*/ */
public KEY_TYPE POP(); public KEY_TYPE pop();
/** /**
* Provides the Object on top of the stack * Provides the Object on top of the stack
@@ -28,8 +38,8 @@ public interface STACK extends Stack<CLASS_TYPE>
* @throws ArrayIndexOutOfBoundsException if the stack is empty * @throws ArrayIndexOutOfBoundsException if the stack is empty
* @see Stack#top() * @see Stack#top()
*/ */
public default KEY_TYPE TOP() { public default KEY_TYPE top() {
return PEEK(0); return peek(0);
} }
/** /**
@@ -40,41 +50,38 @@ public interface STACK extends Stack<CLASS_TYPE>
* @throws ArrayIndexOutOfBoundsException if the index is out of bounds * @throws ArrayIndexOutOfBoundsException if the index is out of bounds
* @see Stack#peek(int) * @see Stack#peek(int)
*/ */
public KEY_TYPE PEEK(int index); public KEY_TYPE peek(int index);
#if !OBJECT_TYPE /**
/** {@inheritDoc} * Clears the stack
* <p>This default implementation delegates to the corresponding type-specific function. */
* @deprecated Please use the corresponding type-specific function instead. public void clear();
*/
@Override
@Deprecated
public default void push(CLASS_TYPE e) { PUSH(OBJ_TO_KEY(e)); }
/** {@inheritDoc} /**
* <p>This default implementation delegates to the corresponding type-specific function. * Provides the amount of elements currently in the stack
* @deprecated Please use the corresponding type-specific function instead. * @return amount of elements in the list
*/ */
@Override public int size();
@Deprecated
public default CLASS_TYPE pop() { return KEY_TO_OBJ(POP()); }
/** {@inheritDoc} /**
* <p>This default implementation delegates to the corresponding type-specific function. * @return if the stack is empty
* @deprecated Please use the corresponding type-specific function instead. */
*/ public default boolean isEmpty() {
@Override return size() == 0;
@Deprecated
public default CLASS_TYPE top() {
return peek(size() - 1);
} }
/** {@inheritDoc} /**
* <p>This default implementation delegates to the corresponding type-specific function. * A method to drop the contents of the Stack without clearing the stack
* @deprecated Please use the corresponding type-specific function instead. * @Type(E)
*/ * @return the contents of the stack into a seperate array.
@Override */
@Deprecated public default GENERIC_SPECIAL_KEY_BRACES<E> KEY_SPECIAL_TYPE[] TO_ARRAY() { return TO_ARRAY(NEW_SPECIAL_KEY_ARRAY(size())); }
public default CLASS_TYPE peek(int index) { return KEY_TO_OBJ(PEEK(index)); } /**
#endif * 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,66 +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;
public Reversed(COMPARATOR original) { /**
this.original = original; * default constructor
} * @param original that is going to be reversed
*/
public int compare(KEY_TYPE o1, KEY_TYPE o2) { public Reversed(COMPARATOR original) {
return original.compare(o2, o1); this.original = original;
} }
@Override public int compare(KEY_TYPE o1, KEY_TYPE o2) {
public COMPARATOR reversed() { return original.compare(o2, o1);
return original; }
}
} @Override
public COMPARATOR reversed() {
return original;
}
}
} }
@@ -12,12 +12,12 @@ public interface CONSUMER extends Consumer<CLASS_TYPE>, JAVA_CONSUMER
public interface CONSUMER extends Consumer<CLASS_TYPE> public interface CONSUMER extends Consumer<CLASS_TYPE>
#endif #endif
{ {
/** /**
* Type-Specific function to reduce (un)boxing. * Type-Specific function to reduce (un)boxing.
* Performs this operation on the given argument. * Performs this operation on the given argument.
* *
* @param t the input argument * @param t the input argument
*/ */
void accept(KEY_TYPE t); void accept(KEY_TYPE t);
/** /**
@@ -0,0 +1,19 @@
package speiger.src.collections.PACKAGE.functions;
/**
* Type-Specific Supplier interface that reduces (un)boxing and allows to merge other consumer types into this interface
* @Type(T)
*/
#if TYPE_OBJECT
public interface SUPPLIER KEY_GENERIC_TYPE extends java.util.function.Supplier<KEY_TYPE>
#else if JDK_TYPE && !TYPE_BOOLEAN
public interface SUPPLIER KEY_GENERIC_TYPE extends JAVA_SUPPLIER
#else
public interface SUPPLIER KEY_GENERIC_TYPE
#endif
{
/**
* @return the supplied value
*/
public KEY_TYPE SUPPLY_GET();
}
@@ -0,0 +1,92 @@
package speiger.src.collections.PACKAGE.functions;
import java.util.concurrent.RunnableFuture;
#if !TYPE_OBJECT
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
#endif
/**
*
* A Type Specific Task interface that allows you to keep track of the task that is currently running.<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.
* - pause/resume: which allows to pause/resume the task at any moment, making it easier to create thread-safe actions.
* @Type(T)
*/
public interface TASK KEY_GENERIC_TYPE extends RunnableFuture<CLASS_TYPE> {
/**
* Helper function to detect if the task is currently paused.
* @return true if paused
*/
public boolean isPaused();
/**
* Pauses the task, which lets the thread finish without completing the task.
* Tasks are written in the way where they can pause without any issues.
* This won't be instant, as this function is applied asynchronous and doesn't check if the thread paused.
* So make sure it had the time to pause.
*/
public void pause();
/**
* Pauses the task, which lets the thread finish without completing the task.
* Tasks are written in the way where they can pause without any issues.
* This won't be instant, as this function is applied asynchronous.
* It will await the pausing of the task.
*/
public void awaitPausing();
/**
* Continues the task if it wasn't already completed.
* This is done by resubmitting the task to the executor provided.
*/
public void resume();
/**
* Quality of life function that allows to detect if no cancellation/exception was applied to this task and it completed on its own.
* @return true if it was properly completed
*/
public boolean isSuccessful();
#if !TYPE_OBJECT
/**
* A Type Specific get method that allows to reduce (un)boxing of primtives.
*
* Waits if necessary for the computation to complete, and then
* retrieves its result.
*
* @return the computed result as primitive
* @throws CancellationException if the computation was cancelled
* @throws ExecutionException if the computation threw an exception
* @throws InterruptedException if the current thread was interrupted
* while waiting
*/
public KEY_TYPE GET_KEY() throws InterruptedException, ExecutionException;
/**
* Waits if necessary for at most the given time for the computation
* to complete, and then retrieves its result, if available.
*
* @param timeout the maximum time to wait
* @param unit the time unit of the timeout argument
* @return the computed result as primitive
* @throws CancellationException if the computation was cancelled
* @throws ExecutionException if the computation threw an exception
* @throws InterruptedException if the current thread was interrupted while waiting
* @throws TimeoutException if the wait timed out
*/
public KEY_TYPE GET_KEY(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
@Override
@Deprecated
public default CLASS_TYPE get() throws InterruptedException, ExecutionException { return KEY_TO_OBJ(GET_KEY()); }
@Override
@Deprecated
public default CLASS_TYPE get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return KEY_TO_OBJ(GET_KEY(timeout, unit)); }
#endif
}
@@ -10,13 +10,13 @@ import java.util.function.BiConsumer;
*/ */
public interface BI_CONSUMER KEY_VALUE_GENERIC_TYPE extends BiConsumer<CLASS_TYPE, CLASS_VALUE_TYPE> public interface BI_CONSUMER KEY_VALUE_GENERIC_TYPE extends BiConsumer<CLASS_TYPE, CLASS_VALUE_TYPE>
{ {
/** /**
* A Type Specific operation method to reduce boxing/unboxing * A Type Specific operation method to reduce boxing/unboxing
* Performs this operation on the given arguments. * Performs this operation on the given arguments.
* *
* @param k the first input argument * @param k the first input argument
* @param v the second input argument * @param v the second input argument
*/ */
void accept(KEY_TYPE k, VALUE_TYPE v); void accept(KEY_TYPE k, VALUE_TYPE v);
/** /**
@@ -1,79 +1,134 @@
package speiger.src.collections.PACKAGE.functions.function; package speiger.src.collections.PACKAGE.functions.function;
#if JDK_FUNCTION && VALUE_BOOLEAN #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 GET_VALUE(KEY_TYPE k); public VALUE_TYPE APPLY(KEY_TYPE k);
#if JDK_FUNCTION #if SAME_TYPE
#if VALUE_BOOLEAN /**
@Override * Creates a Default function that returns the input provided.
public default VALUE_TYPE test(KEY_TYPE k) { return GET_VALUE(k); } * @Type(T)
* @return a input returning function
/** */
* A Type specific and-function helper function that reduces boxing/unboxing public static GENERIC_KEY_BRACES FUNCTION KEY_SAME_GENERIC_TYPE identity() {
* @param other the other function that should be merged with. return T -> T;
* @return a function that compares values in a and comparason }
*/
public default FUNCTION KEY_VALUE_GENERIC_TYPE andType(FUNCTION KEY_VALUE_GENERIC_TYPE other) { /**
Objects.requireNonNull(other); * Returns a composed function that first applies the {@code before}
return T -> GET_VALUE(T) && other.GET_VALUE(T); * function to its input, and then applies this function to the result.
} * If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
@Override *
@Deprecated * @Type(I)
public default FUNCTION KEY_VALUE_GENERIC_TYPE and(JAVA_FUNCTION KEY_VALUE_SUPER_GENERIC_TYPE other) { * @param before the function that should be used first
Objects.requireNonNull(other); * @return a composed function with a different starting function.
return T -> GET_VALUE(T) && other.test(T); */
} public default GENERIC_SPECIAL_VALUE_BRACES<I> FUNCTION SV_GENERIC_TYPE<I> compose(FUNCTION SK_GENERIC_TYPE<I> before) {
Objects.requireNonNull(before);
@Override return T -> APPLY(before.APPLY(T));
public default FUNCTION KEY_VALUE_GENERIC_TYPE negate() { }
return T -> !GET_VALUE(T);
} /**
* Returns a composed function that first applies this function to
/** * its input, and then applies the {@code after} function to the result.
* A Type specific or-function helper function that reduces boxing/unboxing * If evaluation of either function throws an exception, it is relayed to
* @param other the other function that should be merged with. * the caller of the composed function.
* @return a function that compares values in a or comparason *
*/ * @Type(I)
public default FUNCTION KEY_VALUE_GENERIC_TYPE orType(FUNCTION KEY_VALUE_GENERIC_TYPE other) { * @param after the function that should be used last
Objects.requireNonNull(other); * @return a composed function with a different starting function.
return T -> GET_VALUE(T) || other.GET_VALUE(T); */
} public default GENERIC_SPECIAL_VALUE_BRACES<I> FUNCTION KS_GENERIC_TYPE<I> andThen(FUNCTION VS_GENERIC_TYPE<I> after) {
Objects.requireNonNull(after);
@Override return T -> after.APPLY(APPLY(T));
@Deprecated }
public default FUNCTION KEY_VALUE_GENERIC_TYPE or(JAVA_FUNCTION KEY_VALUE_SUPER_GENERIC_TYPE other) {
Objects.requireNonNull(other); #endif
return T -> GET_VALUE(T) || other.test(T); #if VALUE_BOOLEAN
} /**
#else if VALUE_OBJECT * Creates a Always true function that may be useful if you don't need to process information or just want a default.
* @Type(T)
@Override * @return a default returning function
public default VALUE_TYPE apply(KEY_TYPE k) { return GET_VALUE(k); } */
#else public static GENERIC_KEY_BRACES FUNCTION KEY_GENERIC_TYPE alwaysTrue() {
return T -> true;
@Override }
public default VALUE_TYPE APPLY_VALUE(KEY_TYPE k) { return GET_VALUE(k); }
#endif /**
#endif * Creates a Always false function that may be useful if you don't need to process information or just want a default.
* @Type(T)
* @return a default returning function
*/
public static GENERIC_KEY_BRACES FUNCTION KEY_GENERIC_TYPE alwaysFalse() {
return T -> false;
}
/**
* A Type specific and-function helper function that reduces boxing/unboxing
* @param other the other function that should be merged with.
* @return a function that compares values in a and comparason
*/
public default FUNCTION KEY_VALUE_GENERIC_TYPE andType(FUNCTION KEY_VALUE_GENERIC_TYPE other) {
Objects.requireNonNull(other);
return T -> APPLY(T) && other.APPLY(T);
}
#if JDK_FUNCTION
@Override
@Deprecated
public default FUNCTION KEY_VALUE_GENERIC_TYPE and(JAVA_FUNCTION KEY_VALUE_SUPER_GENERIC_TYPE other) {
Objects.requireNonNull(other);
return T -> APPLY(T) && other.APPLY(T);
}
@Override
#else
/**
* A type specific inverter function
* @return the same function but inverts the result
*/
#endif
public default FUNCTION KEY_VALUE_GENERIC_TYPE negate() {
return T -> !APPLY(T);
}
/**
* A Type specific or-function helper function that reduces boxing/unboxing
* @param other the other function that should be merged with.
* @return a function that compares values in a or comparason
*/
public default FUNCTION KEY_VALUE_GENERIC_TYPE orType(FUNCTION KEY_VALUE_GENERIC_TYPE other) {
Objects.requireNonNull(other);
return T -> APPLY(T) || other.APPLY(T);
}
#if JDK_FUNCTION
@Override
@Deprecated
public default FUNCTION KEY_VALUE_GENERIC_TYPE or(JAVA_FUNCTION KEY_VALUE_SUPER_GENERIC_TYPE other) {
Objects.requireNonNull(other);
return T -> APPLY(T) || other.APPLY(T);
}
#endif
#endif
} }
@@ -24,12 +24,12 @@ public interface UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE extends BiFunction<CLASS_
#else #else
/** /**
* A Type Specifc apply method to reduce boxing/unboxing. * A Type Specifc apply method to reduce boxing/unboxing.
* Applies this function to the given arguments. * Applies this function to the given arguments.
* *
* @param k the first function argument * @param k the first function argument
* @param v the second function argument * @param v the second function argument
* @return the function result * @return the function result
*/ */
public VALUE_TYPE APPLY_VALUE(KEY_TYPE k, VALUE_TYPE v); public VALUE_TYPE APPLY_VALUE(KEY_TYPE k, VALUE_TYPE v);
@Override @Override
@@ -1,13 +1,26 @@
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.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;
#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;
#endif
import speiger.src.collections.utils.SanityChecks;
/** /**
* Abstract implementation of the {@link LIST} interface. * Abstract implementation of the {@link LIST} interface.
@@ -15,9 +28,8 @@ import speiger.src.collections.PACKAGE.collections.ITERATOR;
*/ */
public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION KEY_GENERIC_TYPE implements LIST KEY_GENERIC_TYPE public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION KEY_GENERIC_TYPE implements LIST KEY_GENERIC_TYPE
{ {
#if !TYPE_OBJECT
/** /**
* A Type-Specific implementation of add function that delegates to {@link #add(int, KEY_TYPE)} * A Type-Specific implementation of add function that delegates to {@link List#add(int, Object)}
*/ */
@Override @Override
public boolean add(KEY_TYPE e) { public boolean add(KEY_TYPE e) {
@@ -25,6 +37,7 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
return true; return true;
} }
#if !TYPE_OBJECT
/** {@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.
@@ -43,9 +56,7 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
*/ */
@Override @Override
public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) { public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) {
boolean modified = false; return addAll(size(), c);
for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();modified |= add(iter.NEXT()));
return modified;
} }
/** /**
@@ -55,16 +66,24 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
*/ */
@Override @Override
public boolean addAll(LIST KEY_GENERIC_TYPE c) { public boolean addAll(LIST KEY_GENERIC_TYPE c) {
boolean modified = false; return addAll(size(), c);
for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();modified |= add(iter.NEXT())); }
return modified;
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public boolean addAll(Collection<? extends CLASS_TYPE> c) {
return c instanceof COLLECTION ? addAll((COLLECTION KEY_GENERIC_TYPE)c) : addAll(size(), c);
} }
/** /**
* The IndexOf implementation iterates over all elements and compares them to the search value. * The IndexOf implementation iterates over all elements and compares them to the search value.
* @param o the value that the index is searched for. * @param o the value that the index is searched for.
* @return index of the value that was searched for. -1 if not found * @return index of the value that was searched for. -1 if not found
* @deprecated it is highly suggested not to use this with Primitives because of boxing. But it is still supported because of ObjectComparason that are custom objects and allow to find the contents. * @note it is highly suggested not to use this with Primitives because of boxing. But it is still supported because of ObjectComparason that are custom objects and allow to find the contents.
*/ */
@Override @Override
@Primitive @Primitive
@@ -92,7 +111,7 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
* The lastIndexOf implementation iterates over all elements and compares them to the search value. * The lastIndexOf implementation iterates over all elements and compares them to the search value.
* @param o the value that the index is searched for. * @param o the value that the index is searched for.
* @return the last index of the value that was searched for. -1 if not found * @return the last index of the value that was searched for. -1 if not found
* @deprecated it is highly suggested not to use this with Primitives because of boxing. But it is still supported because of ObjectComparason that are custom objects and allow to find the contents. * @note it is highly suggested not to use this with Primitives because of boxing. But it is still supported because of ObjectComparason that are custom objects and allow to find the contents.
*/ */
@Override @Override
@Primitive @Primitive
@@ -148,36 +167,44 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
} }
#endif #endif
@Override
public boolean REMOVE_SWAP(KEY_TYPE e) {
int index = indexOf(e);
if(index == -1) return false;
swapRemove(index);
return true;
}
/** /**
* Compares if the list are the same. * Compares if the list are the same.
*/ */
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (o == this) if (o == this)
return true; return true;
if (!(o instanceof List)) if (!(o instanceof List))
return false; return false;
List<?> l = (List<?>)o; List<?> l = (List<?>)o;
if(l.size() != size()) return false; if(l.size() != size()) return false;
#if !TYPE_OBJECT #if !TYPE_OBJECT
if(l instanceof LIST) if(l instanceof LIST)
{ {
LIST_ITERATOR e1 = listIterator(); LIST_ITERATOR e1 = listIterator();
LIST_ITERATOR e2 = ((LIST)l).listIterator(); LIST_ITERATOR e2 = ((LIST)l).listIterator();
while (e1.hasNext() && e2.hasNext()) { while (e1.hasNext() && e2.hasNext()) {
if(!(KEY_EQUALS(e1.NEXT(), e2.NEXT()))) if(!(KEY_EQUALS(e1.NEXT(), e2.NEXT())))
return false; return false;
} }
return !(e1.hasNext() || e2.hasNext()); return !(e1.hasNext() || e2.hasNext());
} }
#endif #endif
ListIterator<CLASS_TYPE> e1 = listIterator(); ListIterator<CLASS_TYPE> e1 = listIterator();
ListIterator<?> e2 = l.listIterator(); ListIterator<?> e2 = l.listIterator();
while (e1.hasNext() && e2.hasNext()) { while (e1.hasNext() && e2.hasNext()) {
if(!Objects.equals(e1.next(), e2.next())) if(!Objects.equals(e1.next(), e2.next()))
return false; return false;
} }
return !(e1.hasNext() || e2.hasNext()); return !(e1.hasNext() || e2.hasNext());
} }
/** /**
@@ -185,20 +212,26 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
*/ */
@Override @Override
public int hashCode() { public int hashCode() {
int hashCode = 1; int hashCode = 1;
LIST_ITERATOR KEY_GENERIC_TYPE i = listIterator(); LIST_ITERATOR KEY_GENERIC_TYPE i = listIterator();
while(i.hasNext()) while(i.hasNext())
#if TYPE_OBJECT #if TYPE_OBJECT
hashCode = 31 * hashCode + i.next().hashCode(); hashCode = 31 * hashCode + i.next().hashCode();
#else #else
hashCode = 31 * hashCode + KEY_TO_HASH(i.NEXT()); hashCode = 31 * hashCode + KEY_TO_HASH(i.NEXT());
#endif #endif
return hashCode; return hashCode;
} }
@Override @Override
public LIST KEY_GENERIC_TYPE subList(int fromIndex, int toIndex) { public LIST KEY_GENERIC_TYPE subList(int fromIndex, int toIndex) {
return new SUB_LIST(this, fromIndex, toIndex); SanityChecks.checkArrayCapacity(size(), fromIndex, toIndex-fromIndex);
return new SubList(this, 0, fromIndex, toIndex);
}
@Override
public LIST KEY_GENERIC_TYPE reversed() {
return new ReversedList(this);
} }
@Override @Override
@@ -210,144 +243,558 @@ 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();
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);
while(size < size()) REMOVE(size() - 1); while(size < size()) REMOVE(size() - 1);
} }
private class SUB_LIST extends ABSTRACT_LIST KEY_GENERIC_TYPE { public ABSTRACT_LIST KEY_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); }
ABSTRACT_LIST KEY_GENERIC_TYPE l;
int offset; private class ReversedList extends ABSTRACT_LIST KEY_GENERIC_TYPE
int size; {
final ABSTRACT_LIST KEY_GENERIC_TYPE list;
SUB_LIST(ABSTRACT_LIST KEY_GENERIC_TYPE l, int from, int to) { public ReversedList(ABSTRACT_LIST KEY_GENERIC_TYPE list) {
if (from < 0) throw new IndexOutOfBoundsException("fromIndex = " + from); this.list = list;
else if (to > l.size()) throw new IndexOutOfBoundsException("toIndex = " + to);
else if (from > to) throw new IllegalArgumentException("fromIndex(" + from + ") > toIndex(" + to + ")");
this.l = l;
offset = from;
size = to - from;
} }
@Override @Override
public void add(int index, KEY_TYPE e) { public void add(int index, KEY_TYPE e) {
checkAddRange(index); list.add(list.size() - index - 1, e);
l.add(index+offset, e);
size++;
}
@Override
public boolean addAll(int index, Collection<? extends CLASS_TYPE> c) {
checkAddRange(index);
int size = c.size();
if(size == 0) return false;
l.addAll(index + offset, l);
offset += size;
return true;
} }
@Override @Override
public boolean addAll(int index, COLLECTION KEY_GENERIC_TYPE c) { public boolean addAll(int index, COLLECTION KEY_GENERIC_TYPE c) {
checkAddRange(index); return addCollection(index, c);
int size = c.size();
if(size == 0) return false;
l.addAll(index + offset, l);
offset += size;
return true;
} }
@Override @Override
public boolean addAll(int index, LIST KEY_GENERIC_TYPE c) { public boolean addAll(int index, LIST KEY_GENERIC_TYPE c) {
checkAddRange(index); if(c instanceof RandomAccess) {
int size = c.size(); for(int i = 0,m=c.size();i<m;i++) {
if(size == 0) return false; list.add(list.size() - index - i - 1, c.GET_KEY(i));
l.addAll(index + offset, l); }
offset += size; 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; 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 @Override
public void addElements(int from, KEY_TYPE[] a, int offset, int length) { public void addElements(int from, KEY_TYPE[] a, int offset, int length) {
checkRange(from); for(int i = 0,m=length;i<m;i++) {
l.addElements(from + this.offset, a, offset, length); list.add(list.size() - from - i - 1, a[i+offset]);
size += length; }
} }
@Override @Override
public KEY_TYPE[] getElements(int from, KEY_TYPE[] a, int offset, int length) { public KEY_TYPE[] getElements(int from, KEY_TYPE[] a, int offset, int length) {
checkRange(from); return reverse(list.getElements(list.size() - from - 1, a, offset, length));
return l.getElements(from + this.offset, a, offset, length);
} }
@Override @Override
public void removeElements(int from, int to) { public void removeElements(int from, int to) {
checkRange(from); list.removeElements(list.size() - to - 1, list.size() - from - 1);
checkRange(to); }
l.removeElements(from + offset, to + offset);
size -= to - from; @Override
public KEY_TYPE swapRemove(int index) {
return list.swapRemove(list.size() - index - 1);
} }
#if TYPE_OBJECT #if TYPE_OBJECT
@Override @Override
public <K> K[] extractElements(int from, int to, Class<K> clz) { public <K> K[] extractElements(int from, int to, Class<K> type) {
checkRange(from); return reverse(list.extractElements(list.size() - to - 1, list.size() - from - 1, type));
checkRange(to);
K[] a = l.extractElements(from + offset, to + offset, clz);
size -= to - from;
return a;
} }
#else #else
@Override @Override
public KEY_TYPE[] extractElements(int from, int to) { public KEY_TYPE[] extractElements(int from, int to) {
checkRange(from); return reverse(list.extractElements(list.size() - to - 1, list.size() - from - 1));
checkRange(to); }
KEY_TYPE[] a = l.extractElements(from + offset, to + offset);
#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
{
final ABSTRACT_LIST KEY_GENERIC_TYPE list;
final int parentOffset;
final int offset;
int size;
public SubList(ABSTRACT_LIST KEY_GENERIC_TYPE list, int offset, int from, int to) {
this.list = list;
this.parentOffset = from;
this.offset = offset + from;
this.size = to - from;
}
@Override
public void add(int index, KEY_TYPE element) {
checkAddSubRange(index);
list.add(parentOffset+index, element);
size++;
}
@Override
public boolean addAll(int index, Collection<? extends CLASS_TYPE> c) {
checkAddSubRange(index);
int add = c.size();
if(add <= 0) return false;
list.addAll(parentOffset+index, c);
this.size += add;
return true;
}
@Override
public boolean addAll(int index, COLLECTION KEY_GENERIC_TYPE c) {
checkAddSubRange(index);
int add = c.size();
if(add <= 0) return false;
list.addAll(parentOffset+index, c);
this.size += add;
return true;
}
@Override
public boolean addAll(int index, LIST KEY_GENERIC_TYPE c) {
checkAddSubRange(index);
int add = c.size();
if(add <= 0) return false;
list.addAll(parentOffset+index, c);
this.size += add;
return true;
}
@Override
public void addElements(int from, KEY_TYPE[] a, int offset, int length) {
checkAddSubRange(from);
if(length <= 0) return;
list.addElements(parentOffset+from, a, offset, length);
this.size += length;
}
@Override
public KEY_TYPE[] getElements(int from, KEY_TYPE[] a, int offset, int length) {
SanityChecks.checkArrayCapacity(size, from, length);
SanityChecks.checkArrayCapacity(a.length, offset, length);
return list.getElements(from+parentOffset, a, offset, length);
}
@Override
public void removeElements(int from, int to) {
if(to-from <= 0) return;
checkSubRange(from);
checkAddSubRange(to);
list.removeElements(from+parentOffset, to+parentOffset);
size -= to - from; size -= to - from;
return a; }
#if TYPE_OBJECT
@Override
public <K> K[] extractElements(int from, int to, Class<K> type) {
checkSubRange(from);
checkAddSubRange(to);
K[] result = list.extractElements(from+parentOffset, to+parentOffset, type);
size -= result.length;
return result;
}
#else
@Override
public KEY_TYPE[] extractElements(int from, int to) {
checkSubRange(from);
checkAddSubRange(to);
KEY_TYPE[] result = list.extractElements(from+parentOffset, to+parentOffset);
size -= result.length;
return result;
} }
#endif #endif
@Override @Override
public KEY_TYPE GET_KEY(int index) { public KEY_TYPE GET_KEY(int index) {
checkRange(index); checkSubRange(index);
return l.GET_KEY(index + offset); return list.GET_KEY(parentOffset+index);
}
@Override
public KEY_TYPE set(int index, KEY_TYPE element) {
checkSubRange(index);
return list.set(parentOffset+index, element);
} }
@Override @Override
public KEY_TYPE set(int index, KEY_TYPE e) { public KEY_TYPE swapRemove(int index) {
checkRange(index); checkSubRange(index);
return l.set(index + offset, e); if(index == size-1) {
KEY_TYPE result = list.REMOVE(parentOffset+size-1);
size--;
return result;
}
KEY_TYPE result = list.set(index+parentOffset, list.GET_KEY(parentOffset+size-1));
list.REMOVE(parentOffset+size-1);
size--;
return result;
} }
@Override @Override
public KEY_TYPE REMOVE(int index) { public KEY_TYPE REMOVE(int index) {
checkRange(index); checkSubRange(index);
KEY_TYPE result = list.REMOVE(index+parentOffset);
size--; size--;
return l.REMOVE(index + offset); return result;
} }
@Override @Override
public int size() { public int size() {
return size; return size;
} }
#if SPLIT_ITERATOR_FEATURE
@Override
public SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createSplititerator(this, 16464); }
#endif
private void checkRange(int index) { @Override
public LIST_ITERATOR KEY_GENERIC_TYPE listIterator(int index) {
if(index < 0 || index > size()) throw new IndexOutOfBoundsException();
return new SubListIterator(this, index);
}
@Override
public LIST KEY_GENERIC_TYPE subList(int fromIndex, int toIndex) {
SanityChecks.checkArrayCapacity(size, fromIndex, toIndex-fromIndex);
return new SubList(this, offset, fromIndex, toIndex);
}
protected void checkSubRange(int index) {
if (index < 0 || index >= size) if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
} }
private void checkAddRange(int index) { protected void checkAddSubRange(int index) {
if (index < 0 || index > size) if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
} }
private class SubListIterator implements LIST_ITERATOR KEY_GENERIC_TYPE
{
ABSTRACT_LIST KEY_GENERIC_TYPE list;
int index;
int lastReturned = -1;
SubListIterator(ABSTRACT_LIST KEY_GENERIC_TYPE list, int index) {
this.list = list;
this.index = index;
}
@Override
public boolean hasNext() {
return index < list.size();
}
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
int i = index++;
return list.GET_KEY((lastReturned = i));
}
@Override
public boolean hasPrevious() {
return index > 0;
}
@Override
public KEY_TYPE PREVIOUS() {
if(!hasPrevious()) throw new NoSuchElementException();
index--;
return list.GET_KEY((lastReturned = index));
}
@Override
public int nextIndex() {
return index;
}
@Override
public int previousIndex() {
return index-1;
}
@Override
public void remove() {
if(lastReturned == -1) throw new IllegalStateException();
list.REMOVE(lastReturned);
index = lastReturned;
lastReturned = -1;
}
@Override
public void set(KEY_TYPE e) {
if(lastReturned == -1) throw new IllegalStateException();
list.set(lastReturned, e);
}
@Override
public void add(KEY_TYPE e) {
list.add(index, e);
index++;
lastReturned = -1;
}
@Override
public int skip(int amount) {
if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
int steps = Math.min(amount, size() - index);
index += steps;
if(steps > 0) lastReturned = Math.min(index-1, size()-1);
return steps;
}
@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.min(index, size()-1);
return steps;
}
}
}
#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 {
@@ -365,8 +812,9 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
@Override @Override
public KEY_TYPE NEXT() { public KEY_TYPE NEXT() {
lastReturned = index; if(!hasNext()) throw new NoSuchElementException();
return GET_KEY(index++); int i = index++;
return GET_KEY((lastReturned = i));
} }
@Override @Override
@@ -376,8 +824,9 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
@Override @Override
public KEY_TYPE PREVIOUS() { public KEY_TYPE PREVIOUS() {
lastReturned = index; if(!hasPrevious()) throw new NoSuchElementException();
return GET_KEY(index--); index--;
return GET_KEY((lastReturned = index));
} }
@Override @Override
@@ -392,34 +841,31 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
@Override @Override
public void remove() { public void remove() {
if(lastReturned == -1) if(lastReturned == -1) throw new IllegalStateException();
throw new IllegalStateException();
ABSTRACT_LIST.this.REMOVE(lastReturned); ABSTRACT_LIST.this.REMOVE(lastReturned);
if(lastReturned < index) index = lastReturned;
index--;
lastReturned = -1; lastReturned = -1;
} }
@Override @Override
public void set(KEY_TYPE e) { public void set(KEY_TYPE e) {
if(lastReturned == -1) if(lastReturned == -1) throw new IllegalStateException();
throw new IllegalStateException();
ABSTRACT_LIST.this.set(lastReturned, e); ABSTRACT_LIST.this.set(lastReturned, e);
} }
@Override @Override
public void add(KEY_TYPE e) { public void add(KEY_TYPE e) {
if(lastReturned == -1) ABSTRACT_LIST.this.add(index, e);
throw new IllegalStateException(); index++;
ABSTRACT_LIST.this.add(index++, e);
lastReturned = -1; lastReturned = -1;
} }
@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");
int steps = Math.min(amount, (size() - 1) - index); int steps = Math.min(amount, size() - index);
index += steps; index += steps;
if(steps > 0) lastReturned = Math.min(index-1, size()-1);
return steps; return steps;
} }
@@ -428,6 +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.max(index, 0);
return steps; return steps;
} }
} }
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,585 @@
package speiger.src.collections.PACKAGE.lists;
import java.util.Arrays;
#if TYPE_OBJECT
import java.util.Comparator;
#endif
import java.util.Collection;
import java.util.NoSuchElementException;
import java.util.Objects;
#if TYPE_OBJECT
import java.util.function.BiFunction;
import java.util.function.Consumer;
#endif
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
#if !TYPE_OBJECT && JDK_FUNCTION
import java.util.function.PREDICATE;
#endif
#if PRIMITIVES
#if !JDK_FUNCTION
import java.util.function.JAVA_PREDICATE;
#endif
import java.util.function.JAVA_UNARY_OPERATOR;
#endif
import speiger.src.collections.PACKAGE.collections.COLLECTION;
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
import speiger.src.collections.PACKAGE.utils.ARRAYS;
#endif
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
#if !JDK_FUNCTION
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
#endif
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.objects.utils.ObjectArrays;
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
import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR;
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
#endif
import speiger.src.collections.utils.SanityChecks;
#if TYPE_OBJECT
/**
* A Type-Specific Immutable implementation of list that is written to reduce (un)boxing
*
* @Type(T)
*/
public class IMMUTABLE_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
#else
/**
* A Type-Specific Immutable implementation of list that is written to reduce (un)boxing
*/
public class IMMUTABLE_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
#endif
{
/** The backing array */
protected transient KEY_TYPE[] data;
/**
* Creates a new Immutable copy of the contents of the Collection.
* @param c the elements that should be added into the list
*/
@Primitive
public IMMUTABLE_LIST(Collection<? extends CLASS_TYPE> c) {
data = ARRAYS.pour(ITERATORS.wrap(c.iterator()));
}
/**
* Creates a new Immutable copy of the contents of the Collection.
* @param c the elements that should be added into the list
*/
public IMMUTABLE_LIST(COLLECTION KEY_GENERIC_TYPE c) {
data = ARRAYS.pour(c.iterator());
}
/**
* Creates a new Immutable copy of the contents of the List.
* @param l the elements that should be added into the list
*/
public IMMUTABLE_LIST(LIST KEY_GENERIC_TYPE l) {
KEY_TYPE[] temp = NEW_KEY_ARRAY(l.size());
l.getElements(0, temp, 0, l.size());
data = temp;
}
/**
* Creates a new Immutable copy of the contents of the Array.
* @param a the array that should be copied
*/
public IMMUTABLE_LIST(KEY_TYPE... a) {
this(a, 0, a.length);
}
/**
* Creates a new ImmutableList copy of the array with a custom length
* @param a the array that should be copied
* @param length the desired length that should be copied
*/
public IMMUTABLE_LIST(KEY_TYPE[] a, int length) {
this(a, 0, length);
}
/**
* Creates a new ImmutableList copy of the array with in the custom range.
* @param a the array that should be copied
* @param offset the starting offset of where the array should be copied from
* @param length the desired length that should be copied
* @throws IllegalStateException if offset is smaller then 0
* @throws IllegalStateException if the offset + length exceeds the array length
*/
public IMMUTABLE_LIST(KEY_TYPE[] a, int offset, int length) {
SanityChecks.checkArrayCapacity(a.length, offset, length);
data = Arrays.copyOfRange(a, offset, offset+length);
}
@Override
public boolean add(KEY_TYPE e) { throw new UnsupportedOperationException(); }
@Override
public void add(int index, KEY_TYPE e) { throw new UnsupportedOperationException(); }
@Override
@Primitive
public boolean addAll(int index, Collection<? extends CLASS_TYPE> c) { throw new UnsupportedOperationException(); }
@Override
public boolean addAll(int index, COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); }
@Override
public boolean addAll(int index, LIST KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); }
@Override
public boolean addAll(KEY_TYPE[] e, int offset, int length) { throw new UnsupportedOperationException(); }
@Override
public void addElements(int from, KEY_TYPE[] a, int offset, int length) { throw new UnsupportedOperationException(); }
@Override
public KEY_TYPE[] getElements(int from, KEY_TYPE[] a, int offset, int length) {
SanityChecks.checkArrayCapacity(a.length, offset, length);
SanityChecks.checkArrayCapacity(data.length, from, length);
System.arraycopy(data, from, a, offset, length);
return a;
}
@Override
public void removeElements(int from, int to) { throw new UnsupportedOperationException(); }
#if TYPE_OBJECT
@Override
public <K> K[] extractElements(int from, int to, Class<K> type) { throw new UnsupportedOperationException(); }
#else
@Override
public KEY_TYPE[] extractElements(int from, int to) { throw new UnsupportedOperationException(); }
#endif
/**
* A function to find if the Element is present in this list.
* @param o the element that is searched for
* @return if the element was found.
*/
@Override
@Primitive
public boolean contains(Object o) {
return indexOf(o) != -1;
}
/**
* A function to find the index of a given element
* @param o the element that is searched for
* @return the index of the element if found. (if not found then -1)
*/
@Override
@Primitive
public int indexOf(Object o) {
#if TYPE_OBJECT
if(o == null) {
for(int i = 0,m=data.length;i<m;i++)
if(data[i] == null) return i;
return -1;
}
#else
if(o == null) return -1;
#endif
for(int i = 0,m=data.length;i<m;i++) {
if(EQUALS_KEY_TYPE(data[i], o)) return i;
}
return -1;
}
/**
* A function to find the last index of a given element
* @param o the element that is searched for
* @return the last index of the element if found. (if not found then -1)
*/
@Override
@Primitive
public int lastIndexOf(Object o) {
#if TYPE_OBJECT
if(o == null) {
for(int i = data.length - 1;i>=0;i--)
if(data[i] == null) return i;
return -1;
}
#else
if(o == null) return -1;
#endif
for(int i = data.length - 1;i>=0;i--) {
if(EQUALS_KEY_TYPE(data[i], o)) return i;
}
return -1;
}
#if TYPE_OBJECT
@Override
public void sort(Comparator<? super CLASS_TYPE> c) { throw new UnsupportedOperationException(); }
@Override
public void unstableSort(Comparator<? super CLASS_TYPE> c) { throw new UnsupportedOperationException(); }
#else
/**
* A Type Specific implementation of the Collection#contains function.
* @param e the element that is searched for.
* @return if the element was found
*/
@Override
public boolean contains(KEY_TYPE e) {
return indexOf(e) != -1;
}
/**
* A Type-Specific function to find the index of a given element
* @param e the element that is searched for
* @return the index of the element if found. (if not found then -1)
*/
@Override
public int indexOf(KEY_TYPE e) {
for(int i = 0,m=data.length;i<m;i++) {
if(KEY_EQUALS(data[i], e)) return i;
}
return -1;
}
/**
* A Type-Specific function to find the last index of a given element
* @param e the element that is searched for
* @return the last index of the element if found. (if not found then -1)
*/
@Override
public int lastIndexOf(KEY_TYPE e) {
for(int i = data.length - 1;i>=0;i--) {
if(KEY_EQUALS(data[i], e)) return i;
}
return -1;
}
@Override
public void sort(COMPARATOR c) { throw new UnsupportedOperationException(); }
@Override
public void unstableSort(COMPARATOR c) { throw new UnsupportedOperationException(); }
#endif
/**
* A Type-Specific get function to reduce (un)boxing
* @param index the index of the element to fetch
* @return the value of the requested index
* @throws IndexOutOfBoundsException if the index is out of range
*/
@Override
public KEY_TYPE GET_KEY(int index) {
checkRange(index);
return data[index];
}
@Override
public IMMUTABLE_LIST KEY_GENERIC_TYPE copy() {
return new IMMUTABLE_LISTBRACES(Arrays.copyOf(data, data.length));
}
/**
* A Type Specific foreach function that reduces (un)boxing
*
* @implSpec
* <p>The default implementation behaves as if:
* <pre>{@code
* for(int i = 0;i<size;i++)
* action.accept(data[i]);
* }</pre>
*
* @param action The action to be performed for each element
* @throws NullPointerException if the specified action is null
* @see Iterable#forEach(java.util.function.Consumer)
*/
@Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
for(int i = 0,m=data.length;i<m;i++)
action.accept(data[i]);
}
@Override
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
for(int i = 0,m=data.length;i<m;i++)
action.accept(input, data[i]);
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0,m=data.length;i<m;i++) {
if(filter.test(data[i])) return true;
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0,m=data.length;i<m;i++) {
if(filter.test(data[i])) return false;
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0,m=data.length;i<m;i++) {
if(!filter.test(data[i])) return false;
}
return true;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0,m=data.length;i<m;i++) {
if(filter.test(data[i])) return data[i];
}
return EMPTY_VALUE;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
for(int i = 0,m=data.length;i<m;i++) {
state = operator.APPLY_VALUE(state, data[i]);
}
return state;
}
#else
@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);
KEY_SPECIAL_TYPE state = identity;
for(int i = 0,m=data.length;i<m;i++) {
state = operator.APPLY_VALUE(state, data[i]);
}
return state;
}
#endif
@Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_VALUE;
boolean empty = true;
for(int i = 0,m=data.length;i<m;i++) {
if(empty) {
empty = false;
state = data[i];
continue;
}
state = operator.APPLY_VALUE(state, data[i]);
}
return state;
}
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int result = 0;
for(int i = 0,m=data.length;i<m;i++) {
if(filter.test(data[i])) result++;
}
return result;
}
@Override
public LIST_ITERATOR KEY_GENERIC_TYPE listIterator(int index) {
if(index < 0 || index > size()) throw new IndexOutOfBoundsException();
return new LIST_ITER(index);
}
@Override
public KEY_TYPE set(int index, KEY_TYPE e) { throw new UnsupportedOperationException(); }
@Override
@Primitive
public void replaceAll(UnaryOperator<CLASS_TYPE> o) { throw new UnsupportedOperationException(); }
#if PRIMITIVES
@Override
public void REPLACE(JAVA_UNARY_OPERATOR o) { throw new UnsupportedOperationException(); }
#endif
@Override
public KEY_TYPE REMOVE(int index) { throw new UnsupportedOperationException(); }
@Override
public KEY_TYPE swapRemove(int index) { throw new UnsupportedOperationException(); }
#if !TYPE_OBJECT
@Override
public boolean REMOVE_KEY(KEY_TYPE type) { throw new UnsupportedOperationException(); }
#endif
@Override
@Primitive
public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException(); }
@Override
@Primitive
public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); }
@Override
@Primitive
public boolean removeIf(Predicate<? super CLASS_TYPE> filter) { throw new UnsupportedOperationException(); }
@Override
public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); }
@Override
public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); }
@Override
public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { throw new UnsupportedOperationException(); }
@Override
public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { throw new UnsupportedOperationException(); }
#if PRIMITIVES
@Override
public boolean remIf(JAVA_PREDICATE filter) { throw new UnsupportedOperationException(); }
#endif
/**
* A toArray implementation that ensures the Array itself is a Object.
* @return a Array of the elements in the list
*/
@Override
@Primitive
public Object[] toArray() {
if(data.length == 0) return ObjectArrays.EMPTY_ARRAY;
Object[] obj = new Object[data.length];
for(int i = 0,m=data.length;i<m;i++)
obj[i] = KEY_TO_OBJ(data[i]);
return obj;
}
/**
* A toArray implementation that ensures the Array itself is a Object.
* @param a original array. If null a Object array with the right size is created. If to small the Array of the same type is created with the right size
* @return a Array of the elements in the list
*/
@Override
@Primitive
public <E> E[] toArray(E[] a) {
if(a == null) a = (E[])new Object[data.length];
else if(a.length < data.length) a = (E[])ObjectArrays.newArray(a.getClass().getComponentType(), data.length);
for(int i = 0,m=data.length;i<m;i++)
a[i] = (E)KEY_TO_OBJ(data[i]);
if (a.length > data.length) a[data.length] = null;
return a;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) {
if(a.length < data.length) a = new KEY_TYPE[data.length];
System.arraycopy(data, 0, a, 0, data.length);
if (a.length > data.length) a[data.length] = EMPTY_KEY_VALUE;
return a;
}
#endif
/**
* A function to return the size of the list
* @return the size of elements in the list
*/
@Override
public int size() {
return data.length;
}
@Override
public void size(int size) { throw new UnsupportedOperationException(); }
@Override
public void clear() { throw new UnsupportedOperationException(); }
protected void checkRange(int index) {
if (index < 0 || index >= data.length)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + data.length);
}
#if SPLIT_ITERATOR_FEATURE
#if PRIMITIVES && STREAM_FEATURE
/**
* Returns a Java-Type-Specific Stream to reduce boxing/unboxing.
* @return a Stream of the closest java type
* @note characteristics are ordered, sized, subsized
*/
@Override
public JAVA_STREAM primitiveStream() { return StreamSupport.NEW_STREAM(SPLIT_ITERATORS.createArrayJavaSplititerator(data, data.length, 16464), false); }
#endif
/**
* A Type Specific Type Splititerator to reduce boxing/unboxing
* @return type specific splititerator
* @note characteristics are ordered, sized, subsized
*/
@Override
public SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createArraySplititerator(data, data.length, 16464); }
#endif
private class LIST_ITER implements LIST_ITERATOR KEY_GENERIC_TYPE {
int index;
LIST_ITER(int index) {
this.index = index;
}
@Override
public boolean hasNext() {
return index < size();
}
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
return GET_KEY(index++);
}
@Override
public boolean hasPrevious() {
return index > 0;
}
@Override
public KEY_TYPE PREVIOUS() {
if(!hasPrevious()) throw new NoSuchElementException();
return GET_KEY(--index);
}
@Override
public int nextIndex() {
return index;
}
@Override
public int previousIndex() {
return index-1;
}
@Override
public void remove() { throw new UnsupportedOperationException(); }
@Override
public void set(KEY_TYPE e) { throw new UnsupportedOperationException(); }
@Override
public void add(KEY_TYPE e) { throw new UnsupportedOperationException(); }
@Override
public int skip(int amount) {
if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
int steps = Math.min(amount, size() - index);
index += steps;
return steps;
}
@Override
public int back(int amount) {
if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
int steps = Math.min(amount, index);
index -= steps;
return steps;
}
}
}
File diff suppressed because it is too large Load Diff
@@ -26,9 +26,9 @@ public interface LIST_ITERATOR KEY_GENERIC_TYPE extends ListIterator<CLASS_TYPE>
public void add(KEY_TYPE e); public void add(KEY_TYPE e);
/** {@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
public default CLASS_TYPE previous() { public default CLASS_TYPE previous() {
@@ -36,9 +36,9 @@ public interface LIST_ITERATOR KEY_GENERIC_TYPE extends ListIterator<CLASS_TYPE>
} }
/** {@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
public default CLASS_TYPE next() { public default CLASS_TYPE next() {
@@ -46,9 +46,9 @@ public interface LIST_ITERATOR KEY_GENERIC_TYPE extends ListIterator<CLASS_TYPE>
} }
/** {@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
public default void set(CLASS_TYPE e) { public default void set(CLASS_TYPE e) {
@@ -56,9 +56,9 @@ public interface LIST_ITERATOR KEY_GENERIC_TYPE extends ListIterator<CLASS_TYPE>
} }
/** {@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
public default void add(CLASS_TYPE e) { public default void add(CLASS_TYPE e) {
@@ -3,27 +3,37 @@ package speiger.src.collections.PACKAGE.maps.abstracts;
import java.util.AbstractMap; import java.util.AbstractMap;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
#if VALUE_BOOLEAN && JDK_FUNCTION
import java.util.function.PREDICATE;
#endif
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER;
#if !VALUE_BOOLEAN || !JDK_FUNCTION
import speiger.src.collections.PACKAGE.functions.function.FUNCTION; import speiger.src.collections.PACKAGE.functions.function.FUNCTION;
#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;
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
import speiger.src.collections.PACKAGE.utils.maps.MAPS; import speiger.src.collections.PACKAGE.utils.maps.MAPS;
#endif
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION;
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION;
#if !SAME_TYPE #if !SAME_TYPE
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR;
import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR; import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR;
#endif #endif
import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_SUPPLIER;
import speiger.src.collections.objects.collections.ObjectIterable;
#if !TYPE_OBJECT && !VALUE_OBJECT #if !TYPE_OBJECT && !VALUE_OBJECT
import speiger.src.collections.objects.collections.ObjectIterator; import speiger.src.collections.objects.collections.ObjectIterator;
#endif #endif
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.objects.sets.ObjectSet; import speiger.src.collections.objects.sets.ObjectSet;
#endif #endif
import speiger.src.collections.utils.SanityChecks;
/** /**
* A Base Implementation of a Type Specific Map to reduce boxing/unboxing * A Base Implementation of a Type Specific Map to reduce boxing/unboxing
@@ -45,9 +55,46 @@ public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CL
return this; return this;
} }
protected ObjectIterable<MAP.Entry KEY_VALUE_GENERIC_TYPE> getFastIterable(MAP KEY_VALUE_GENERIC_TYPE map) {
#if MAPS_FEATURE
return MAPS.fastIterable(map);
#else
return map.ENTRY_SET();
#endif
}
protected ObjectIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> getFastIterator(MAP KEY_VALUE_GENERIC_TYPE map) {
#if MAPS_FEATURE
return MAPS.fastIterator(map);
#else
return map.ENTRY_SET().iterator();
#endif
}
@Override
public MAP KEY_VALUE_GENERIC_TYPE copy() {
throw new UnsupportedOperationException();
}
#if !TYPE_OBJECT || !VALUE_OBJECT
@Override
@Deprecated
public CLASS_VALUE_TYPE put(CLASS_TYPE key, CLASS_VALUE_TYPE value) {
return VALUE_TO_OBJ(put(OBJ_TO_KEY(key), OBJ_TO_VALUE(value)));
}
#endif
#if VALUE_PRIMITIVES
@Override
public void addToAll(MAP KEY_VALUE_GENERIC_TYPE m) {
for(MAP.Entry KEY_VALUE_GENERIC_TYPE entry : getFastIterable(m))
addTo(entry.ENTRY_KEY(), entry.ENTRY_VALUE());
}
#endif
@Override @Override
public void putAll(MAP KEY_VALUE_GENERIC_TYPE m) { public void putAll(MAP KEY_VALUE_GENERIC_TYPE m) {
for(ObjectIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> iter = MAPS.fastIterator(m);iter.hasNext();) { for(ObjectIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> iter = getFastIterator(m);iter.hasNext();) {
MAP.Entry KEY_VALUE_GENERIC_TYPE entry = iter.next(); MAP.Entry KEY_VALUE_GENERIC_TYPE entry = iter.next();
put(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); put(entry.ENTRY_KEY(), entry.ENTRY_VALUE());
} }
@@ -60,6 +107,28 @@ public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CL
else super.putAll(m); else super.putAll(m);
} }
@Override
public void putAll(KEY_TYPE[] keys, VALUE_TYPE[] values, int offset, int size) {
SanityChecks.checkArrayCapacity(keys.length, offset, size);
SanityChecks.checkArrayCapacity(values.length, offset, size);
for(int i = 0;i<size;i++) put(keys[i], values[i]);
}
#if !TYPE_OBJECT || !VALUE_OBJECT
@Override
public void putAll(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, int offset, int size) {
SanityChecks.checkArrayCapacity(keys.length, offset, size);
SanityChecks.checkArrayCapacity(values.length, offset, size);
for(int i = 0;i<size;i++) put(keys[i], values[i]);
}
#endif
@Override
public void putAllIfAbsent(MAP KEY_VALUE_GENERIC_TYPE m) {
for(MAP.Entry KEY_VALUE_GENERIC_TYPE entry : getFastIterable(m))
putIfAbsent(entry.ENTRY_KEY(), entry.ENTRY_VALUE());
}
#if TYPE_OBJECT #if TYPE_OBJECT
@Override @Override
@@ -98,26 +167,32 @@ public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CL
@Override @Override
public boolean replace(KEY_TYPE key, VALUE_TYPE oldValue, VALUE_TYPE newValue) { public boolean replace(KEY_TYPE key, VALUE_TYPE oldValue, VALUE_TYPE newValue) {
VALUE_TYPE curValue = GET_VALUE(key); VALUE_TYPE curValue = GET_VALUE(key);
if (VALUE_EQUALS_NOT(curValue, oldValue) || (VALUE_EQUALS(curValue, getDefaultReturnValue()) && !containsKey(key))) { if (VALUE_EQUALS_NOT(curValue, oldValue) || (VALUE_EQUALS(curValue, getDefaultReturnValue()) && !containsKey(key))) {
return false; return false;
} }
put(key, newValue); put(key, newValue);
return true; return true;
} }
@Override @Override
public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value) { public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value) {
VALUE_TYPE curValue; VALUE_TYPE curValue;
if (VALUE_EQUALS_NOT((curValue = GET_VALUE(key)), getDefaultReturnValue()) || containsKey(key)) { if (VALUE_EQUALS_NOT((curValue = GET_VALUE(key)), getDefaultReturnValue()) || containsKey(key)) {
curValue = put(key, value); curValue = put(key, value);
} }
return curValue; return curValue;
}
@Override
public void REPLACE_VALUES(MAP KEY_VALUE_GENERIC_TYPE m) {
for(MAP.Entry KEY_VALUE_GENERIC_TYPE entry : getFastIterable(m))
replace(entry.ENTRY_KEY(), entry.ENTRY_VALUE());
} }
@Override @Override
public void REPLACE_VALUES(UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { public void REPLACE_VALUES(UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction); Objects.requireNonNull(mappingFunction);
for(ObjectIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> iter = MAPS.fastIterator(this);iter.hasNext();) { for(ObjectIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> iter = getFastIterator(this);iter.hasNext();) {
MAP.Entry KEY_VALUE_GENERIC_TYPE entry = iter.next(); MAP.Entry KEY_VALUE_GENERIC_TYPE entry = iter.next();
entry.setValue(mappingFunction.APPLY_VALUE(entry.ENTRY_KEY(), entry.ENTRY_VALUE())); entry.setValue(mappingFunction.APPLY_VALUE(entry.ENTRY_KEY(), entry.ENTRY_VALUE()));
} }
@@ -125,59 +200,176 @@ 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);
VALUE_TYPE value = GET_VALUE(key); #if !VALUE_OBJECT
VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, value); VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, GET_VALUE(key));
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { #else
if(VALUE_EQUALS_NOT(value, getDefaultReturnValue()) || containsKey(key)) { VALUE_TYPE value = GET_VALUE(key);
remove(key); VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, value);
return getDefaultReturnValue(); if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
} if(VALUE_EQUALS_NOT(value, getDefaultReturnValue()) || containsKey(key)) {
return getDefaultReturnValue(); remove(key);
} return getDefaultReturnValue();
put(key, newValue); }
return getDefaultReturnValue();
}
#endif
put(key, newValue);
return newValue; return newValue;
} }
@Override @Override
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) {
Objects.requireNonNull(mappingFunction); Objects.requireNonNull(mappingFunction);
VALUE_TYPE value; #if VALUE_OBJECT
if((value = GET_VALUE(key)) == getDefaultReturnValue() || !containsKey(key)) { VALUE_TYPE value;
VALUE_TYPE newValue = mappingFunction.GET_VALUE(key); if((value = GET_VALUE(key)) == getDefaultReturnValue() || !containsKey(key)) {
if(VALUE_EQUALS_NOT(newValue, getDefaultReturnValue())) { VALUE_TYPE newValue = mappingFunction.APPLY(key);
put(key, newValue); if(VALUE_EQUALS_NOT(newValue, getDefaultReturnValue())) {
return newValue; put(key, newValue);
} return newValue;
} }
}
return value; 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 @Override
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) {
Objects.requireNonNull(mappingFunction); Objects.requireNonNull(mappingFunction);
VALUE_TYPE value; #if VALUE_OBJECT
if(VALUE_EQUALS_NOT((value = GET_VALUE(key)), getDefaultReturnValue()) || containsKey(key)) { VALUE_TYPE value;
VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, value); if(VALUE_EQUALS_NOT((value = GET_VALUE(key)), getDefaultReturnValue()) || containsKey(key)) {
if(VALUE_EQUALS_NOT(newValue, getDefaultReturnValue())) { VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, value);
put(key, newValue); if(VALUE_EQUALS_NOT(newValue, getDefaultReturnValue())) {
return newValue; put(key, newValue);
} return newValue;
remove(key); }
} remove(key);
}
#else
if(containsKey(key)) {
VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, GET_VALUE(key));
put(key, newValue);
return newValue;
}
#endif
return getDefaultReturnValue(); 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 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();
}
put(key, newValue);
return newValue;
}
@Override
public VALUE_TYPE COMPUTE_IF_ABSENTNonDefault(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction);
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;
}
@Override
public VALUE_TYPE SUPPLY_IF_ABSENTNonDefault(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) {
Objects.requireNonNull(valueProvider);
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;
}
@Override
public VALUE_TYPE COMPUTE_IF_PRESENTNonDefault(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction);
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);
}
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);
VALUE_TYPE oldValue = GET_VALUE(key); VALUE_TYPE oldValue = GET_VALUE(key);
VALUE_TYPE newValue = VALUE_EQUALS(oldValue, getDefaultReturnValue()) ? value : mappingFunction.APPLY_VALUE(oldValue, value); VALUE_TYPE newValue = VALUE_EQUALS(oldValue, getDefaultReturnValue()) ? value : mappingFunction.APPLY_VALUE(oldValue, value);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) remove(key); if(VALUE_EQUALS(newValue, getDefaultReturnValue())) remove(key);
else put(key, newValue); else put(key, newValue);
return newValue; return newValue;
} }
@Override
public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction);
for(MAP.Entry KEY_VALUE_GENERIC_TYPE entry : getFastIterable(m)) {
KEY_TYPE key = entry.ENTRY_KEY();
VALUE_TYPE oldValue = GET_VALUE(key);
VALUE_TYPE newValue = VALUE_EQUALS(oldValue, getDefaultReturnValue()) ? entry.ENTRY_VALUE() : mappingFunction.APPLY_VALUE(oldValue, entry.ENTRY_VALUE());
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) remove(key);
else put(key, newValue);
}
}
#if TYPE_OBJECT #if TYPE_OBJECT
@Override @Override
public CLASS_VALUE_TYPE get(Object key) { public CLASS_VALUE_TYPE get(Object key) {
@@ -208,10 +400,20 @@ public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CL
} }
#endif #endif
@Override
public CLASS_VALUE_TYPE remove(Object key) {
#if TYPE_OBJECT
return VALUE_TO_OBJ(REMOVE_VALUE((CLASS_TYPE)key));
#else
return key instanceof CLASS_TYPE ? VALUE_TO_OBJ(REMOVE_VALUE(CLASS_TO_KEY(key))) : VALUE_TO_OBJ(getDefaultReturnValue());
#endif
}
@Override @Override
public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) { public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) {
Objects.requireNonNull(action); Objects.requireNonNull(action);
for(ObjectIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> iter = MAPS.fastIterator(this);iter.hasNext();) { for(ObjectIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> iter = getFastIterator(this);iter.hasNext();) {
MAP.Entry KEY_VALUE_GENERIC_TYPE entry = iter.next(); MAP.Entry KEY_VALUE_GENERIC_TYPE entry = iter.next();
action.accept(entry.ENTRY_KEY(), entry.ENTRY_VALUE()); action.accept(entry.ENTRY_KEY(), entry.ENTRY_VALUE());
} }
@@ -229,7 +431,11 @@ public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CL
#else #else
@Override @Override
public boolean remove(Object o) { public boolean remove(Object o) {
return VALUE_EQUALS_NOT(ABSTRACT_MAP.this.remove(o), getDefaultReturnValue()); if(ABSTRACT_MAP.this.containsKey(o)) {
ABSTRACT_MAP.this.remove(o);
return true;
}
return false;
} }
#endif #endif
@@ -241,7 +447,7 @@ public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CL
@Override @Override
public ITERATOR KEY_GENERIC_TYPE iterator() { public ITERATOR KEY_GENERIC_TYPE iterator() {
return new ITERATOR KEY_GENERIC_TYPE() { return new ITERATOR KEY_GENERIC_TYPE() {
ObjectIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> iter = MAPS.fastIterator(ABSTRACT_MAP.this); ObjectIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> iter = getFastIterator(ABSTRACT_MAP.this);
@Override @Override
public boolean hasNext() { public boolean hasNext() {
return iter.hasNext(); return iter.hasNext();
@@ -292,7 +498,7 @@ public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CL
@Override @Override
public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() { public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() {
return new VALUE_ITERATOR VALUE_GENERIC_TYPE() { return new VALUE_ITERATOR VALUE_GENERIC_TYPE() {
ObjectIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> iter = MAPS.fastIterator(ABSTRACT_MAP.this); ObjectIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> iter = getFastIterator(ABSTRACT_MAP.this);
@Override @Override
public boolean hasNext() { public boolean hasNext() {
return iter.hasNext(); return iter.hasNext();
@@ -332,7 +538,7 @@ public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CL
@Override @Override
public int hashCode() { public int hashCode() {
int hash = 0; int hash = 0;
ObjectIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> iter = MAPS.fastIterator(this); ObjectIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> iter = getFastIterator(this);
while(iter.hasNext()) hash += iter.next().hashCode(); while(iter.hasNext()) hash += iter.next().hashCode();
return hash; return hash;
} }
@@ -427,7 +633,7 @@ public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CL
@Override @Override
public String toString() { public String toString() {
return KEY_TO_STRING(key) + "->" + VALUE_TO_STRING(value); return KEY_TO_STRING(key) + "=" + VALUE_TO_STRING(value);
} }
} }
} }
@@ -0,0 +1,995 @@
package speiger.src.collections.PACKAGE.maps.impl.misc;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.function.Consumer;
#if TYPE_OBJECT
import java.util.Objects;
#endif
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif
import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER;
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
import speiger.src.collections.PACKAGE.maps.interfaces.MAP;
import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP;
import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET;
import speiger.src.collections.PACKAGE.sets.ORDERED_SET;
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION;
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION;
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR;
#if !VALUE_OBJECT && !SAME_TYPE
import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER;
import speiger.src.collections.VALUE_PACKAGE.lists.VALUE_LIST_ITERATOR;
#endif
#if !TYPE_OBJECT
import speiger.src.collections.objects.collections.ObjectBidirectionalIterator;
import speiger.src.collections.objects.lists.ObjectListIterator;
import speiger.src.collections.objects.sets.AbstractObjectSet;
#endif
/**
* A Type Specific LinkedEnumMap implementation that allows for Primitive Values and faster iteration.
* Unlike javas implementation this one does not jump around between a single long or long array implementation based around the enum size
* This will cause a bit more memory usage but allows for a simpler implementation.
* @Type(T)
* @ValueType(V)
*/
public class LINKED_ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ENUM_MAP KEY_VALUE_GENERIC_TYPE implements ORDERED_MAP KEY_VALUE_GENERIC_TYPE
{
/** The Backing array for links between nodes. Left 32 Bits => Previous Entry, Right 32 Bits => Next Entry */
protected long[] links;
/** The First Index in the Map */
protected int firstIndex = -1;
/** The Last Index in the Map */
protected int lastIndex = -1;
/**
* Default Constructor
* @param keyType the type of Enum that should be used
*/
public LINKED_ENUM_MAP(Class<T> keyType) {
super(keyType);
links = new long[keys.length];
}
#if !VALUE_OBJECT
/**
* Helper constructor that allow to create a EnumMap from boxed values (it will unbox them)
* @param keys the keys that should be put into the EnumMap
* @param values the values that should be put into the EnumMap.
* @throws IllegalStateException if the keys and values do not match in lenght
*/
public LINKED_ENUM_MAP(T[] keys, CLASS_VALUE_TYPE[] values) {
if(keys.length <= 0) throw new IllegalArgumentException("Empty Array are not allowed");
if(keys.length != values.length) throw new IllegalArgumentException("Keys and Values have to be the same size");
keyType = keys[0].getDeclaringClass();
this.keys = getKeyUniverse(keyType);
this.values = NEW_VALUE_ARRAY(this.keys.length);
present = new long[((this.keys.length - 1) >> 6) + 1];
links = new long[this.keys.length];
putAll(keys, values);
}
#endif
/**
* Helper constructor that allow to create a EnumMap from unboxed values
* @param keys the keys that should be put into the map
* @param values the values that should be put into the map.
* @throws IllegalStateException if the keys and values do not match in lenght
*/
public LINKED_ENUM_MAP(T[] keys, VALUE_TYPE[] values) {
if(keys.length <= 0) throw new IllegalArgumentException("Empty Array are not allowed");
if(keys.length != values.length) throw new IllegalArgumentException("Keys and Values have to be the same size");
keyType = keys[0].getDeclaringClass();
this.keys = getKeyUniverse(keyType);
this.values = NEW_VALUE_ARRAY(this.keys.length);
present = new long[((this.keys.length - 1) >> 6) + 1];
links = new long[this.keys.length];
putAll(keys, values);
}
/**
* A Helper constructor that allows to create a EnumMap with exactly the same values as the provided map.
* @param map the values that should be present in the map
*/
public LINKED_ENUM_MAP(Map<? extends CLASS_TYPE, ? extends CLASS_VALUE_TYPE> map) {
if(map instanceof LINKED_ENUM_MAP) {
LINKED_ENUM_MAP KEY_VALUE_GENERIC_TYPE enumMap = (LINKED_ENUM_MAP KEY_VALUE_GENERIC_TYPE)map;
keyType = enumMap.keyType;
keys = enumMap.keys;
values = enumMap.values.clone();
present = enumMap.present.clone();
links = enumMap.links.clone();
size = enumMap.size;
}
else if(map instanceof ENUM_MAP) {
ENUM_MAP KEY_VALUE_GENERIC_TYPE enumMap = (ENUM_MAP KEY_VALUE_GENERIC_TYPE)map;
keyType = enumMap.keyType;
keys = enumMap.keys;
values = enumMap.values.clone();
present = enumMap.present.clone();
links = new long[keys.length];
for(int i = 0,m=keys.length;i<m;i++) {
if(isSet(i)) {
if(size == 0) {
firstIndex = lastIndex = i;
links[i] = -1L;
}
else {
links[lastIndex] ^= ((links[lastIndex] ^ (i & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
links[i] = ((lastIndex & 0xFFFFFFFFL) << 32) | 0xFFFFFFFFL;
lastIndex = i;
}
size++;
}
}
}
else if(map.isEmpty()) throw new IllegalArgumentException("Empty Maps are not allowed");
else {
keyType = map.keySet().iterator().next().getDeclaringClass();
this.keys = getKeyUniverse(keyType);
this.values = NEW_VALUE_ARRAY(keys.length);
present = new long[((keys.length - 1) >> 6) + 1];
links = new long[keys.length];
putAll(map);
}
}
/**
* A Type Specific Helper function that allows to create a new EnumMap with exactly the same values as the provided map.
* @param map the values that should be present in the map
*/
public LINKED_ENUM_MAP(MAP KEY_VALUE_GENERIC_TYPE map) {
if(map instanceof LINKED_ENUM_MAP) {
LINKED_ENUM_MAP KEY_VALUE_GENERIC_TYPE enumMap = (LINKED_ENUM_MAP KEY_VALUE_GENERIC_TYPE)map;
keyType = enumMap.keyType;
keys = enumMap.keys;
values = enumMap.values.clone();
present = enumMap.present.clone();
links = enumMap.links.clone();
size = enumMap.size;
}
else if(map instanceof ENUM_MAP) {
ENUM_MAP KEY_VALUE_GENERIC_TYPE enumMap = (ENUM_MAP KEY_VALUE_GENERIC_TYPE)map;
keyType = enumMap.keyType;
keys = enumMap.keys;
values = enumMap.values.clone();
present = enumMap.present.clone();
links = new long[keys.length];
for(int i = 0,m=keys.length;i<m;i++) {
if(isSet(i)) {
if(size == 0) {
firstIndex = lastIndex = i;
links[i] = -1L;
}
else {
links[lastIndex] ^= ((links[lastIndex] ^ (i & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
links[i] = ((lastIndex & 0xFFFFFFFFL) << 32) | 0xFFFFFFFFL;
lastIndex = i;
}
size++;
}
}
}
else if(map.isEmpty()) throw new IllegalArgumentException("Empty Maps are not allowed");
else {
keyType = map.keySet().iterator().next().getDeclaringClass();
this.keys = getKeyUniverse(keyType);
this.values = NEW_VALUE_ARRAY(keys.length);
present = new long[((keys.length - 1) >> 6) + 1];
links = new long[keys.length];
putAll(map);
}
}
@Override
public VALUE_TYPE putAndMoveToFirst(T key, VALUE_TYPE value) {
int index = key.ordinal();
if(isSet(index)) {
VALUE_TYPE result = values[index];
values[index] = value;
moveToFirstIndex(index);
return result;
}
set(index);
values[index] = value;
onNodeAdded(index);
moveToFirstIndex(index);
return getDefaultReturnValue();
}
@Override
public VALUE_TYPE putAndMoveToLast(T key, VALUE_TYPE value) {
int index = key.ordinal();
if(isSet(index)) {
VALUE_TYPE result = values[index];
values[index] = value;
moveToLastIndex(index);
return result;
}
set(index);
values[index] = value;
onNodeAdded(index);
moveToLastIndex(index);
return getDefaultReturnValue();
}
@Override
public boolean moveToFirst(T key) {
int index = key.ordinal();
if(isSet(index)) {
moveToFirstIndex(index);
return true;
}
return false;
}
@Override
public boolean moveToLast(T key) {
int index = key.ordinal();
if(isSet(index)) {
moveToLastIndex(index);
return true;
}
return false;
}
@Override
public VALUE_TYPE getAndMoveToFirst(T key) {
int index = key.ordinal();
if(!isSet(index)) return getDefaultReturnValue();
moveToFirstIndex(index);
return values[index];
}
@Override
public VALUE_TYPE getAndMoveToLast(T key) {
int index = key.ordinal();
if(!isSet(index)) return getDefaultReturnValue();
moveToLastIndex(index);
return values[index];
}
@Override
public LINKED_ENUM_MAP KEY_VALUE_GENERIC_TYPE copy() {
LINKED_ENUM_MAP KEY_VALUE_GENERIC_TYPE map = new LINKED_ENUM_MAPKV_BRACES(keyType);
map.size = size;
System.arraycopy(present, 0, map.present, 0, Math.min(present.length, map.present.length));
System.arraycopy(values, 0, map.values, 0, Math.min(values.length, map.values.length));
System.arraycopy(links, 0, map.links, 0, Math.min(links.length, map.links.length));
map.firstIndex = firstIndex;
map.lastIndex = lastIndex;
return map;
}
@Override
public T FIRST_ENTRY_KEY() {
if(size == 0) throw new NoSuchElementException();
return keys[firstIndex];
}
@Override
public T POLL_FIRST_ENTRY_KEY() {
if(size == 0) throw new NoSuchElementException();
int pos = firstIndex;
firstIndex = (int)links[pos];
if(0 <= firstIndex) links[firstIndex] |= 0xFFFFFFFF00000000L;
T result = keys[pos];
size--;
values[result.ordinal()] = EMPTY_VALUE;
return result;
}
@Override
public T LAST_ENTRY_KEY() {
if(size == 0) throw new NoSuchElementException();
return keys[lastIndex];
}
@Override
public T POLL_LAST_ENTRY_KEY() {
if(size == 0) throw new NoSuchElementException();
int pos = lastIndex;
lastIndex = (int)(links[pos] >>> 32);
if(0 <= lastIndex) links[lastIndex] |= 0xFFFFFFFFL;
T result = keys[pos];
size--;
values[result.ordinal()] = EMPTY_VALUE;
return result;
}
@Override
public VALUE_TYPE FIRST_ENTRY_VALUE() {
if(size == 0) throw new NoSuchElementException();
return values[firstIndex];
}
@Override
public VALUE_TYPE LAST_ENTRY_VALUE() {
if(size == 0) throw new NoSuchElementException();
return values[lastIndex];
}
@Override
public ObjectOrderedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> ENTRY_SET() {
if(entrySet == null) entrySet = new MapEntrySet();
return (ObjectOrderedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE>)entrySet;
}
@Override
public ORDERED_SET KEY_GENERIC_TYPE keySet() {
if(keySet == null) keySet = new KeySet();
return (ORDERED_SET KEY_GENERIC_TYPE)keySet;
}
@Override
public VALUE_COLLECTION VALUE_GENERIC_TYPE values() {
if(valuesC == null) valuesC = new Values();
return valuesC;
}
@Override
public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) {
int index = firstIndex;
while(index != -1){
action.accept(keys[index], values[index]);
index = (int)links[index];
}
}
@Override
public void clear() {
super.clear();
firstIndex = lastIndex = -1;
}
protected void moveToFirstIndex(int startPos) {
if(size == 1 || firstIndex == startPos) return;
if(lastIndex == startPos) {
lastIndex = (int)(links[startPos] >>> 32);
links[lastIndex] |= 0xFFFFFFFFL;
}
else {
long link = links[startPos];
int prev = (int)(link >>> 32);
int next = (int)link;
links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L);
}
links[firstIndex] ^= ((links[firstIndex] ^ ((startPos & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L);
links[startPos] = 0xFFFFFFFF00000000L | (firstIndex & 0xFFFFFFFFL);
firstIndex = startPos;
}
protected void moveToLastIndex(int startPos) {
if(size == 1 || lastIndex == startPos) return;
if(firstIndex == startPos) {
firstIndex = (int)links[startPos];
links[lastIndex] |= 0xFFFFFFFF00000000L;
}
else {
long link = links[startPos];
int prev = (int)(link >>> 32);
int next = (int)link;
links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L);
}
links[lastIndex] ^= ((links[lastIndex] ^ (startPos & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
links[startPos] = ((lastIndex & 0xFFFFFFFFL) << 32) | 0xFFFFFFFFL;
lastIndex = startPos;
}
@Override
protected void onNodeAdded(int pos) {
if(size == 0) {
firstIndex = lastIndex = pos;
links[pos] = -1L;
}
else {
links[lastIndex] ^= ((links[lastIndex] ^ (pos & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
links[pos] = ((lastIndex & 0xFFFFFFFFL) << 32) | 0xFFFFFFFFL;
lastIndex = pos;
}
}
@Override
protected void onNodeRemoved(int pos) {
if(size == 0) firstIndex = lastIndex = -1;
else if(firstIndex == pos) {
firstIndex = (int)links[pos];
if(0 <= firstIndex) links[firstIndex] |= 0xFFFFFFFF00000000L;
}
else if(lastIndex == pos) {
lastIndex = (int)(links[pos] >>> 32);
if(0 <= lastIndex) links[lastIndex] |= 0xFFFFFFFFL;
}
else {
long link = links[pos];
int prev = (int)(link >>> 32);
int next = (int)link;
links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L);
}
}
private class MapEntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE {
@Override
public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public boolean addAndMoveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public boolean moveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) {
return LINKED_ENUM_MAP.this.moveToFirst(o.ENTRY_KEY());
}
@Override
public boolean moveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) {
return LINKED_ENUM_MAP.this.moveToLast(o.ENTRY_KEY());
}
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE first() {
return new BasicEntryKV_BRACES(FIRST_ENTRY_KEY(), FIRST_ENTRY_VALUE());
}
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE last() {
return new BasicEntryKV_BRACES(LAST_ENTRY_KEY(), LAST_ENTRY_VALUE());
}
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirst() {
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(FIRST_ENTRY_KEY(), FIRST_ENTRY_VALUE());
POLL_FIRST_ENTRY_KEY();
return entry;
}
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLast() {
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(LAST_ENTRY_KEY(), LAST_ENTRY_VALUE());
POLL_LAST_ENTRY_KEY();
return entry;
}
@Override
public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> iterator() {
return new EntryIterator();
}
@Override
public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> iterator(MAP.Entry KEY_VALUE_GENERIC_TYPE fromElement) {
return new EntryIterator(fromElement.ENTRY_KEY());
}
@Override
public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> fastIterator() {
return new FastEntryIterator();
}
@Override
public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> fastIterator(T fromElement) {
return new FastEntryIterator(fromElement);
}
public MapEntrySet copy() { throw new UnsupportedOperationException(); }
@Override
public void forEach(Consumer<? super MAP.Entry KEY_VALUE_GENERIC_TYPE> action) {
int index = firstIndex;
while(index != -1){
action.accept(new ValueMapEntry(index));
index = (int)links[index];
}
}
@Override
public void fastForEach(Consumer<? super MAP.Entry KEY_VALUE_GENERIC_TYPE> action) {
MapEntry entry = new MapEntry();
int index = firstIndex;
while(index != -1){
entry.set(index);
action.accept(entry);
index = (int)links[index];
}
}
@Override
@Deprecated
public boolean contains(Object o) {
if(o instanceof Map.Entry) {
if(o instanceof MAP.Entry) {
MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o;
if(!keyType.isInstance(entry.ENTRY_KEY())) return false;
int index = ((T)entry.ENTRY_KEY()).ordinal();
if(index >= 0 && LINKED_ENUM_MAP.this.isSet(index)) return VALUE_EQUALS(entry.ENTRY_VALUE(), LINKED_ENUM_MAP.this.values[index]);
}
else {
Map.Entry<?, ?> entry = (Map.Entry<?, ?>)o;
if(!keyType.isInstance(entry.getKey())) return false;
int index = ((T)entry.getKey()).ordinal();
if(index >= 0 && LINKED_ENUM_MAP.this.isSet(index)) return Objects.equals(entry.getValue(), VALUE_TO_OBJ(LINKED_ENUM_MAP.this.values[index]));
}
}
return false;
}
@Override
@Deprecated
public boolean remove(Object o) {
if(o instanceof Map.Entry) {
if(o instanceof MAP.Entry) {
MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o;
return LINKED_ENUM_MAP.this.remove(entry.ENTRY_KEY(), entry.ENTRY_VALUE());
}
Map.Entry<?, ?> entry = (Map.Entry<?, ?>)o;
return LINKED_ENUM_MAP.this.remove(entry.getKey(), entry.getValue());
}
return false;
}
@Override
public int size() {
return LINKED_ENUM_MAP.this.size();
}
@Override
public void clear() {
LINKED_ENUM_MAP.this.clear();
}
}
private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE {
#if TYPE_OBJECT
@Override
@Deprecated
public boolean contains(Object e) {
return containsKey(e);
}
@Override
public boolean remove(Object o) {
int oldSize = size;
LINKED_ENUM_MAP.this.remove(o);
return size != oldSize;
}
#else
@Override
public boolean contains(T e) {
return containsKey(e);
}
@Override
public boolean remove(T o) {
int oldSize = size;
LINKED_ENUM_MAP.this.remove(o);
return size != oldSize;
}
#endif
@Override
public boolean add(T o) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAndMoveToFirst(T o) { throw new UnsupportedOperationException(); }
@Override
public boolean addAndMoveToLast(T o) { throw new UnsupportedOperationException(); }
@Override
public boolean moveToFirst(T o) {
return LINKED_ENUM_MAP.this.moveToFirst(o);
}
@Override
public boolean moveToLast(T o) {
return LINKED_ENUM_MAP.this.moveToLast(o);
}
@Override
public LIST_ITERATOR KEY_GENERIC_TYPE iterator() {
return new KeyIterator();
}
@Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator(T fromElement) {
return new KeyIterator(fromElement);
}
public KeySet copy() { throw new UnsupportedOperationException(); }
@Override
public int size() {
return LINKED_ENUM_MAP.this.size();
}
@Override
public void clear() {
LINKED_ENUM_MAP.this.clear();
}
@Override
public T FIRST_KEY() {
return FIRST_ENTRY_KEY();
}
@Override
public T POLL_FIRST_KEY() {
return POLL_FIRST_ENTRY_KEY();
}
@Override
public T LAST_KEY() {
return LAST_ENTRY_KEY();
}
@Override
public T POLL_LAST_KEY() {
return POLL_LAST_ENTRY_KEY();
}
#if TYPE_OBJECT
@Override
public void forEach(Consumer KEY_SUPER_GENERIC_TYPE action) {
int index = firstIndex;
while(index != -1){
action.accept(keys[index]);
index = (int)links[index];
}
}
#else
@Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
int index = firstIndex;
while(index != -1){
action.accept(keys[index]);
index = (int)links[index];
}
}
#endif
}
private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE {
#if VALUE_OBJECT
@Override
@Deprecated
public boolean contains(Object e) {
return containsValue(e);
}
#else
@Override
public boolean contains(VALUE_TYPE e) {
return containsValue(e);
}
#endif
@Override
public boolean add(VALUE_TYPE o) {
throw new UnsupportedOperationException();
}
@Override
public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() {
return new ValueIterator();
}
@Override
public int size() {
return LINKED_ENUM_MAP.this.size();
}
@Override
public void clear() {
LINKED_ENUM_MAP.this.clear();
}
#if VALUE_OBJECT
@Override
public void forEach(Consumer VALUE_SUPER_GENERIC_TYPE action) {
int index = firstIndex;
while(index != -1){
action.accept(values[index]);
index = (int)links[index];
}
}
#else
@Override
public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) {
int index = firstIndex;
while(index != -1){
action.accept(values[index]);
index = (int)links[index];
}
}
#endif
}
private class FastEntryIterator extends MapIterator implements ObjectListIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> {
MapEntry entry = new MapEntry();
public FastEntryIterator() {}
public FastEntryIterator(T from) {
super(from);
}
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE next() {
entry.index = nextEntry();
return entry;
}
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() {
entry.index = previousEntry();
return entry;
}
@Override
public void set(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); }
@Override
public void add(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); }
}
private class EntryIterator extends MapIterator implements ObjectListIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> {
MapEntry entry;
public EntryIterator() {}
public EntryIterator(T from) {
super(from);
}
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE next() {
return entry = new ValueMapEntry(nextEntry());
}
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() {
return entry = new ValueMapEntry(previousEntry());
}
@Override
public void remove() {
super.remove();
entry.index = -1;
}
@Override
public void set(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); }
@Override
public void add(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); }
}
private class KeyIterator extends MapIterator implements LIST_ITERATOR KEY_GENERIC_TYPE {
public KeyIterator() {}
public KeyIterator(T from) {
super(from);
}
@Override
public T PREVIOUS() {
return keys[previousEntry()];
}
@Override
public T NEXT() {
return keys[nextEntry()];
}
@Override
public void set(T e) { throw new UnsupportedOperationException(); }
@Override
public void add(T e) { throw new UnsupportedOperationException(); }
}
private class ValueIterator extends MapIterator implements VALUE_LIST_ITERATOR VALUE_GENERIC_TYPE {
public ValueIterator() {}
@Override
public VALUE_TYPE VALUE_PREVIOUS() {
return values[previousEntry()];
}
@Override
public VALUE_TYPE VALUE_NEXT() {
return values[nextEntry()];
}
@Override
public void set(VALUE_TYPE e) { throw new UnsupportedOperationException(); }
@Override
public void add(VALUE_TYPE e) { throw new UnsupportedOperationException(); }
}
private class MapIterator {
int previous = -1;
int next = -1;
int current = -1;
int index = 0;
MapIterator() {
next = firstIndex;
}
MapIterator(T from) {
previous = from.ordinal() - 1;
index = from.ordinal();
next = from.ordinal();
if(!isSet(index)) throw new NoSuchElementException();
}
public boolean hasNext() {
return next != -1;
}
public boolean hasPrevious() {
return previous != -1;
}
public int nextIndex() {
ensureIndexKnown();
return index;
}
public int previousIndex() {
ensureIndexKnown();
return index - 1;
}
public void remove() {
if(current == -1) throw new IllegalStateException();
ensureIndexKnown();
if(current == previous) {
index--;
previous = (int)(links[current] >>> 32);
}
else next = (int)links[current];
size--;
if(previous == -1) firstIndex = next;
else links[previous] ^= ((links[previous] ^ (next & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
if (next == -1) lastIndex = previous;
else links[next] ^= ((links[next] ^ ((previous & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L);
values[current] = EMPTY_VALUE;
present[current >> 6] &= ~(1L << current);
current = -1;
}
public int previousEntry() {
if(!hasPrevious()) throw new NoSuchElementException();
current = previous;
previous = (int)(links[current] >> 32);
next = current;
if(index >= 0) index--;
return current;
}
public int nextEntry() {
if(!hasNext()) throw new NoSuchElementException();
current = next;
next = (int)(links[current]);
previous = current;
if(index >= 0) index++;
return current;
}
private void ensureIndexKnown() {
if(index == -1) {
if(previous == -1) {
index = 0;
}
else if(next == -1) {
index = size;
}
else {
index = 1;
for(int pos = firstIndex;pos != previous;pos = (int)links[pos], index++);
}
}
}
}
protected class ValueMapEntry extends MapEntry {
protected KEY_TYPE key;
protected VALUE_TYPE value;
public ValueMapEntry(int index) {
super(index);
key = keys[index];
value = values[index];
}
@Override
public KEY_TYPE ENTRY_KEY() {
return key;
}
@Override
public VALUE_TYPE ENTRY_VALUE() {
return value;
}
@Override
public VALUE_TYPE setValue(VALUE_TYPE value) {
this.value = value;
return super.setValue(value);
}
}
protected class MapEntry implements MAP.Entry KEY_VALUE_GENERIC_TYPE, Map.Entry<CLASS_TYPE, CLASS_VALUE_TYPE> {
public int index = -1;
public MapEntry() {}
public MapEntry(int index) {
this.index = index;
}
void set(int index) {
this.index = index;
}
@Override
public KEY_TYPE ENTRY_KEY() {
return keys[index];
}
@Override
public VALUE_TYPE ENTRY_VALUE() {
return values[index];
}
@Override
public VALUE_TYPE setValue(VALUE_TYPE value) {
VALUE_TYPE oldValue = values[index];
values[index] = value;
return oldValue;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Map.Entry) {
if(obj instanceof MAP.Entry) {
MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)obj;
return KEY_EQUALS(ENTRY_KEY(), entry.ENTRY_KEY()) && VALUE_EQUALS(ENTRY_VALUE(), entry.ENTRY_VALUE());
}
Map.Entry<?, ?> entry = (Map.Entry<?, ?>)obj;
Object key = entry.getKey();
Object value = entry.getValue();
#if TYPE_OBJECT && VALUE_OBJECT
return KEY_EQUALS(ENTRY_KEY(), key) && VALUE_EQUALS(ENTRY_VALUE(), value);
#else if TYPE_OBJECT
return value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(ENTRY_KEY(), key) && VALUE_EQUALS(ENTRY_VALUE(), CLASS_TO_VALUE(value));
#else if VALUE_OBJECT
return key instanceof CLASS_TYPE && KEY_EQUALS(ENTRY_KEY(), CLASS_TO_KEY(key)) && VALUE_EQUALS(ENTRY_VALUE(), value);
#else
return key instanceof CLASS_TYPE && value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(ENTRY_KEY(), CLASS_TO_KEY(key)) && VALUE_EQUALS(ENTRY_VALUE(), CLASS_TO_VALUE(value));
#endif
}
return false;
}
@Override
public int hashCode() {
return KEY_TO_HASH(ENTRY_KEY()) ^ VALUE_TO_HASH(ENTRY_VALUE());
}
@Override
public String toString() {
return KEY_TO_STRING(ENTRY_KEY()) + "=" + VALUE_TO_STRING(ENTRY_VALUE());
}
}
}
@@ -0,0 +1,95 @@
package speiger.src.collections.PACKAGE.maps.interfaces;
import java.util.concurrent.ConcurrentMap;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
/**
* A type specific ConcurrentMap interface that reduces boxing/unboxing.
* Since the interface adds nothing new. It is there just for completion sake.
* @Type(T)
* @ValueType(V)
*/
public interface CONCURRENT_MAP KEY_VALUE_GENERIC_TYPE extends ConcurrentMap<CLASS_TYPE, CLASS_VALUE_TYPE>, MAP KEY_VALUE_GENERIC_TYPE
{
@Override
@Primitive
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);
}
@Override
@Primitive
public default CLASS_VALUE_TYPE computeIfAbsent(CLASS_TYPE key, Function<? super CLASS_TYPE, ? extends CLASS_VALUE_TYPE> mappingFunction) {
return MAP.super.computeIfAbsent(key, mappingFunction);
}
@Override
@Primitive
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);
}
@Override
@Primitive
public default void forEach(BiConsumer<? super CLASS_TYPE, ? super CLASS_VALUE_TYPE> action) {
MAP.super.forEach(action);
}
@Override
@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) {
return MAP.super.merge(key, value, mappingFunction);
}
#if TYPE_OBJECT && VALUE_OBJECT
@Override
public CLASS_VALUE_TYPE getOrDefault(Object key, CLASS_VALUE_TYPE defaultValue);
@Override
public CLASS_VALUE_TYPE putIfAbsent(CLASS_TYPE key, CLASS_VALUE_TYPE value);
@Override
public boolean remove(Object key, Object value);
@Override
public boolean replace(CLASS_TYPE key, CLASS_VALUE_TYPE oldValue, CLASS_VALUE_TYPE newValue);
@Override
public CLASS_VALUE_TYPE replace(CLASS_TYPE key, CLASS_VALUE_TYPE value);
#else
@Primitive
@Override
public default CLASS_VALUE_TYPE getOrDefault(Object key, CLASS_VALUE_TYPE defaultValue) {
return MAP.super.getOrDefault(key, defaultValue);
}
@Override
@Primitive
public default CLASS_VALUE_TYPE putIfAbsent(CLASS_TYPE key, CLASS_VALUE_TYPE value) {
return MAP.super.putIfAbsent(key, value);
}
@Override
@Deprecated
public default boolean remove(Object key, Object value) {
return MAP.super.remove(key, value);
}
@Override
@Deprecated
public default boolean replace(CLASS_TYPE key, CLASS_VALUE_TYPE oldValue, CLASS_VALUE_TYPE newValue) {
return MAP.super.replace(key, oldValue, newValue);
}
@Override
@Deprecated
public default CLASS_VALUE_TYPE replace(CLASS_TYPE key, CLASS_VALUE_TYPE value) {
return MAP.super.replace(key, value);
}
#endif
@Override
@Deprecated
public default void replaceAll(BiFunction<? super CLASS_TYPE, ? super CLASS_VALUE_TYPE, ? extends CLASS_VALUE_TYPE> mappingFunction) {
MAP.super.replaceAll(mappingFunction);
}
}
@@ -2,6 +2,9 @@ package speiger.src.collections.PACKAGE.maps.interfaces;
import java.util.NavigableMap; import java.util.NavigableMap;
import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET; import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET;
#if MAPS_FEATURE
import speiger.src.collections.PACKAGE.utils.maps.MAPS;
#endif
/** /**
* A Type Specific Navigable Map interface with a couple helper methods * A Type Specific Navigable Map interface with a couple helper methods
@@ -10,6 +13,8 @@ import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET;
*/ */
public interface NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE extends SORTED_MAP KEY_VALUE_GENERIC_TYPE, NavigableMap<CLASS_TYPE, CLASS_VALUE_TYPE> public interface NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE extends SORTED_MAP KEY_VALUE_GENERIC_TYPE, NavigableMap<CLASS_TYPE, CLASS_VALUE_TYPE>
{ {
@Override
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE copy();
/** @return a Type Specific desendingMap */ /** @return a Type Specific desendingMap */
@Override @Override
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap(); public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap();
@@ -31,7 +36,34 @@ public interface NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE extends SORTED_MAP KEY_VAL
/** @return a Type Specific pollLastEntry */ /** @return a Type Specific pollLastEntry */
@Override @Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLastEntry(); public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLastEntry();
/** @return a Type Specific Navigable Key Set */
@Override
public NAVIGABLE_SET KEY_GENERIC_TYPE keySet();
#if MAPS_FEATURE
/**
* Creates a Wrapped NavigableMap that is Synchronized
* @return a new NavigableMap that is synchronized
* @see MAPS#synchronize
*/
public default NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE synchronize() { return MAPS.synchronize(this); }
/**
* Creates a Wrapped NavigableMap that is Synchronized
* @param mutex is the controller of the synchronization block
* @return a new NavigableMap Wrapper that is synchronized
* @see MAPS#synchronize
*/
public default NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE synchronize(Object mutex) { return MAPS.synchronize(this, mutex); }
/**
* Creates a Wrapped NavigableMap that is unmodifiable
* @return a new NavigableMap Wrapper that is unmodifiable
* @see MAPS#unmodifiable
*/
public default NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE unmodifiable() { return MAPS.unmodifiable(this); }
#endif
#if !TYPE_OBJECT #if !TYPE_OBJECT
/** /**
* A Type Specific SubMap method to reduce boxing/unboxing * A Type Specific SubMap method to reduce boxing/unboxing
@@ -182,13 +214,13 @@ public interface NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE extends SORTED_MAP KEY_VAL
default NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(CLASS_TYPE fromKey) { return tailMap(OBJ_TO_KEY(fromKey), true); } default NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(CLASS_TYPE fromKey) { return tailMap(OBJ_TO_KEY(fromKey), true); }
#else #else
@Override @Override
default MAP.Entry KEY_VALUE_GENERIC_TYPE lowerEntry(CLASS_TYPE key) { return lowerEntry(OBJ_TO_KEY(key)); } MAP.Entry KEY_VALUE_GENERIC_TYPE lowerEntry(CLASS_TYPE key);
@Override @Override
default MAP.Entry KEY_VALUE_GENERIC_TYPE floorEntry(CLASS_TYPE key) { return floorEntry(OBJ_TO_KEY(key)); } MAP.Entry KEY_VALUE_GENERIC_TYPE floorEntry(CLASS_TYPE key);
@Override @Override
default MAP.Entry KEY_VALUE_GENERIC_TYPE ceilingEntry(CLASS_TYPE key) { return ceilingEntry(OBJ_TO_KEY(key)); } MAP.Entry KEY_VALUE_GENERIC_TYPE ceilingEntry(CLASS_TYPE key);
@Override @Override
default MAP.Entry KEY_VALUE_GENERIC_TYPE higherEntry(CLASS_TYPE key) { return higherEntry(OBJ_TO_KEY(key)); } MAP.Entry KEY_VALUE_GENERIC_TYPE higherEntry(CLASS_TYPE key);
@Override @Override
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(CLASS_TYPE fromKey, boolean fromInclusive, CLASS_TYPE toKey, boolean toInclusive); public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(CLASS_TYPE fromKey, boolean fromInclusive, CLASS_TYPE toKey, boolean toInclusive);
@@ -0,0 +1,149 @@
package speiger.src.collections.PACKAGE.maps.interfaces;
#if MAPS_FEATURE
import speiger.src.collections.PACKAGE.utils.maps.MAPS;
#endif
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.sets.ORDERED_SET;
#endif
import speiger.src.collections.objects.collections.ObjectBidirectionalIterator;
import speiger.src.collections.objects.sets.ObjectOrderedSet;
/**
* A Special Map Interface giving Access to some really usefull functions
* The Idea behind this interface is to allow access to functions that give control to the Order of elements.
* Since Linked implementations as examples can be reordered outside of the Insertion Order.
* This interface provides basic access to such functions while also providing some Sorted/NaivgableMap implementations that still fit into here.
*
* @Type(T)
* @ValueType(V)
*/
public interface ORDERED_MAP KEY_VALUE_GENERIC_TYPE extends MAP KEY_VALUE_GENERIC_TYPE
{
/**
* A customized put method that allows you to insert into the first index.
* @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 putAndMoveToFirst(KEY_TYPE key, VALUE_TYPE value);
/**
* A customized put method that allows you to insert into the last index. (This may be nessesary depending on the implementation)
* @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 putAndMoveToLast(KEY_TYPE key, VALUE_TYPE value);
/**
* A specific move method to move a given key/value to the first index.
* @param key that should be moved to the first index
* @return true if the value was moved.
* @note returns false if the value was not present in the first place
*/
public boolean moveToFirst(KEY_TYPE key);
/**
* A specific move method to move a given key/value to the last index.
* @param key that should be moved to the first last
* @return true if the value was moved.
* @note returns false if the value was not present in the first place
*/
public boolean moveToLast(KEY_TYPE key);
/**
* A Specific get method that allows to move teh given key/value int the first index.
* @param key that is searched for
* @return the given value for the requested key or default return value
*/
public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key);
/**
* A Specific get method that allows to move teh given key/value int the last index.
* @param key that is searched for
* @return the given value for the requested key or default return value
*/
public VALUE_TYPE getAndMoveToLast(KEY_TYPE key);
/**
* A method to get the first Key of a Map.
* @return the first key in the map
*/
public KEY_TYPE FIRST_ENTRY_KEY();
/**
* A method to get and remove the first Key of a Map.
* @return the first key in the map
*/
public KEY_TYPE POLL_FIRST_ENTRY_KEY();
/**
* A method to get the last Key of a Map.
* @return the last key in the map
*/
public KEY_TYPE LAST_ENTRY_KEY();
/**
* A method to get and remove the last Key of a Map.
* @return the last key in the map
*/
public KEY_TYPE POLL_LAST_ENTRY_KEY();
/**
* A method to get the first Value of a Map.
* @return the first key in the map
*/
public VALUE_TYPE FIRST_ENTRY_VALUE();
/**
* A method to get the last Value of a Map.
* @return the last key in the map
*/
public VALUE_TYPE LAST_ENTRY_VALUE();
@Override
public ORDERED_MAP KEY_VALUE_GENERIC_TYPE copy();
@Override
public ORDERED_SET KEY_GENERIC_TYPE keySet();
@Override
public ObjectOrderedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> ENTRY_SET();
#if MAPS_FEATURE
/**
* Creates a Wrapped SortedMap that is Synchronized
* @return a new SortedMap that is synchronized
* @see MAPS#synchronize
*/
@Override
public default ORDERED_MAP KEY_VALUE_GENERIC_TYPE synchronize() { return MAPS.synchronize(this); }
/**
* Creates a Wrapped SortedMap that is Synchronized
* @param mutex is the controller of the synchronization block
* @return a new SortedMap Wrapper that is synchronized
* @see MAPS#synchronize
*/
@Override
public default ORDERED_MAP KEY_VALUE_GENERIC_TYPE synchronize(Object mutex) { return MAPS.synchronize(this, mutex); }
/**
* Creates a Wrapped SortedMap that is unmodifiable
* @return a new SortedMap Wrapper that is unmodifiable
* @see MAPS#unmodifiable
*/
@Override
public default ORDERED_MAP KEY_VALUE_GENERIC_TYPE unmodifiable() { return MAPS.unmodifiable(this); }
#endif
/**
* Fast Ordered Entry Set that allows for a faster Entry Iterator by recycling the Entry Object and just exchanging 1 internal value
* @Type(T)
* @ValueType(V)
*/
interface FastOrderedSet KEY_VALUE_GENERIC_TYPE extends MAP.FastEntrySet KEY_VALUE_GENERIC_TYPE, ObjectOrderedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> {
@Override
public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> fastIterator();
/**
* Fast iterator that recycles the given Entry object to improve speed and reduce object allocation
* @param fromElement that is going to be started from.
* @return a improved iterator that starts from the desired element
*/
public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> fastIterator(KEY_TYPE fromElement);
}
}
@@ -9,8 +9,13 @@ import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
#endif #endif
import speiger.src.collections.PACKAGE.sets.SET; import speiger.src.collections.PACKAGE.sets.SORTED_SET;
#if MAPS_FEATURE
import speiger.src.collections.PACKAGE.utils.maps.MAPS;
#endif
#if !TYPE_OBJECT
import speiger.src.collections.objects.sets.ObjectSortedSet; import speiger.src.collections.objects.sets.ObjectSortedSet;
#endif
import speiger.src.collections.objects.collections.ObjectBidirectionalIterator; import speiger.src.collections.objects.collections.ObjectBidirectionalIterator;
/** /**
@@ -18,68 +23,46 @@ import speiger.src.collections.objects.collections.ObjectBidirectionalIterator;
* *
* @Type(T) * @Type(T)
* @ValueType(V) * @ValueType(V)
* @note ORDERED_MAP is only extended until 0.6.0 for Compat reasons.
* The supported classes already implement ORDERED_MAP directly and will remove SORTED_MAP implementations in favor of ORDERED_MAP instead
*/ */
public interface SORTED_MAP KEY_VALUE_GENERIC_TYPE extends SortedMap<CLASS_TYPE, CLASS_VALUE_TYPE>, MAP KEY_VALUE_GENERIC_TYPE public interface SORTED_MAP KEY_VALUE_GENERIC_TYPE extends SortedMap<CLASS_TYPE, CLASS_VALUE_TYPE>, MAP KEY_VALUE_GENERIC_TYPE
{ {
/**
* A customized put method that allows you to insert into the first index.
* @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)
* @note some implementations do not support this method
*/
public VALUE_TYPE putAndMoveToFirst(KEY_TYPE key, VALUE_TYPE value);
/**
* A customized put method that allows you to insert into the last index. (This may be nessesary depending on the implementation)
* @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)
* @note some implementations do not support this method
*/
public VALUE_TYPE putAndMoveToLast(KEY_TYPE key, VALUE_TYPE value);
/**
* A specific move method to move a given key/value to the first index.
* @param key that should be moved to the first index
* @return true if the value was moved.
* @note returns false if the value was not present in the first place
* @note some implementations do not support this method
*/
public boolean moveToFirst(KEY_TYPE key);
/**
* A specific move method to move a given key/value to the last index.
* @param key that should be moved to the first last
* @return true if the value was moved.
* @note returns false if the value was not present in the first place
* @note some implementations do not support this method
*/
public boolean moveToLast(KEY_TYPE key);
/**
* A Specific get method that allows to move teh given key/value int the first index.
* @param key that is searched for
* @return the given value for the requested key or default return value
* @note some implementations do not support this method
*/
public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key);
/**
* A Specific get method that allows to move teh given key/value int the last index.
* @param key that is searched for
* @return the given value for the requested key or default return value
* @note some implementations do not support this method
*/
public VALUE_TYPE getAndMoveToLast(KEY_TYPE key);
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator(); public COMPARATOR KEY_GENERIC_TYPE comparator();
@Override @Override
public SET KEY_GENERIC_TYPE keySet(); public SORTED_MAP KEY_VALUE_GENERIC_TYPE copy();
@Override
public SORTED_SET KEY_GENERIC_TYPE keySet();
@Override @Override
public VALUE_COLLECTION VALUE_GENERIC_TYPE values(); public VALUE_COLLECTION VALUE_GENERIC_TYPE values();
#if MAPS_FEATURE
/**
* Creates a Wrapped SortedMap that is Synchronized
* @return a new SortedMap that is synchronized
* @see MAPS#synchronize
*/
public default SORTED_MAP KEY_VALUE_GENERIC_TYPE synchronize() { return MAPS.synchronize(this); }
/**
* Creates a Wrapped SortedMap that is Synchronized
* @param mutex is the controller of the synchronization block
* @return a new SortedMap Wrapper that is synchronized
* @see MAPS#synchronize
*/
public default SORTED_MAP KEY_VALUE_GENERIC_TYPE synchronize(Object mutex) { return MAPS.synchronize(this, mutex); }
/**
* Creates a Wrapped SortedMap that is unmodifiable
* @return a new SortedMap Wrapper that is unmodifiable
* @see MAPS#unmodifiable
*/
public default SORTED_MAP KEY_VALUE_GENERIC_TYPE unmodifiable() { return MAPS.unmodifiable(this); }
#endif
#if !TYPE_OBJECT #if !TYPE_OBJECT
/** /**
* A Type Specific SubMap method to reduce boxing/unboxing * A Type Specific SubMap method to reduce boxing/unboxing
@@ -178,11 +161,11 @@ public interface SORTED_MAP KEY_VALUE_GENERIC_TYPE extends SortedMap<CLASS_TYPE,
public VALUE_TYPE LAST_ENTRY_VALUE(); public VALUE_TYPE LAST_ENTRY_VALUE();
@Override @Override
public default SORTED_MAP KEY_VALUE_GENERIC_TYPE subMap(CLASS_TYPE fromKey, CLASS_TYPE toKey) { return subMap(OBJ_TO_KEY(fromKey), OBJ_TO_KEY(toKey)); } public SORTED_MAP KEY_VALUE_GENERIC_TYPE subMap(CLASS_TYPE fromKey, CLASS_TYPE toKey);
@Override @Override
public default SORTED_MAP KEY_VALUE_GENERIC_TYPE headMap(CLASS_TYPE toKey) { return headMap(OBJ_TO_KEY(toKey)); } public SORTED_MAP KEY_VALUE_GENERIC_TYPE headMap(CLASS_TYPE toKey);
@Override @Override
public default SORTED_MAP KEY_VALUE_GENERIC_TYPE tailMap(CLASS_TYPE fromKey) { return tailMap(OBJ_TO_KEY(fromKey)); } public SORTED_MAP KEY_VALUE_GENERIC_TYPE tailMap(CLASS_TYPE fromKey);
#endif #endif
/** /**
@@ -193,6 +176,11 @@ public interface SORTED_MAP KEY_VALUE_GENERIC_TYPE extends SortedMap<CLASS_TYPE,
interface FastSortedSet KEY_VALUE_GENERIC_TYPE extends MAP.FastEntrySet KEY_VALUE_GENERIC_TYPE, ObjectSortedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> { interface FastSortedSet KEY_VALUE_GENERIC_TYPE extends MAP.FastEntrySet KEY_VALUE_GENERIC_TYPE, ObjectSortedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> {
@Override @Override
public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> fastIterator(); public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> fastIterator();
/**
* Fast iterator that recycles the given Entry object to improve speed and reduce object allocation
* @param fromElement that is going to be started from.
* @return a improved iterator that starts from the desired element
*/
public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> fastIterator(KEY_TYPE fromElement); public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> fastIterator(KEY_TYPE fromElement);
} }
} }
@@ -0,0 +1,166 @@
package speiger.src.collections.PACKAGE.misc.pairs;
#if IMMUTABLE_PAIR
import speiger.src.collections.PACKAGE.misc.pairs.impl.IMMUTABLE_PAIR;
#endif
#if MUTABLE_PAIR
import speiger.src.collections.PACKAGE.misc.pairs.impl.MUTABLE_PAIR;
#endif
/**
* Key Value Pair Interface that allows to reduce boxing/unboxing.
* @Type(T)
* @ValueType(V)
*/
public interface PAIR KEY_VALUE_GENERIC_TYPE
{
#if IMMUTABLE_PAIR
/**
* Empty Reference for Immutable Pairs
*/
public static final PAIR NO_KV_GENERIC_TYPE EMPTY = new IMMUTABLE_PAIRKV_BRACES();
/**
* @Type(T)
* @ValueType(V)
* @return empty Immutable Pair
*/
public static GENERIC_KEY_VALUE_BRACES PAIR KEY_VALUE_GENERIC_TYPE of() {
#if TYPE_OBJECT || VALUE_OBJECT
return (PAIR KEY_VALUE_GENERIC_TYPE)EMPTY;
#else
return EMPTY;
#endif
}
/**
* @param key the key that should be in the pair
* @Type(T)
* @ValueType(V)
* @return Immutable Pair of Key
*/
public static GENERIC_KEY_VALUE_BRACES PAIR KEY_VALUE_GENERIC_TYPE ofKey(KEY_TYPE key) {
return new IMMUTABLE_PAIRKV_BRACES(key, EMPTY_VALUE);
}
/**
* @param value the value that should be in the pair
* @Type(T)
* @ValueType(V)
* @return Immutable Pair of Value
*/
public static GENERIC_KEY_VALUE_BRACES PAIR KEY_VALUE_GENERIC_TYPE ofValue(VALUE_TYPE value) {
return new IMMUTABLE_PAIRKV_BRACES(EMPTY_KEY_VALUE, value);
}
/**
* @param key the key that should be in the pair
* @param value the value that should be in the pair
* @Type(T)
* @ValueType(V)
* @return Immutable Pair of key and value
*/
public static GENERIC_KEY_VALUE_BRACES PAIR KEY_VALUE_GENERIC_TYPE of(KEY_TYPE key, VALUE_TYPE value) {
return new IMMUTABLE_PAIRKV_BRACES(key, value);
}
/**
* @param pair the Pair that should be immutably copied
* @Type(T)
* @ValueType(V)
* @return a Immutable Copy of the Provided Pair
*/
public static GENERIC_KEY_VALUE_BRACES PAIR KEY_VALUE_GENERIC_TYPE of(PAIR KEY_VALUE_GENERIC_TYPE pair) {
return new IMMUTABLE_PAIRKV_BRACES(pair.ENTRY_KEY(), pair.ENTRY_VALUE());
}
#endif
#if MUTABLE_PAIR
/**
* @Type(T)
* @ValueType(V)
* @return empty Mutable Pair
*/
public static GENERIC_KEY_VALUE_BRACES PAIR KEY_VALUE_GENERIC_TYPE mutable() {
return new MUTABLE_PAIRKV_BRACES();
}
/**
* @param key the key that should be in the pair
* @Type(T)
* @ValueType(V)
* @return Mutable Pair of key
*/
public static GENERIC_KEY_VALUE_BRACES PAIR KEY_VALUE_GENERIC_TYPE mutableKey(KEY_TYPE key) {
return new MUTABLE_PAIRKV_BRACES(key, EMPTY_VALUE);
}
/**
* @param value the value that should be in the pair
* @Type(T)
* @ValueType(V)
* @return Mutable Pair of value
*/
public static GENERIC_KEY_VALUE_BRACES PAIR KEY_VALUE_GENERIC_TYPE mutableValue(VALUE_TYPE value) {
return new MUTABLE_PAIRKV_BRACES(EMPTY_KEY_VALUE, value);
}
/**
* @param key the key that should be in the pair
* @param value the value that should be in the pair
* @Type(T)
* @ValueType(V)
* @return Mutable Pair of key and value
*/
public static GENERIC_KEY_VALUE_BRACES PAIR KEY_VALUE_GENERIC_TYPE mutable(KEY_TYPE key, VALUE_TYPE value) {
return new MUTABLE_PAIRKV_BRACES(key, value);
}
/**
* @param pair the Pair that should be copied
* @Type(T)
* @ValueType(V)
* @return a Mutable Copy of the Provided Pair
*/
public static GENERIC_KEY_VALUE_BRACES PAIR KEY_VALUE_GENERIC_TYPE mutable(PAIR KEY_VALUE_GENERIC_TYPE pair) {
return new MUTABLE_PAIRKV_BRACES(pair.ENTRY_KEY(), pair.ENTRY_VALUE());
}
#endif
/**
* Sets the Key of the Pair.
* @param key the key that should be set.
* @return self or a new Pair instance with the new key.
*/
public PAIR KEY_VALUE_GENERIC_TYPE KEY_ENTRY(KEY_TYPE key);
/**
* @return the Key of the Pair
*/
public KEY_TYPE ENTRY_KEY();
/**
* Sets the Value of the Pair.
* @param value the value that should be set.
* @return self or a new Pair instance with the new value.
*/
public PAIR KEY_VALUE_GENERIC_TYPE VALUE_ENTRY(VALUE_TYPE value);
/**
* @return the Value of the Pair
*/
public VALUE_TYPE ENTRY_VALUE();
/**
* Sets key and value of the Pair
* @param key the key that should be set.
* @param value the value that should be set.
* @return self or a new Pair instance with the new key and value.
*/
public PAIR KEY_VALUE_GENERIC_TYPE set(KEY_TYPE key, VALUE_TYPE value);
/**
* Clones the Pair if it is mutable.
* @return a New Mutable Instance if it is mutable
*/
public PAIR KEY_VALUE_GENERIC_TYPE shallowCopy();
}
@@ -0,0 +1,84 @@
package speiger.src.collections.PACKAGE.misc.pairs.impl;
#if TYPE_OBJECT || VALUE_OBJECT
import java.util.Objects;
#endif
import speiger.src.collections.PACKAGE.misc.pairs.PAIR;
/**
* Mutable Pair Implementation that
* @Type(T)
* @ValueType(V)
*/
public class IMMUTABLE_PAIR KEY_VALUE_GENERIC_TYPE implements PAIR KEY_VALUE_GENERIC_TYPE
{
protected final KEY_TYPE key;
protected final VALUE_TYPE value;
/**
* Default Constructor
*/
public IMMUTABLE_PAIR() {
this(EMPTY_KEY_VALUE, EMPTY_VALUE);
}
/**
* Key/Value Constructur
* @param key the key of the Pair
* @param value the value of the Pair
*/
public IMMUTABLE_PAIR(KEY_TYPE key, VALUE_TYPE value) {
this.key = key;
this.value = value;
}
@Override
public PAIR KEY_VALUE_GENERIC_TYPE KEY_ENTRY(KEY_TYPE key) {
return new IMMUTABLE_PAIRKV_BRACES(key, value);
}
@Override
public KEY_TYPE ENTRY_KEY() {
return key;
}
@Override
public PAIR KEY_VALUE_GENERIC_TYPE VALUE_ENTRY(VALUE_TYPE value) {
return new IMMUTABLE_PAIRKV_BRACES(key, value);
}
@Override
public VALUE_TYPE ENTRY_VALUE() {
return value;
}
@Override
public PAIR KEY_VALUE_GENERIC_TYPE set(KEY_TYPE key, VALUE_TYPE value) {
return new IMMUTABLE_PAIRKV_BRACES(key, value);
}
@Override
public PAIR KEY_VALUE_GENERIC_TYPE shallowCopy() {
return this;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof PAIR) {
PAIR KEY_VALUE_GENERIC_TYPE entry = (PAIR KEY_VALUE_GENERIC_TYPE)obj;
return KEY_EQUALS(key, entry.ENTRY_KEY()) && VALUE_EQUALS(value, entry.ENTRY_VALUE());
}
return false;
}
@Override
public int hashCode() {
return KEY_TO_HASH(key) ^ VALUE_TO_HASH(value);
}
@Override
public String toString() {
return KEY_TO_STRING(key) + "->" + VALUE_TO_STRING(value);
}
}
@@ -0,0 +1,88 @@
package speiger.src.collections.PACKAGE.misc.pairs.impl;
#if TYPE_OBJECT || VALUE_OBJECT
import java.util.Objects;
#endif
import speiger.src.collections.PACKAGE.misc.pairs.PAIR;
/**
* Mutable Pair Implementation that
* @Type(T)
* @ValueType(V)
*/
public class MUTABLE_PAIR KEY_VALUE_GENERIC_TYPE implements PAIR KEY_VALUE_GENERIC_TYPE
{
protected KEY_TYPE key;
protected VALUE_TYPE value;
/**
* Default Constructor
*/
public MUTABLE_PAIR() {}
/**
* Key/Value Constructur
* @param key the key of the Pair
* @param value the value of the Pair
*/
public MUTABLE_PAIR(KEY_TYPE key, VALUE_TYPE value) {
this.key = key;
this.value = value;
}
@Override
public PAIR KEY_VALUE_GENERIC_TYPE KEY_ENTRY(KEY_TYPE key) {
this.key = key;
return this;
}
@Override
public KEY_TYPE ENTRY_KEY() {
return key;
}
@Override
public PAIR KEY_VALUE_GENERIC_TYPE VALUE_ENTRY(VALUE_TYPE value) {
this.value = value;
return this;
}
@Override
public VALUE_TYPE ENTRY_VALUE() {
return value;
}
@Override
public PAIR KEY_VALUE_GENERIC_TYPE set(KEY_TYPE key, VALUE_TYPE value) {
this.key = key;
this.value = value;
return this;
}
@Override
public PAIR KEY_VALUE_GENERIC_TYPE shallowCopy() {
return PAIR.mutable(key, value);
}
@Override
public boolean equals(Object obj) {
if(obj instanceof PAIR) {
PAIR KEY_VALUE_GENERIC_TYPE entry = (PAIR KEY_VALUE_GENERIC_TYPE)obj;
return KEY_EQUALS(key, entry.ENTRY_KEY()) && VALUE_EQUALS(value, entry.ENTRY_VALUE());
}
return false;
}
@Override
public int hashCode() {
return KEY_TO_HASH(key) ^ VALUE_TO_HASH(value);
}
@Override
public String toString() {
return KEY_TO_STRING(key) + "->" + VALUE_TO_STRING(value);
}
}
@@ -0,0 +1,46 @@
package speiger.src.collections.PACKAGE.queues;
#if TYPE_OBJECT
import java.util.Objects;
#endif
import java.util.StringJoiner;
/**
* Helper class that implements all the essential methods for the PriorityQueues
* @Type(T)
*/
public abstract class ABSTRACT_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_QUEUE KEY_GENERIC_TYPE
{
@Override
public boolean equals(Object obj) {
if(obj instanceof PRIORITY_QUEUE) {
PRIORITY_QUEUE KEY_GENERIC_TYPE queue = (PRIORITY_QUEUE KEY_GENERIC_TYPE)obj;
if(queue.size() != size()) return false;
for(int i = 0,m=size();i<m;i++) {
if(KEY_EQUALS_NOT(queue.peek(i), peek(i))) return false;
}
return true;
}
return false;
}
@Override
public int hashCode() {
int result = 1;
for (int i = 0,m=size();i<m;i++) {
result = 31 * result + KEY_TO_HASH(peek(i));
}
return result;
}
@Override
public String toString()
{
if(isEmpty()) return "[]";
StringJoiner joiner = new StringJoiner(", ", "[", "]");
for (int i = 0,m=size();i<m;i++) {
joiner.add(KEY_TO_STRING(peek(i)));
}
return joiner.toString();
}
}
@@ -1,311 +1,468 @@
package speiger.src.collections.PACKAGE.queues; package speiger.src.collections.PACKAGE.queues;
#if TYPE_OBJECT import java.util.Arrays;
import java.util.Arrays; #if TYPE_OBJECT
import java.util.Comparator; import java.util.Comparator;
#endif import java.util.function.Consumer;
import java.util.NoSuchElementException; import java.util.function.BiFunction;
#endif
import speiger.src.collections.PACKAGE.collections.ITERATOR; import java.util.Objects;
#if !TYPE_OBJECT import java.util.NoSuchElementException;
import speiger.src.collections.PACKAGE.functions.COMPARATOR; #if JDK_FUNCTION
#endif import java.util.function.PREDICATE;
import speiger.src.collections.utils.ITrimmable; #endif
/** import speiger.src.collections.PACKAGE.collections.ITERATOR;
* A Simple First In First Out Priority Queue that is a Good Replacement for a linked list (or ArrayDequeue) #if !TYPE_OBJECT
* Its specific implementation uses a backing array that grows and shrinks as it is needed. import speiger.src.collections.PACKAGE.functions.COMPARATOR;
* @Type(T) import speiger.src.collections.PACKAGE.functions.CONSUMER;
*/ #endif
public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE implements PRIORITY_DEQUEUE KEY_GENERIC_TYPE, ITrimmable import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER;
{ import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
/** Max Possible ArraySize without the JVM Crashing */ #if !JDK_FUNCTION
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
/** The Minimum Capacity that is allowed */ #endif
public static final int MIN_CAPACITY = 4; import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
/** The Backing array */ import speiger.src.collections.utils.ITrimmable;
protected transient KEY_TYPE[] array;
/** The First Index pointer */ /**
protected int first; * A Simple First In First Out Priority Queue that is a Good Replacement for a linked list (or ArrayDequeue)
/** The Last Index pointer */ * Its specific implementation uses a backing array that grows and shrinks as it is needed.
protected int last; * @Type(T)
*/
/** 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 {
* @param values the Array that should be used /** Max Possible ArraySize without the JVM Crashing */
*/ private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
public ARRAY_FIFO_QUEUE(KEY_TYPE[] values) { /** The Minimum Capacity that is allowed */
this(values, 0, values.length); public static final int MIN_CAPACITY = 4;
} /** The Backing array */
protected transient KEY_TYPE[] array;
/** /** The First Index pointer */
* Constructor using a initial array protected int first;
* @param values the Array that should be used /** The Last Index pointer */
* @param size the amount of elements that are in the initial array protected int last;
* @throws IllegalStateException if values is smaller then size /** The Minimum Capacity of the Queue **/
*/ 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
/** */
* Constructor using a initial array public ARRAY_FIFO_QUEUE(KEY_TYPE[] values) {
* @param values the Array that should be used this(values, 0, values.length);
* @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
public ARRAY_FIFO_QUEUE(KEY_TYPE[] values, int offset, int size) { * @param values the Array that should be used
if (values.length < size) throw new IllegalArgumentException("Initial array (" + values.length + ") is smaller then the expected size (" + size + ")"); * @param size the amount of elements that are in the initial array
if(values.length <= 0) values = NEW_KEY_ARRAY(1); * @throws IllegalStateException if values is smaller then size
array = values; */
first = offset; public ARRAY_FIFO_QUEUE(KEY_TYPE[] values, int size) {
last = (offset + size) % array.length; this(values, 0, size);
if(array.length == size) expand(); }
}
/**
/** * Constructor using a initial array
* Constructor with a Min Capacity * @param values the Array that should be used
* @param capacity the initial capacity of the backing array * @param offset where to begin in the initial array
* @throws IllegalStateException if the initial size is smaller 0 * @param size the amount of elements that are in the initial array
*/ * @throws IllegalStateException if values is smaller then size
public ARRAY_FIFO_QUEUE(int capacity) { */
if (capacity < 0) throw new IllegalArgumentException("Initial capacity (" + capacity + ") is negative"); public ARRAY_FIFO_QUEUE(KEY_TYPE[] values, int offset, int size) {
array = NEW_KEY_ARRAY(Math.max(1, capacity)); if (values.length < size) throw new IllegalArgumentException("Initial array (" + values.length + ") is smaller then the expected size (" + size + ")");
} if(values.length <= 0) values = NEW_KEY_ARRAY(MIN_CAPACITY);
else if(values.length < MIN_CAPACITY) values = Arrays.copyOf(values, MIN_CAPACITY);
/** minCapacity = MIN_CAPACITY;
* Default Construtor array = values;
*/ first = offset;
public ARRAY_FIFO_QUEUE() { last = (offset + size) % array.length;
this(MIN_CAPACITY); if(array.length == size) expand();
} }
@Override /**
public ITERATOR KEY_GENERIC_TYPE iterator() { * Constructor with a Min Capacity
return new Iter(); * @param capacity the initial capacity of the backing array
} * @throws IllegalStateException if the initial size is smaller 0
*/
@Override public ARRAY_FIFO_QUEUE(int capacity) {
public int size() { if (capacity < 0) throw new IllegalArgumentException("Initial capacity (" + capacity + ") is negative");
final int apparentLength = last - first; array = NEW_KEY_ARRAY(Math.max(MIN_CAPACITY, capacity+1));
return apparentLength >= 0 ? apparentLength : array.length + apparentLength; minCapacity = array.length;
} }
@Override /**
public void clear() { * Default Construtor
#if TYPE_OBJECT */
Arrays.fill(array, null); public ARRAY_FIFO_QUEUE() {
#endif this(MIN_CAPACITY);
first = last = 0; }
}
@Override
@Override public ITERATOR KEY_GENERIC_TYPE iterator() {
public void ENQUEUE(KEY_TYPE e) { return new Iter();
array[last] = e; }
last = ++last % array.length;
if(last == first) expand(); @Override
} public int size() {
final int apparentLength = last - first;
@Override return apparentLength >= 0 ? apparentLength : array.length + apparentLength;
public void ENQUEUE_FIRST(KEY_TYPE e) { }
if(first == 0) first = array.length;
array[--first] = e; @Override
if(first == last) expand(); public void clear() {
} if(first != last) {
#if TYPE_OBJECT
@Override Arrays.fill(array, null);
public KEY_TYPE DEQUEUE() { #endif
if(first == last) throw new NoSuchElementException(); first = last = 0;
KEY_TYPE data = array[first]; }
#if TYPE_OBJECT else if(first != 0) {
array[first] = null; first = last = 0;
#endif }
first = ++first % array.length; }
reduce();
return data; @Override
} public void enqueue(KEY_TYPE e) {
array[last++] = e;
@Override if(last == array.length) last = 0;
public KEY_TYPE DEQUEUE_LAST() { if(last == first) expand();
if(first == last) throw new NoSuchElementException(); }
if(last == 0) last = array.length;
KEY_TYPE data = array[--last]; @Override
#if TYPE_OBJECT public void enqueueFirst(KEY_TYPE e) {
array[last] = null; if(first == 0) first = array.length;
#endif array[--first] = e;
reduce(); if(first == last) expand();
return data; }
}
@Override
@Override public KEY_TYPE dequeue() {
public KEY_TYPE PEEK(int index) { if(first == last) throw new NoSuchElementException();
if(first == last || index < 0 || index > size()) throw new NoSuchElementException(); KEY_TYPE data = array[first];
return array[(first + index) % array.length]; #if TYPE_OBJECT
} array[first] = null;
#endif
@Override if(++first == array.length) first = 0;
public boolean REMOVE(KEY_TYPE e) { reduce();
if(first == last) return false; return data;
for(int i = 0,m=size();i<m;i++) { }
int index = (first + i) % array.length;
if(e == array[index]) @Override
return removeIndex(index); public KEY_TYPE dequeueLast() {
} if(first == last) throw new NoSuchElementException();
return false; if(last == 0) last = array.length;
} KEY_TYPE data = array[--last];
#if TYPE_OBJECT
@Override array[last] = null;
public boolean REMOVE_LAST(KEY_TYPE e) { #endif
if(first == last) return false; reduce();
if(first == last) return false; return data;
for(int i = size()-1;i>=0;i--) { }
int index = (first + i) % array.length;
if(e == array[index]) @Override
return removeIndex(index); public KEY_TYPE peek(int index) {
} if(first == last || index < 0 || index >= size()) throw new NoSuchElementException();
return false; index += first;
} return index >= array.length ? array[index-array.length] : array[index];
}
protected boolean removeIndex(int index) {
if(first >= last ? index < first && index > last : index < first || index > last) return false; @Override
if(index == first) { public boolean contains(KEY_TYPE e) {
#if TYPE_OBJECT if(first == last) return false;
array[first] = null; for(int i = 0,m=size();i<m;i++) {
#endif if(e == array[(first + i) % array.length]) return true;
first++; }
} return false;
else if(index == last) { }
last--;
#if TYPE_OBJECT @Override
array[last] = null; public boolean removeFirst(KEY_TYPE e) {
#endif if(first == last) return false;
} for(int i = 0,m=size();i<m;i++) {
else if(index > last) { int index = (first + i) % array.length;
System.arraycopy(array, first, array, first+1, (index - first)); if(e == array[index])
#if TYPE_OBJECT return removeIndex(index);
array[first] = null; }
#endif return false;
first = ++first % array.length; }
}
else if(index < first) { @Override
System.arraycopy(array, index+1, array, index, (last - index) - 1); public boolean removeLast(KEY_TYPE e) {
#if TYPE_OBJECT if(first == last) return false;
array[last] = null; for(int i = size()-1;i>=0;i--) {
#endif int index = (first + i) % array.length;
if(--last < 0) last += array.length; if(e == array[index])
} return removeIndex(index);
else { }
if(index - first < last - index) { return false;
System.arraycopy(array, first, array, first+1, (index - first)); }
#if TYPE_OBJECT
array[first] = null; protected boolean removeIndex(int index) {
#endif if(first >= last ? index < first && index > last : index < first || index > last) return false;
first = ++first % array.length; if(index == first) {
} #if TYPE_OBJECT
else { array[first] = null;
System.arraycopy(array, index+1, array, index, (last - index) - 1); #endif
#if TYPE_OBJECT first++;
array[last] = null; }
#endif else if(index == last) {
if(--last < 0) last += array.length; last--;
} #if TYPE_OBJECT
} array[last] = null;
reduce(); #endif
return true; }
} else if(index > last) {
System.arraycopy(array, first, array, first+1, (index - first));
@Override #if TYPE_OBJECT
public void onChanged() {} array[first] = null;
#endif
@Override first = ++first % array.length;
public COMPARATOR KEY_SUPER_GENERIC_TYPE comparator() { return null; } }
else if(index < first) {
@Override System.arraycopy(array, index+1, array, index, (last - index) - 1);
public boolean trim(int size) { #if TYPE_OBJECT
int newSize = Math.max(size, size()); array[last] = null;
if(newSize >= array.length) return false; #endif
KEY_TYPE[] newArray = NEW_KEY_ARRAY(newSize); if(--last < 0) last += array.length;
if(first <= last) System.arraycopy(array, first, newArray, 0, last - first); }
else { else {
System.arraycopy(array, first, newArray, 0, array.length - first); if(index - first < last - index) {
System.arraycopy(array, 0, newArray, array.length - first, last); System.arraycopy(array, first, array, first+1, (index - first));
} #if TYPE_OBJECT
first = 0; array[first] = null;
last = size(); #endif
array = newArray; first = ++first % array.length;
return true; }
} else {
System.arraycopy(array, index+1, array, index, (last - index) - 1);
@Override #if TYPE_OBJECT
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] input) { array[last] = null;
if(input == null || input.length < size()) input = NEW_KEY_ARRAY(size()); #endif
if (first <= last) System.arraycopy(array, first, input, 0, last - first); if(--last < 0) last += array.length;
else { }
System.arraycopy(array, first, input, 0, array.length - first); }
System.arraycopy(array, 0, input, array.length - first, last); reduce();
} return true;
return input; }
}
@Override
#if !TYPE_OBJECT public void onChanged() {}
@Override
public CLASS_TYPE[] toArray(CLASS_TYPE[] input) { @Override
if(input == null || input.length < size()) input = NEW_CLASS_ARRAY(size()); public ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE copy() {
if (first <= last) { ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE queue = new ARRAY_FIFO_QUEUEBRACES();
for(int i = 0,m=last-first;i<m;i++) queue.first = first;
input[i] = KEY_TO_OBJ(array[first + i]); queue.last = last;
} queue.minCapacity = minCapacity;
else { queue.array = Arrays.copyOf(array, array.length);
int offset = 0; return queue;
for(int i = 0,m=array.length-first;i<m;i++,offset++) }
input[i] = KEY_TO_OBJ(array[first + i]);
for(int i = 0;i<last;i++) @Override
input[offset+i] = KEY_TO_OBJ(array[i]); public COMPARATOR KEY_SUPER_GENERIC_TYPE comparator() { return null; }
}
return input; @Override
} public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
#endif if(first == last) return;
protected void reduce() { for(int i = 0,m=size();i<m;i++)
final int size = size(); action.accept(array[(first + i) % array.length]);
if (array.length > MIN_CAPACITY && size <= array.length / 4) resize(size, array.length / 2); clearAndTrim(0);
} }
protected void expand() { @Override
resize(array.length, (int)Math.min(MAX_ARRAY_SIZE, 2L * array.length)); public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) {
} Objects.requireNonNull(action);
if(first == last) return;
protected final void resize(int oldSize, int newSize) { for(int i = 0,m=size();i<m;i++)
KEY_TYPE[] newArray = NEW_KEY_ARRAY(newSize); action.accept(i, array[(first + i) % array.length]);
if(first >= last) { clearAndTrim(0);
if(oldSize != 0) }
{
System.arraycopy(array, first, newArray, 0, array.length - first); @Override
System.arraycopy(array, 0, newArray, array.length - first, last); public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
} Objects.requireNonNull(action);
} if(first == last) return;
else System.arraycopy(array, first, newArray, 0, last-first); for(int i = 0,m=size();i<m;i++)
first = 0; action.accept(input, array[(first + i) % array.length]);
last = oldSize; clearAndTrim(0);
array = newArray; }
}
@Override
private class Iter implements ITERATOR KEY_GENERIC_TYPE public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
{ Objects.requireNonNull(filter);
int index = first; for(int i = 0,m=size();i<m;i++) {
@Override if(filter.test(array[(first + i) % array.length])) return true;
public boolean hasNext() }
{ return false;
return index != last; }
}
@Override
@Override public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
public KEY_TYPE NEXT() { Objects.requireNonNull(filter);
KEY_TYPE value = array[index]; for(int i = 0,m=size();i<m;i++) {
removeIndex(index); if(filter.test(array[(first + i) % array.length])) return false;
index = ++index % array.length; }
return value; return true;
} }
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0,m=size();i<m;i++) {
if(!filter.test(array[(first + i) % array.length])) return false;
}
return true;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0,m=size();i<m;i++) {
int index = (first + i) % array.length;
if(filter.test(array[index])) {
KEY_TYPE data = array[index];
removeIndex(index);
return data;
}
}
return EMPTY_VALUE;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
for(int i = 0,m=size();i<m;i++) {
state = operator.APPLY_VALUE(state, array[(first + i) % array.length]);
}
return state;
}
#else
@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);
KEY_SPECIAL_TYPE state = identity;
for(int i = 0,m=size();i<m;i++) {
state = operator.APPLY_VALUE(state, array[(first + i) % array.length]);
}
return state;
}
#endif
@Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_VALUE;
boolean empty = true;
for(int i = 0,m=size();i<m;i++) {
if(empty) {
empty = false;
state = array[(first + i) % array.length];
continue;
}
state = operator.APPLY_VALUE(state, array[(first + i) % array.length]);
}
return state;
}
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int result = 0;
for(int i = 0,m=size();i<m;i++) {
if(filter.test(array[(first + i) % array.length])) result++;
}
return result;
}
@Override
public boolean trim(int size) {
int newSize = Math.max(Math.max(size, size()), minCapacity);
if(newSize >= array.length) return false;
KEY_TYPE[] newArray = NEW_KEY_ARRAY(newSize);
if(first <= last) System.arraycopy(array, first, newArray, 0, last - first);
else {
System.arraycopy(array, first, newArray, 0, array.length - first);
System.arraycopy(array, 0, newArray, array.length - first, last);
}
first = 0;
last = size();
array = newArray;
return true;
}
/**
* Trims the collection down to the requested size and clears all elements while doing so
* @param size the amount of elements that should be allowed
* @note this will enforce minimum size of the collection itself
*/
@Override
public void clearAndTrim(int size) {
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,312 +1,447 @@
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.Objects; import java.util.function.Consumer;
#endif import java.util.function.BiFunction;
#endif
import speiger.src.collections.PACKAGE.collections.COLLECTION; import java.util.Objects;
import speiger.src.collections.PACKAGE.collections.ITERATOR; #if JDK_FUNCTION
#if !TYPE_OBJECT import java.util.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.COMPARATOR; #endif
#endif
import speiger.src.collections.PACKAGE.utils.ARRAYS; import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR;
/** #if !TYPE_OBJECT
* A Array Priority Queue, this is a very unoptimized implementation of the PriorityQueue for very specific usecases. import speiger.src.collections.PACKAGE.functions.COMPARATOR;
* It allows for duplicated entries and works like {@link java.util.List#indexOf(Object)} search. import speiger.src.collections.PACKAGE.functions.CONSUMER;
* It is highly suggested to use HeapPriorityQueue otherwise, unless you know why you need this specific implementation #endif
* @Type(T) import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER;
*/ import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
public class ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_QUEUE KEY_GENERIC_TYPE #if !JDK_FUNCTION
{ import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
/** The Backing Array */ #endif
protected transient KEY_TYPE[] array = EMPTY_KEY_ARRAY; import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
/** The Amount of elements stored within the array */ import speiger.src.collections.PACKAGE.utils.ARRAYS;
protected int size; import speiger.src.collections.utils.SanityChecks;
/** The Last known first index pointer */
protected int firstIndex = -1; /**
/** The Sorter of the Array */ * A Array Priority Queue, this is a very unoptimized implementation of the PriorityQueue for very specific usecases.
protected COMPARATOR KEY_SUPER_GENERIC_TYPE comparator; * 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
/** * @Type(T)
* Default Constructor */
*/ public class ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEUE KEY_GENERIC_TYPE
public ARRAY_PRIORITY_QUEUE() { {
this(0, null); /** The Backing Array */
} protected transient KEY_TYPE[] array = EMPTY_KEY_ARRAY;
/** The Amount of elements stored within the array */
/** protected int size;
* Constructor using custom sorter /** The Last known first index pointer */
* @param comp Comparator to sort the Array. Can be null protected int firstIndex = -1;
*/ /** The Sorter of the Array */
public ARRAY_PRIORITY_QUEUE(COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { protected COMPARATOR KEY_SUPER_GENERIC_TYPE comparator;
this(0, comp);
} /**
* Default Constructor
/** */
* Constructor with a Min Capacity public ARRAY_PRIORITY_QUEUE() {
* @param size the initial capacity of the backing array this(0, null);
* @throws IllegalStateException if the initial size is smaller 0 }
*/
public ARRAY_PRIORITY_QUEUE(int size) { /**
this(size, null); * Constructor using custom sorter
} * @param comp Comparator to sort the Array. Can be null
*/
/** public ARRAY_PRIORITY_QUEUE(COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
* Constructor with a Min Capacity and custom Sorter this(0, comp);
* @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 with a Min Capacity
public ARRAY_PRIORITY_QUEUE(int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { * @param size the initial capacity of the backing array
if(size < 0) throw new IllegalAccessError("Size has to be 0 or positive"); * @throws IllegalStateException if the initial size is smaller 0
if(size > 0) array = NEW_KEY_ARRAY(size); */
this.size = size; public ARRAY_PRIORITY_QUEUE(int size) {
comparator = comp; this(size, null);
} }
/** /**
* Constructor using a initial array * Constructor with a Min Capacity and custom Sorter
* @param array the Array that should be used * @param size the initial capacity of the backing array
*/ * @param comp Comparator to sort the Array. Can be null
public ARRAY_PRIORITY_QUEUE(KEY_TYPE[] array) { * @throws IllegalStateException if the initial size is smaller 0
this(array, array.length); */
} public ARRAY_PRIORITY_QUEUE(int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
if(size < 0) throw new IllegalAccessError("Size has to be 0 or positive");
/** if(size > 0) array = NEW_KEY_ARRAY(size);
* Constructor using a initial array comparator = comp;
* @param array the Array that should be used }
* @param size the amount of elements found within the array
* @throws NegativeArraySizeException if size is smaller then 0 /**
*/ * Constructor using a initial array
public ARRAY_PRIORITY_QUEUE(KEY_TYPE[] array, int size) { * @param array the Array that should be used
this.array = Arrays.copyOf(array, size); */
this.size = size; 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 * Constructor using a initial array
* @param comp Comparator to sort the Array. Can be null * @param array the Array that should be used
*/ * @param size the amount of elements found within the array
public ARRAY_PRIORITY_QUEUE(KEY_TYPE[] array, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { * @throws NegativeArraySizeException if size is smaller then 0
this(array, array.length, comp); */
} public ARRAY_PRIORITY_QUEUE(KEY_TYPE[] array, int size) {
this.array = Arrays.copyOf(array, size);
/** this.size = size;
* Constructor using a initial array and a custom sorter }
* @param array the Array that should be used
* @param size the amount of elements found within the array /**
* @param comp Comparator to sort the Array. Can be null * Constructor using a initial array and a custom sorter
* @throws NegativeArraySizeException if size is smaller then 0 * @param array the Array that should be used
*/ * @param comp Comparator to sort the Array. Can be null
public ARRAY_PRIORITY_QUEUE(KEY_TYPE[] array, int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { */
this.array = Arrays.copyOf(array, size); public ARRAY_PRIORITY_QUEUE(KEY_TYPE[] array, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
this.size = size; this(array, array.length, comp);
this.comparator = comp; }
}
/**
/** * Constructor using a initial array and a custom sorter
* Constructor using a Collection * @param array the Array that should be used
* @param c the Collection that should be used * @param size the amount of elements found within the array
*/ * @param comp Comparator to sort the Array. Can be null
public ARRAY_PRIORITY_QUEUE(COLLECTION KEY_GENERIC_TYPE c) { * @throws NegativeArraySizeException if size is smaller then 0
array = CAST_KEY_ARRAY c.TO_ARRAY(); */
size = c.size(); public ARRAY_PRIORITY_QUEUE(KEY_TYPE[] array, int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
} this.array = Arrays.copyOf(array, size);
this.size = size;
/** this.comparator = comp;
* Constructor using a Collection and a custom sorter }
* @param c the Collection that should be used
* @param comp Comparator to sort the Array. Can be null /**
*/ * Constructor using a Collection
public ARRAY_PRIORITY_QUEUE(COLLECTION KEY_GENERIC_TYPE c, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { * @param c the Collection that should be used
array = CAST_KEY_ARRAY c.TO_ARRAY(); */
size = c.size(); public ARRAY_PRIORITY_QUEUE(COLLECTION KEY_GENERIC_TYPE c) {
comparator = comp; array = CAST_KEY_ARRAY c.TO_ARRAY();
} size = c.size();
}
/**
* Wrapping method to help serialization /**
* @param array the array that should be used * Constructor using a Collection and a custom sorter
* @Type(T) * @param c the Collection that should be used
* @return a ArrayPriorityQueue containing the original input array * @param comp Comparator to sort the Array. Can be null
*/ */
public static GENERIC_KEY_BRACES ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE wrap(KEY_TYPE[] array) { public ARRAY_PRIORITY_QUEUE(COLLECTION KEY_GENERIC_TYPE c, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
return wrap(array, array.length); array = CAST_KEY_ARRAY c.TO_ARRAY();
} size = c.size();
comparator = comp;
/** }
* Wrapping method to help serialization
* @param array the array that should be used /**
* @param size the amount of elements within the array * Wrapping method to help serialization
* @Type(T) * @param array the array that should be used
* @return a ArrayPriorityQueue containing the original input array * @Type(T)
*/ * @return a ArrayPriorityQueue containing the original input array
public static GENERIC_KEY_BRACES ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE wrap(KEY_TYPE[] array, int size) { */
ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE queue = new ARRAY_PRIORITY_QUEUEBRACES(); public static GENERIC_KEY_BRACES ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE wrap(KEY_TYPE[] array) {
queue.array = array; return wrap(array, array.length);
queue.size = size; }
return queue;
} /**
* Wrapping method to help serialization
/** * @param array the array that should be used
* Wrapping method to help serialization, using a custom sorter * @param size the amount of elements within the array
* @param array the array that should be used * @Type(T)
* @param comp Comparator to sort the Array. Can be null * @return a ArrayPriorityQueue containing the original input array
* @Type(T) */
* @return a ArrayPriorityQueue containing the original input array public static GENERIC_KEY_BRACES ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE wrap(KEY_TYPE[] array, int size) {
*/ ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE queue = new ARRAY_PRIORITY_QUEUEBRACES();
public static GENERIC_KEY_BRACES ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE wrap(KEY_TYPE[] array, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { queue.array = array;
return wrap(array, array.length, comp); queue.size = size;
} return queue;
}
/**
* Wrapping method to help serialization, using a custom sorter /**
* @param array the array that should be used * Wrapping method to help serialization, using a custom sorter
* @param size the amount of elements within the array * @param array the array that should be used
* @param comp Comparator to sort the Array. Can be null * @param comp Comparator to sort the Array. Can be null
* @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, int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { public static GENERIC_KEY_BRACES ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE wrap(KEY_TYPE[] array, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE queue = new ARRAY_PRIORITY_QUEUEBRACES(comp); return wrap(array, array.length, comp);
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
@Override * @param size the amount of elements within the array
public void ENQUEUE(KEY_TYPE e) { * @param comp Comparator to sort the Array. Can be null
if(size == array.length) array = Arrays.copyOf(array, size+1); * @Type(T)
if(firstIndex != -1){ * @return a ArrayPriorityQueue containing the original input array
int compare = comparator == null ? COMPAREABLE_TO_KEY(e, array[firstIndex]) : comparator.compare(e, array[firstIndex]); */
if(compare < 0) firstIndex = size; public static GENERIC_KEY_BRACES ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE wrap(KEY_TYPE[] array, int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
else if(compare > 0) firstIndex = -1; ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE queue = new ARRAY_PRIORITY_QUEUEBRACES(comp);
} queue.array = array;
array[size++] = e; queue.size = size;
} return queue;
}
@Override
public KEY_TYPE DEQUEUE() { @Override
if(size <= 0) throw new NoSuchElementException(); public void enqueue(KEY_TYPE e) {
int index = findFirstIndex(); 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));
KEY_TYPE value = array[index]; if(firstIndex != -1){
if(index != --size) System.arraycopy(array, index+1, array, index, size - index); int compare = comparator == null ? COMPAREABLE_TO_KEY(e, array[firstIndex]) : comparator.compare(e, array[firstIndex]);
#if TYPE_OBJECT if(compare < 0) firstIndex = size;
array[size] = null; else if(compare > 0) firstIndex = -1;
#endif }
firstIndex = -1; array[size++] = e;
return value; }
}
@Override
@Override public KEY_TYPE dequeue() {
public KEY_TYPE PEEK(int index) { if(size <= 0) throw new NoSuchElementException();
if(index < 0 || index >= size) throw new NoSuchElementException(); int index = findFirstIndex();
return array[index]; KEY_TYPE value = array[index];
} if(index != --size) System.arraycopy(array, index+1, array, index, size - index);
#if TYPE_OBJECT
@Override array[size] = null;
public boolean REMOVE(KEY_TYPE e) { #endif
for(int i = 0;i<size;i++) firstIndex = -1;
if(KEY_EQUALS(e, array[i])) return removeIndex(i); return value;
return false; }
}
@Override
@Override public KEY_TYPE first() {
public boolean REMOVE_LAST(KEY_TYPE e) { if(isEmpty()) throw new NoSuchElementException();
for(int i = size-1;i>=0;i--) if(firstIndex == -1) findFirstIndex();
if(KEY_EQUALS(e, array[i])) return removeIndex(i); return array[firstIndex];
return false; }
}
@Override
protected boolean removeIndex(int index) { public KEY_TYPE peek(int index) {
if(index != --size) System.arraycopy(array, index+1, array, index, size - index); if(index < 0 || index >= size) throw new NoSuchElementException();
#if TYPE_OBJECT return array[index];
array[size] = null; }
#endif
if(index == firstIndex) firstIndex = -1; @Override
else if(firstIndex != -1 && index >= firstIndex) firstIndex--; public boolean contains(KEY_TYPE e) {
return true; for(int i = 0;i<size;i++)
} if(KEY_EQUALS(e, array[i])) return true;
return false;
@Override }
public void onChanged() {
firstIndex = -1; @Override
} public boolean removeFirst(KEY_TYPE e) {
for(int i = 0;i<size;i++)
@Override if(KEY_EQUALS(e, array[i])) return removeIndex(i);
public int size() { return false;
return size; }
}
@Override
@Override public boolean removeLast(KEY_TYPE e) {
public void clear() { for(int i = size-1;i>=0;i--)
#if TYPE_OBJECT if(KEY_EQUALS(e, array[i])) return removeIndex(i);
Arrays.fill(array, null); return false;
#endif }
size = 0;
} protected boolean removeIndex(int index) {
if(index != --size) System.arraycopy(array, index+1, array, index, size - index);
@Override #if TYPE_OBJECT
public ITERATOR KEY_GENERIC_TYPE iterator() { array[size] = null;
return new Iter(); #endif
} if(index == firstIndex) firstIndex = -1;
else if(firstIndex != -1 && index >= firstIndex) firstIndex--;
@Override return true;
public COMPARATOR KEY_SUPER_GENERIC_TYPE comparator() { }
return comparator;
} @Override
public void onChanged() {
@Override firstIndex = -1;
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] input) { }
if(input == null || input.length < size()) input = NEW_KEY_ARRAY(size());
System.arraycopy(array, 0, input, 0, size()); @Override
return input; public int size() {
} return size;
}
#if !TYPE_OBJECT
@Override @Override
public CLASS_TYPE[] toArray(CLASS_TYPE[] input) { public void clear() {
if(input == null || input.length < size()) input = new CLASS_TYPE[size()]; #if TYPE_OBJECT
for(int i = 0;i<size;i++) input[i] = KEY_TO_OBJ(array[i]); Arrays.fill(array, null);
return input; #endif
} size = 0;
}
#endif
protected int findFirstIndex() { @Override
if(firstIndex == -1) { public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
int index = size-1; Objects.requireNonNull(action);
KEY_TYPE value = array[index]; for(int i = 0,m=size;i<m;i++) action.accept(dequeue());
if(comparator == null) { }
for(int i = index;i>=0;i--) {
if(COMPAREABLE_TO_KEY(array[i], value) < 0) @Override
value = array[index = i]; public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) {
} Objects.requireNonNull(action);
} for(int i = 0,m=size;i<m;i++) action.accept(i, dequeue());
else { }
for(int i = index;i>=0;i--) {
if(comparator.compare(array[i], value) < 0) @Override
value = array[index = i]; public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
} Objects.requireNonNull(action);
} for(int i = 0,m=size;i<m;i++) action.accept(input, dequeue());
firstIndex = index; }
}
return firstIndex; @Override
} public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
private class Iter implements ITERATOR KEY_GENERIC_TYPE { for(int i = 0;i<size;i++) {
@Override if(filter.test(array[i])) return true;
public boolean hasNext() { }
return !isEmpty(); return false;
} }
@Override @Override
public KEY_TYPE NEXT() { public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
return DEQUEUE(); Objects.requireNonNull(filter);
} for(int i = 0;i<size;i++) {
} if(filter.test(array[i])) return false;
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(!filter.test(array[i])) return false;
}
return true;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
for(int i = 0;i<size;i++) {
state = operator.APPLY_VALUE(state, array[i]);
}
return state;
}
#else
@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);
KEY_SPECIAL_TYPE state = identity;
for(int i = 0;i<size;i++) {
state = operator.APPLY_VALUE(state, array[i]);
}
return state;
}
#endif
@Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_VALUE;
boolean empty = true;
for(int i = 0;i<size;i++) {
if(empty) {
empty = false;
state = array[i];
continue;
}
state = operator.APPLY_VALUE(state, array[i]);
}
return state;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(filter.test(array[i])) {
KEY_TYPE data = array[i];
removeIndex(i);
return data;
}
}
return EMPTY_VALUE;
}
@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;
}
@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,288 +1,415 @@
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.Objects; import java.util.function.Consumer;
#endif import java.util.function.BiFunction;
#endif
import speiger.src.collections.PACKAGE.collections.COLLECTION; import java.util.Objects;
import speiger.src.collections.PACKAGE.collections.ITERATOR; #if JDK_FUNCTION
#if !TYPE_OBJECT import java.util.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.COMPARATOR; #endif
#endif
import speiger.src.collections.PACKAGE.utils.ARRAYS; import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR;
/** #if !TYPE_OBJECT
* A Simple Heap base Priority Queue implementation import speiger.src.collections.PACKAGE.functions.COMPARATOR;
* It is a ArrayBased Alternative to TreeSets that has less object allocations import speiger.src.collections.PACKAGE.functions.CONSUMER;
* @Type(T) #endif
*/ import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER;
public class HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE implements 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 Sorter of the Array */ import speiger.src.collections.utils.SanityChecks;
protected COMPARATOR KEY_SUPER_GENERIC_TYPE comparator;
/**
/** * A Simple Heap base Priority Queue implementation
* Default Constructor * It is a ArrayBased Alternative to TreeSets that has less object allocations
*/ * @Type(T)
public HEAP_PRIORITY_QUEUE() { */
this(0, null); public class HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEUE KEY_GENERIC_TYPE
} {
/** The Backing Array */
/** protected transient KEY_TYPE[] array = EMPTY_KEY_ARRAY;
* Constructor using custom sorter /** The Amount of elements stored within the array */
* @param comp Comparator to sort the Array. Can be null protected int size;
*/ /** The Sorter of the Array */
public HEAP_PRIORITY_QUEUE(COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { protected COMPARATOR KEY_SUPER_GENERIC_TYPE comparator;
this(0, comp);
} /**
* Default Constructor
/** */
* Constructor with a Min Capacity public HEAP_PRIORITY_QUEUE() {
* @param size the initial capacity of the backing array this(0, null);
* @throws IllegalStateException if the initial size is smaller 0 }
*/
public HEAP_PRIORITY_QUEUE(int size) { /**
this(size, null); * Constructor using custom sorter
} * @param comp Comparator to sort the Array. Can be null
*/
/** public HEAP_PRIORITY_QUEUE(COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
* Constructor with a Min Capacity and custom Sorter this(0, comp);
* @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 with a Min Capacity
public HEAP_PRIORITY_QUEUE(int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { * @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
this.size = size; */
comparator = comp; public HEAP_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
*/ * @param size the initial capacity of the backing array
public HEAP_PRIORITY_QUEUE(KEY_TYPE[] array) { * @param comp Comparator to sort the Array. Can be null
this(array, array.length); * @throws IllegalStateException if the initial size is smaller 0
} */
public HEAP_PRIORITY_QUEUE(int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
/** if(size > 0) array = NEW_KEY_ARRAY(size);
* Constructor using a initial array comparator = comp;
* @param array the Array that should be used }
* @param size the amount of elements found within the array
* @throws NegativeArraySizeException if size is smaller then 0 /**
*/ * Constructor using a initial array
public HEAP_PRIORITY_QUEUE(KEY_TYPE[] array, int size) { * @param array the Array that should be used
this.array = Arrays.copyOf(array, size); */
this.size = size; public HEAP_PRIORITY_QUEUE(KEY_TYPE[] array) {
ARRAYS.heapify(array, size, null); this(array, array.length);
} }
/** /**
* Constructor using a initial array and a custom sorter * Constructor using a initial array
* @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 found within the array
*/ * @throws NegativeArraySizeException if size is smaller then 0
public HEAP_PRIORITY_QUEUE(KEY_TYPE[] array, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { */
this(array, array.length, comp); public HEAP_PRIORITY_QUEUE(KEY_TYPE[] array, int size) {
} this.array = Arrays.copyOf(array, size);
this.size = size;
/** ARRAYS.heapify(array, size, null);
* Constructor using a initial array and a custom sorter }
* @param array the Array that should be used
* @param size the amount of elements found within the array /**
* @param comp Comparator to sort the Array. Can be null * Constructor using a initial array and a custom sorter
* @throws NegativeArraySizeException if size is smaller then 0 * @param array the Array that should be used
*/ * @param comp Comparator to sort the Array. Can be null
public HEAP_PRIORITY_QUEUE(KEY_TYPE[] array, int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { */
this.array = Arrays.copyOf(array, size); public HEAP_PRIORITY_QUEUE(KEY_TYPE[] array, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
this.size = size; this(array, array.length, comp);
comparator = comp; }
ARRAYS.heapify(array, size, comp);
} /**
* Constructor using a initial array and a custom sorter
/** * @param array the Array that should be used
* Constructor using a Collection * @param size the amount of elements found within the array
* @param c the Collection that should be used * @param comp Comparator to sort the Array. Can be null
*/ * @throws NegativeArraySizeException if size is smaller then 0
public HEAP_PRIORITY_QUEUE(COLLECTION KEY_GENERIC_TYPE c) { */
array = CAST_KEY_ARRAY c.TO_ARRAY(); public HEAP_PRIORITY_QUEUE(KEY_TYPE[] array, int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
size = c.size(); this.array = Arrays.copyOf(array, size);
ARRAYS.heapify(array, size, null); this.size = size;
} comparator = comp;
ARRAYS.heapify(array, size, comp);
/** }
* Constructor using a Collection and a custom sorter
* @param c the Collection that should be used /**
* @param comp Comparator to sort the Array. Can be null * Constructor using a Collection
*/ * @param c the Collection that should be used
public HEAP_PRIORITY_QUEUE(COLLECTION KEY_GENERIC_TYPE c, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { */
array = CAST_KEY_ARRAY c.TO_ARRAY(); public HEAP_PRIORITY_QUEUE(COLLECTION KEY_GENERIC_TYPE c) {
size = c.size(); array = CAST_KEY_ARRAY c.TO_ARRAY();
comparator = comp; size = c.size();
ARRAYS.heapify(array, size, comp); ARRAYS.heapify(array, size, null);
} }
/** /**
* Wrapping method to help serialization * Constructor using a Collection and a custom sorter
* @param array the array that should be used * @param c the Collection that should be used
* @Type(T) * @param comp Comparator to sort the Array. Can be null
* @return a HeapPriorityQueue containing the original input array */
*/ public HEAP_PRIORITY_QUEUE(COLLECTION KEY_GENERIC_TYPE c, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
public static GENERIC_KEY_BRACES HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE wrap(KEY_TYPE[] array) { array = CAST_KEY_ARRAY c.TO_ARRAY();
return wrap(array, array.length); size = c.size();
} comparator = comp;
ARRAYS.heapify(array, size, comp);
/** }
* Wrapping method to help serialization
* @param array the array that should be used /**
* @param size the amount of elements within the array * Wrapping method to help serialization
* @Type(T) * @param array the array that should be used
* @return a HeapPriorityQueue containing the original input array * @Type(T)
*/ * @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) { */
HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE queue = new HEAP_PRIORITY_QUEUEBRACES(); public static GENERIC_KEY_BRACES HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE wrap(KEY_TYPE[] array) {
queue.array = array; return wrap(array, array.length);
queue.size = size; }
ARRAYS.heapify(array, size, null);
return queue; /**
} * Wrapping method to help serialization
* @param array the array that should be used
/** * @param size the amount of elements within the array
* 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) {
* @return a HeapPriorityQueue containing the original input array HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE queue = new HEAP_PRIORITY_QUEUEBRACES();
*/ 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, null);
} return queue;
}
/**
* Wrapping method to help serialization, using a custom sorter /**
* @param array the array that should be used * Wrapping method to help serialization, using a custom sorter
* @param size the amount of elements within the array * @param array the array that should be used
* @param comp Comparator to sort the Array. Can be null * @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, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { 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(comp); return wrap(array, array.length, comp);
queue.array = array; }
queue.size = size;
ARRAYS.heapify(array, size, comp); /**
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
@Override * @param comp Comparator to sort the Array. Can be null
public int size() { * @Type(T)
return size; * @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, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
@Override HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE queue = new HEAP_PRIORITY_QUEUEBRACES(comp);
public void clear() { queue.array = array;
#if TYPE_OBJECT queue.size = size;
Arrays.fill(array, null); ARRAYS.heapify(array, size, comp);
#endif return queue;
size = 0; }
}
@Override
@Override public int size() {
public ITERATOR KEY_GENERIC_TYPE iterator() { return size;
return new Iter(); }
}
@Override
@Override public void clear() {
public void ENQUEUE(KEY_TYPE e) { #if TYPE_OBJECT
if(size == array.length) array = Arrays.copyOf(array, size + 1); Arrays.fill(array, null);
array[size++] = e; #endif
ARRAYS.shiftUp(array, size-1, comparator); size = 0;
} }
@Override @Override
public KEY_TYPE DEQUEUE() { public ITERATOR KEY_GENERIC_TYPE iterator() {
if(size <= 0) throw new NoSuchElementException(); return new Iter();
KEY_TYPE value = array[0]; }
array[0] = array[--size];
#if TYPE_OBJECT @Override
array[size] = null; public void enqueue(KEY_TYPE e) {
#endif 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));
if(size != 0) ARRAYS.shiftDown(array, size, 0, comparator); array[size++] = e;
return value; ARRAYS.shiftUp(array, size-1, comparator);
} }
@Override @Override
public KEY_TYPE PEEK(int index) { public KEY_TYPE dequeue() {
if(index < 0 || index >= size) throw new NoSuchElementException(); if(size <= 0) throw new NoSuchElementException();
return array[index]; KEY_TYPE value = array[0];
} array[0] = array[--size];
#if TYPE_OBJECT
@Override array[size] = null;
public boolean REMOVE(KEY_TYPE e) { #endif
for(int i = 0;i<size;i++) if(size != 0) ARRAYS.shiftDown(array, size, 0, comparator);
if(KEY_EQUALS(e, array[i])) return removeIndex(i); return value;
return false; }
}
@Override
@Override public KEY_TYPE peek(int index) {
public boolean REMOVE_LAST(KEY_TYPE e) { if(index < 0 || index >= size) throw new NoSuchElementException();
for(int i = size-1;i>=0;i--) return array[index];
if(KEY_EQUALS(e, array[i])) return removeIndex(i); }
return false;
} @Override
public boolean contains(KEY_TYPE e) {
protected boolean removeIndex(int index) { for(int i = 0;i<size;i++)
array[index] = array[--size]; if(KEY_EQUALS(e, array[i])) return true;
#if TYPE_OBJECT return false;
array[size] = null; }
#endif
if(size != index) ARRAYS.shiftDown(array, size, index, comparator); @Override
return true; public boolean removeFirst(KEY_TYPE e) {
} for(int i = 0;i<size;i++)
if(KEY_EQUALS(e, array[i])) return removeIndex(i);
@Override return false;
public void onChanged() { }
if(size <= 0) return;
ARRAYS.shiftDown(array, size, 0, comparator); @Override
} public boolean removeLast(KEY_TYPE e) {
for(int i = size-1;i>=0;i--)
@Override if(KEY_EQUALS(e, array[i])) return removeIndex(i);
public COMPARATOR KEY_SUPER_GENERIC_TYPE comparator() { return false;
return comparator; }
}
@Override
@Override public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] input) { Objects.requireNonNull(action);
if(input == null || input.length < size()) input = NEW_KEY_ARRAY(size()); for(int i = 0,m=size;i<m;i++) action.accept(dequeue());
System.arraycopy(array, 0, input, 0, size()); }
return input;
} @Override
public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) {
#if !TYPE_OBJECT Objects.requireNonNull(action);
@Override for(int i = 0,m=size;i<m;i++) action.accept(i, dequeue());
public CLASS_TYPE[] toArray(CLASS_TYPE[] input) { }
if(input == null || input.length < size()) input = new CLASS_TYPE[size()];
for(int i = 0;i<size;i++) input[i] = KEY_TO_OBJ(array[i]); @Override
return input; public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
} Objects.requireNonNull(action);
for(int i = 0,m=size;i<m;i++) action.accept(input, dequeue());
#endif }
private class Iter implements ITERATOR KEY_GENERIC_TYPE {
@Override @Override
public boolean hasNext() { public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
return !isEmpty(); Objects.requireNonNull(filter);
} for(int i = 0;i<size;i++) {
if(filter.test(array[i])) return true;
@Override }
public KEY_TYPE NEXT() { return false;
return DEQUEUE(); }
}
} @Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(filter.test(array[i])) return false;
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(!filter.test(array[i])) return false;
}
return true;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
for(int i = 0;i<size;i++) {
state = operator.APPLY_VALUE(state, array[i]);
}
return state;
}
#else
@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);
KEY_SPECIAL_TYPE state = identity;
for(int i = 0;i<size;i++) {
state = operator.APPLY_VALUE(state, array[i]);
}
return state;
}
#endif
@Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_VALUE;
boolean empty = true;
for(int i = 0;i<size;i++) {
if(empty) {
empty = false;
state = array[i];
continue;
}
state = operator.APPLY_VALUE(state, array[i]);
}
return state;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(filter.test(array[i])) {
KEY_TYPE data = array[i];
removeIndex(i);
return data;
}
}
return EMPTY_VALUE;
}
@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,5 +1,15 @@
package speiger.src.collections.PACKAGE.queues; package speiger.src.collections.PACKAGE.queues;
#if TYPE_OBJECT
import java.util.Collection;
import java.util.Iterator;
#endif
import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR;
#if QUEUES_FEATURE
import speiger.src.collections.PACKAGE.utils.PRIORITY_QUEUES;
#endif
/** /**
* A Type Speciifc PriorityDeque or Dequeue interface to allow implementations like FIFO queues. * A Type Speciifc PriorityDeque or Dequeue interface to allow implementations like FIFO queues.
* @Type(T) * @Type(T)
@@ -10,39 +20,86 @@ public interface PRIORITY_DEQUEUE KEY_GENERIC_TYPE extends PRIORITY_QUEUE KEY_GE
* Method to insert a element into the first Index instead of the last. * Method to insert a element into the first Index instead of the last.
* @param e the element that should be inserted into the first place * @param e the element that should be inserted into the first place
*/ */
public void ENQUEUE_FIRST(KEY_TYPE e); public void enqueueFirst(KEY_TYPE e);
/**
* Method to mass insert a elements into the first Index of the PriorityDequeue.
* @param e the elements that should be inserted
*/
public default void enqueueAllFirst(KEY_TYPE... e) {
enqueueAllFirst(e, 0, e.length);
}
/**
* Method to mass insert a elements into the first Index of the PriorityDequeue.
* @param e the elements that should be inserted
* @param length the amount of elements that should be inserted
*/
public default void enqueueAllFirst(KEY_TYPE[] e, int length) {
enqueueAllFirst(e, 0, length);
}
/**
* Method to mass insert a elements into the first Index of the PriorityDequeue.
* @param e the elements that should be inserted
* @param offset the offset where in the array should be started
* @param length the amount of elements that should be inserted
*/
public default void enqueueAllFirst(KEY_TYPE[] e, int offset, int length) {
for(int i = 0;i<length;i++)
enqueueFirst(e[i+offset]);
}
/**
* Method to mass insert elements into first Index of the PriorityDequeue.
* @param c the elements that should be inserted from the Collection
*/
public default void enqueueAllFirst(COLLECTION KEY_GENERIC_TYPE c) {
for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();)
enqueueFirst(iter.NEXT());
}
#if TYPE_OBJECT
/**
* Method to mass insert elements into first Index of the PriorityDequeue.
* 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
*/
public default void enqueueAllFirst(Collection<? extends CLASS_TYPE> c) {
for(Iterator<? extends CLASS_TYPE> iter = c.iterator();iter.hasNext();)
enqueueFirst(iter.next());
}
#endif
/** /**
* A Method to remove a element from the last place instead of the first * A Method to remove a element from the last place instead of the first
* @return the last element inserted * @return the last element inserted
* @throws java.util.NoSuchElementException if no element is in the deque * @throws java.util.NoSuchElementException if no element is in the deque
*/ */
public KEY_TYPE DEQUEUE_LAST(); public KEY_TYPE dequeueLast();
/** /**
* Peeking function for the last element * Peeking function for the last element
* @return the Last Element within the dequeue without deleting it * @return the Last Element within the dequeue without deleting it
*/ */
public default KEY_TYPE LAST_KEY() { return PEEK(size()-1); } public default KEY_TYPE last() { return peek(size()-1); }
#if !TYPE_OBJECT #if QUEUES_FEATURE
/** /**
* Boxed Method for the enqueue first method * Creates a Wrapped PriorityDequeue that is Synchronized
* @param e the boxed element that should be inserted * @return a new PriorityDequeue that is synchronized
* @see PRIORITY_QUEUES#synchronize
*/ */
@Deprecated public default PRIORITY_DEQUEUE KEY_GENERIC_TYPE synchronizeQueue() { return PRIORITY_QUEUES.synchronize(this); }
public default void enqueueFirst(CLASS_TYPE e) { ENQUEUE_FIRST(OBJ_TO_KEY(e)); }
/** /**
* Boxed Method for the dequeue last method * Creates a Wrapped PriorityDequeue that is Synchronized
* @return the last element of the Dequeue * @param mutex is the controller of the synchronization block
* @throws java.util.NoSuchElementException if no element is in the dequeue * @return a new PriorityDequeue Wrapper that is synchronized
* * @see PRIORITY_QUEUES#synchronize
*/ */
@Deprecated public default PRIORITY_DEQUEUE KEY_GENERIC_TYPE synchronizeQueue(Object mutex) { return PRIORITY_QUEUES.synchronize(this, mutex); }
public default CLASS_TYPE dequeueLast() { return KEY_TO_OBJ(DEQUEUE_LAST()); }
/**
* Peeking function for the last element
* @return the Last Element within the dequeue without deleting it as boxed element
*/
@Deprecated
public default CLASS_TYPE last() { return peek(size()-1); }
#endif #endif
@Override
public PRIORITY_DEQUEUE KEY_GENERIC_TYPE copy();
} }
@@ -1,120 +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;
#else import java.util.Collection;
import speiger.src.collections.PACKAGE.collections.ITERABLE; import java.util.Iterator;
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import java.util.function.IntFunction;
import speiger.src.collections.objects.queues.ObjectPriorityQueue; #else
#endif import speiger.src.collections.PACKAGE.functions.COMPARATOR;
#endif
/** import speiger.src.collections.PACKAGE.collections.COLLECTION;
* A Simple PriorityQueue (or Queue) interface that provides with the nessesary functions to interact with it, without cluttering with the Collection interface. import speiger.src.collections.PACKAGE.collections.ITERABLE;
* @Type(T) import speiger.src.collections.PACKAGE.collections.ITERATOR;
*/ #if QUEUES_FEATURE
#if TYPE_OBJECT import speiger.src.collections.PACKAGE.utils.PRIORITY_QUEUES;
public interface PRIORITY_QUEUE KEY_GENERIC_TYPE extends Iterable<KEY_TYPE> #endif
#else
public interface PRIORITY_QUEUE KEY_GENERIC_TYPE extends ObjectPriorityQueue<CLASS_TYPE>, ITERABLE KEY_GENERIC_TYPE
#endif /**
{ * A Simple PriorityQueue (or Queue) interface that provides with the nessesary functions to interact with it, without cluttering with the Collection interface.
#if TYPE_OBJECT * @Type(T)
/** */
* @return true if the PriorityQueue is empty public interface PRIORITY_QUEUE KEY_GENERIC_TYPE extends ITERABLE KEY_GENERIC_TYPE
*/ {
public default boolean isEmpty() { return size() <= 0; } /**
/** * @return true if the PriorityQueue is empty
* @return the amount of elements that are stored in the PriorityQueue */
*/ public default boolean isEmpty() { return size() <= 0; }
public int size(); /**
/** * @return the amount of elements that are stored in the PriorityQueue
* clears all elements within the PriorityQueue, */
* this does not resize the backing arrays public int size();
*/ /**
public void clear(); * clears all elements within the PriorityQueue,
* this does not resize the backing arrays
#endif */
/** public void clear();
* Method to insert a element into the PriorityQueue
* @param e the element that should be inserted /**
*/ * Method to insert a element into the PriorityQueue
public void ENQUEUE(KEY_TYPE e); * @param e the element that should be inserted
/** */
* Method to extract a element from the PriorityQueue public void enqueue(KEY_TYPE e);
* @return a element from the Queue
* @throws java.util.NoSuchElementException if no element is present /**
*/ * Method to mass insert elements into the PriorityQueue
public KEY_TYPE DEQUEUE(); * @param e the elements that should be inserted
*/
/** public default void enqueueAll(KEY_TYPE... e) {
* Peeking function to see whats inside the queue. enqueueAll(e, 0, e.length);
* @param index of the element that is requested to be viewed. }
* @return the element that is requested
*/ /**
public KEY_TYPE PEEK(int index); * Method to mass insert elements into the PriorityQueue
/** * @param e the elements that should be inserted
* Shows the element that is to be returned next * @param length the amount of elements that should be inserted
* @return the first element in the Queue */
*/ public default void enqueueAll(KEY_TYPE[] e, int length) {
public default KEY_TYPE FIRST_KEY() { return PEEK(0); } enqueueAll(e, 0, length);
}
/**
* Removes the first found element in the queue /**
* @param e the element that should be removed * Method to mass insert elements into the PriorityQueue
* @return if a searched element was removed * @param e the elements that should be inserted
*/ * @param offset the offset where in the array should be started
public boolean REMOVE(KEY_TYPE e); * @param length the amount of elements that should be inserted
/** */
* Removes the last found element in the queue public default void enqueueAll(KEY_TYPE[] e, int offset, int length) {
* @param e the element that should be removed for(int i = 0;i<length;i++)
* @return if a searched element was removed enqueue(e[i+offset]);
*/ }
public boolean REMOVE_LAST(KEY_TYPE e);
/**
/** * Method to mass insert elements into the PriorityQueue
* Allows to notify the Queue to be revalidate its data * @param c the elements that should be inserted from the Collection
*/ */
public void onChanged(); public default void enqueueAll(COLLECTION KEY_GENERIC_TYPE c) {
for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();)
/** enqueue(iter.NEXT());
* @return the sorter of the Queue, can be null }
*/
@PrimitiveOverride #if TYPE_OBJECT
public COMPARATOR KEY_SUPER_GENERIC_TYPE comparator(); /**
* Method to mass insert elements into the PriorityQueue
/** * This method exists to add support for Java Collections to make it more useable
* A method to drop the contents of the Queue without clearing the queue * @param c the elements that should be inserted from the Collection
* @return the contents of the queue into a seperate array. */
*/ public default void enqueueAll(Collection<? extends CLASS_TYPE> c) {
public default KEY_TYPE[] TO_ARRAY() { return TO_ARRAY(NEW_KEY_ARRAY(size())); } for(Iterator<? extends CLASS_TYPE> iter = c.iterator();iter.hasNext();)
/** enqueue(iter.next());
* 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
* @return the contents of the queue into a seperate array. #endif
* @note if the Type is generic then a Object Array is created instead of a Type Array
*/ /**
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] input); * Method to extract a element from the PriorityQueue
* @return a element from the Queue
#if !TYPE_OBJECT * @throws java.util.NoSuchElementException if no element is present
@Deprecated */
public default void enqueue(CLASS_TYPE e) { ENQUEUE(OBJ_TO_KEY(e)); } public KEY_TYPE dequeue();
@Deprecated
public default CLASS_TYPE dequeue() { return KEY_TO_OBJ(DEQUEUE()); } /**
* Peeking function to see whats inside the queue.
@Deprecated * @param index of the element that is requested to be viewed.
public default CLASS_TYPE peek(int index) { return KEY_TO_OBJ(PEEK(index)); } * @return the element that is requested
@Deprecated */
public default CLASS_TYPE first() { return peek(0); } public KEY_TYPE peek(int index);
/**
@Deprecated * Shows the element that is to be returned next
public default boolean remove(CLASS_TYPE e) { return REMOVE(OBJ_TO_KEY(e)); } * @return the first element in the Queue
@Deprecated */
public default boolean removeLast(CLASS_TYPE e) { return REMOVE_LAST(OBJ_TO_KEY(e)); } public default KEY_TYPE first() { return peek(0); }
@Deprecated /**
public default CLASS_TYPE[] toArray() { return toArray(new CLASS_TYPE[size()]); } * Method to find out if a element is part of the queue
@Deprecated * @param e the element that is searched for
public CLASS_TYPE[] toArray(CLASS_TYPE[] input); * @return true if the element is in the queue
*/
#endif public boolean contains(KEY_TYPE e);
}
/**
* Removes the first found element in the queue
* @param e the element that should be removed
* @return if a searched element was removed
*/
public boolean removeFirst(KEY_TYPE e);
/**
* Removes the last found element in the queue
* @param e the element that should be removed
* @return if a searched element was removed
*/
public boolean removeLast(KEY_TYPE e);
/**
* Allows to notify the Queue to be revalidate its data
*/
public void onChanged();
/**
* A Function that does a shallow clone of the PriorityQueue itself.
* This function is more optimized then a copy constructor since the PriorityQueue does not have to be unsorted/resorted.
* It can be compared to Cloneable but with less exception risk
* @return a Shallow Copy of the PriorityQueue
* @note Wrappers and view PriorityQueues will not support this feature
*/
public PRIORITY_QUEUE KEY_GENERIC_TYPE copy();
/**
* @return the sorter of the Queue, can be null
*/
public COMPARATOR KEY_SUPER_GENERIC_TYPE comparator();
#if TYPE_OBJECT
/**
* @return draining iterator of the PriorityQueue
*/
public ITERATOR KEY_GENERIC_TYPE iterator();
#endif
#if QUEUES_FEATURE
/**
* Creates a Wrapped PriorityQueue that is Synchronized
* @return a new PriorityQueue that is synchronized
* @see PRIORITY_QUEUES#synchronize
*/
public default PRIORITY_QUEUE KEY_GENERIC_TYPE synchronizeQueue() { return PRIORITY_QUEUES.synchronize(this); }
/**
* Creates a Wrapped PriorityQueue that is Synchronized
* @param mutex is the controller of the synchronization block
* @return a new PriorityQueue Wrapper that is synchronized
* @see PRIORITY_QUEUES#synchronize
*/
public default PRIORITY_QUEUE KEY_GENERIC_TYPE synchronizeQueue(Object mutex) { return PRIORITY_QUEUES.synchronize(this, mutex); }
#endif
/**
* A method to drop the contents of the Queue without clearing the queue
* @Type(E)
* @return the contents of the queue into a seperate array.
*/
public default GENERIC_SPECIAL_KEY_BRACES<E> KEY_SPECIAL_TYPE[] TO_ARRAY() { return TO_ARRAY(NEW_SPECIAL_KEY_ARRAY(size())); }
/**
* A method to drop the contents of the Queue without clearing the queue
* @param input where the elements should be inserted to. If it does not fit then it creates a new appropiatly created array
* @Type(E)
* @return the contents of the queue into a seperate array.
* @note if the Type is generic then a Object Array is created instead of a Type Array
*/
public GENERIC_SPECIAL_KEY_BRACES<E> KEY_SPECIAL_TYPE[] TO_ARRAY(KEY_SPECIAL_TYPE[] input);
#if TYPE_OBJECT
/**
* A Helper function that simplifies the process of creating a new Array.
* @param action the array creation function
* @param <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,56 +1,50 @@
package speiger.src.collections.PACKAGE.sets; package speiger.src.collections.PACKAGE.sets;
import java.util.Iterator; #if TYPE_OBJECT
import java.util.Objects; import java.util.Objects;
import java.util.Set; #endif
import java.util.Set;
import speiger.src.collections.PACKAGE.collections.ABSTRACT_COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ABSTRACT_COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR;
/**
* Abstract Type Specific Set that reduces boxing/unboxing /**
* @Type(T) * 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
@Override {
public abstract ITERATOR KEY_GENERIC_TYPE iterator(); #if TYPE_OBJECT
@Override
@Override public KEY_TYPE addOrGet(KEY_TYPE o) { throw new UnsupportedOperationException(); }
public int hashCode() {
int hashCode = 1; #endif
ITERATOR KEY_GENERIC_TYPE i = iterator(); @Override
while(i.hasNext()) public abstract ITERATOR KEY_GENERIC_TYPE iterator();
hashCode = 31 * hashCode + KEY_TO_HASH(i.NEXT()); @Override
return hashCode; public ABSTRACT_SET KEY_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); }
}
@Override
@Override public int hashCode() {
public boolean equals(Object o) { int hashCode = 0;
if (o == this) ITERATOR KEY_GENERIC_TYPE i = iterator();
return true; while(i.hasNext())
if (!(o instanceof Set)) hashCode += KEY_TO_HASH(i.NEXT());
return false; return hashCode;
Set<?> l = (Set<?>)o; }
if(l.size() != size()) return false;
#if !TYPE_OBJECT @Override
if(l instanceof SET) public boolean equals(Object o) {
{ if (o == this)
ITERATOR e1 = iterator(); return true;
ITERATOR e2 = ((SET)l).iterator(); if (!(o instanceof Set))
while (e1.hasNext() && e2.hasNext()) { return false;
if(!(KEY_EQUALS(e1.NEXT(), e2.NEXT()))) Set<?> l = (Set<?>)o;
return false; if(l.size() != size()) return false;
} try {
return !(e1.hasNext() || e2.hasNext()); return containsAll(l);
} } catch (ClassCastException | NullPointerException unused) {
#endif return false;
Iterator<CLASS_TYPE> e1 = iterator(); }
Iterator<?> e2 = l.iterator(); }
while (e1.hasNext() && e2.hasNext()) { }
if(!Objects.equals(e1.next(), e2.next()))
return false;
}
return !(e1.hasNext() || e2.hasNext());
}
}
@@ -3,26 +3,36 @@ package speiger.src.collections.PACKAGE.sets;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Comparator;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.BiFunction;
#endif #endif
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Objects; import java.util.Objects;
import java.util.Set; import java.util.Set;
#if PRIMITIVES #if JDK_FUNCTION
import java.util.function.PREDICATE;
#endif
#if PRIMITIVES && !JDK_FUNCTION
import java.util.function.JAVA_PREDICATE; import java.util.function.JAVA_PREDICATE;
#endif #endif
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;
import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER;
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
#if !JDK_FUNCTION
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
#endif
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER; import speiger.src.collections.PACKAGE.functions.CONSUMER;
import speiger.src.collections.objects.utils.ObjectArrays;
#endif #endif
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
import speiger.src.collections.PACKAGE.utils.ARRAYS; import speiger.src.collections.PACKAGE.utils.ARRAYS;
/** /**
* A Type Specific ArraySet implementation. * A Type Specific ArraySet implementation.
* That is based around the idea of {@link java.util.List#indexOf(Object)} for no duplication. * That is based around the idea of {@link java.util.List#indexOf(Object)} for no duplication.
@@ -30,7 +40,7 @@ import speiger.src.collections.PACKAGE.utils.ARRAYS;
* This implementation does not shrink the backing array * This implementation does not shrink the backing array
* @Type(T) * @Type(T)
*/ */
public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE
{ {
/** The Backing Array */ /** The Backing Array */
protected transient KEY_TYPE[] data; protected transient KEY_TYPE[] data;
@@ -50,6 +60,7 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
* @throws NegativeArraySizeException if the capacity is negative * @throws NegativeArraySizeException if the capacity is negative
*/ */
public ARRAY_SET(int capacity) { public ARRAY_SET(int capacity) {
if(capacity < 0) throw new IllegalStateException("Size has to be 0 or greater");
data = NEW_KEY_ARRAY(capacity); data = NEW_KEY_ARRAY(capacity);
} }
@@ -68,8 +79,8 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
* @throws NegativeArraySizeException if the length is negative * @throws NegativeArraySizeException if the length is negative
*/ */
public ARRAY_SET(KEY_TYPE[] array, int length) { public ARRAY_SET(KEY_TYPE[] array, int length) {
data = Arrays.copyOf(array, length); this(length);
size = length; addAll(array, length);
} }
/** /**
@@ -77,7 +88,7 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
* @param c the elements that should be added to the set. * @param c the elements that should be added to the set.
* @note this slowly checks every element to remove duplicates * @note this slowly checks every element to remove duplicates
*/ */
@Deprecated @Primitive
public ARRAY_SET(Collection<? extends CLASS_TYPE> c) { public ARRAY_SET(Collection<? extends CLASS_TYPE> c) {
this(c.size()); this(c.size());
addAll(c); addAll(c);
@@ -98,7 +109,7 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
* Since it is assumed that there is no duplication in the first place * Since it is assumed that there is no duplication in the first place
* @param s the set the element should be taken from * @param s the set the element should be taken from
*/ */
@Deprecated @Primitive
public ARRAY_SET(Set<? extends CLASS_TYPE> s) { public ARRAY_SET(Set<? extends CLASS_TYPE> s) {
this(s.size()); this(s.size());
for(CLASS_TYPE e : s) for(CLASS_TYPE e : s)
@@ -126,6 +137,17 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
return false; return false;
} }
#if TYPE_OBJECT
@Override
public KEY_TYPE addOrGet(KEY_TYPE o) {
int index = findIndex(o);
if(index != -1) return data[index];
if(data.length == size) data = Arrays.copyOf(data, size == 0 ? 2 : size * 2);
data[size++] = o;
return o;
}
#endif
@Override @Override
public boolean addAndMoveToFirst(KEY_TYPE o) { public boolean addAndMoveToFirst(KEY_TYPE o) {
int index = findIndex(o); int index = findIndex(o);
@@ -153,7 +175,7 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
} }
else if(index != size - 1) { else if(index != size - 1) {
o = data[index]; o = data[index];
System.arraycopy(data, index+1, data, index, size - index); System.arraycopy(data, index+1, data, index, size - index - 1);
data[size-1] = o; data[size-1] = o;
} }
return false; return false;
@@ -208,6 +230,98 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
return data[size - 1]; return data[size - 1];
} }
@Override
public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) {
int j = 0;
for(int i = 0;i<size;i++) {
if(!c.contains(data[i]))
data[j++] = data[i];
}
boolean result = j != size;
#if TYPE_OBJECT
Arrays.fill(data, j, size, null);
#endif
size = j;
return result;
}
@Override
public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) {
int j = 0;
for(int i = 0;i<size;i++) {
if(!c.contains(data[i])) data[j++] = data[i];
else r.accept(data[i]);
}
boolean result = j != size;
#if TYPE_OBJECT
Arrays.fill(data, j, size, null);
#endif
size = j;
return result;
}
@Override
public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) {
int j = 0;
for(int i = 0;i<size;i++) {
if(c.contains(data[i]))
data[j++] = data[i];
}
boolean result = j != size;
#if TYPE_OBJECT
Arrays.fill(data, j, size, null);
#endif
size = j;
return result;
}
@Override
public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) {
int j = 0;
for(int i = 0;i<size;i++) {
if(c.contains(data[i])) data[j++] = data[i];
else r.accept(data[i]);
}
boolean result = j != size;
#if TYPE_OBJECT
Arrays.fill(data, j, size, null);
#endif
size = j;
return result;
}
@Override
@Primitive
public boolean removeAll(Collection<?> c) {
int j = 0;
for(int i = 0;i<size;i++) {
if(!c.contains(KEY_TO_OBJ(data[i])))
data[j++] = data[i];
}
boolean result = j != size;
#if TYPE_OBJECT
Arrays.fill(data, j, size, null);
#endif
size = j;
return result;
}
@Override
@Primitive
public boolean retainAll(Collection<?> c) {
int j = 0;
for(int i = 0;i<size;i++) {
if(c.contains(KEY_TO_OBJ(data[i])))
data[j++] = data[i];
}
boolean result = j != size;
#if TYPE_OBJECT
Arrays.fill(data, j, size, null);
#endif
size = j;
return result;
}
#if !TYPE_OBJECT #if !TYPE_OBJECT
@Override @Override
public boolean remove(KEY_TYPE o) { public boolean remove(KEY_TYPE o) {
@@ -277,21 +391,110 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
} }
#endif #endif
#if TYPE_OBJECT
@Override @Override
public void forEach(Consumer KEY_SUPER_GENERIC_TYPE action) { public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action); Objects.requireNonNull(action);
for(int i = 0;i<size;action.accept(data[i++])); for(int i = 0;i<size;action.accept(data[i++]));
} }
@Override
public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) {
Objects.requireNonNull(action);
for(int i = 0;i<size;action.accept(i, data[i++]));
}
@Override
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
for(int i = 0;i<size;i++)
action.accept(input, data[i]);
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(filter.test(data[i])) return true;
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(filter.test(data[i])) return false;
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(!filter.test(data[i])) return false;
}
return true;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(filter.test(data[i])) return data[i];
}
return EMPTY_VALUE;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
for(int i = 0;i<size;i++) {
state = operator.APPLY_VALUE(state, data[i]);
}
return state;
}
#else #else
@Override @Override
public void forEach(CONSUMER KEY_GENERIC_TYPE action) { public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
Objects.requireNonNull(action); Objects.requireNonNull(operator);
for(int i = 0;i<size;action.accept(data[i++])); KEY_SPECIAL_TYPE state = identity;
for(int i = 0;i<size;i++) {
state = operator.APPLY_VALUE(state, data[i]);
}
return state;
} }
#endif #endif
@Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_VALUE;
boolean empty = true;
for(int i = 0;i<size;i++) {
if(empty) {
empty = false;
state = data[i];
continue;
}
state = operator.APPLY_VALUE(state, data[i]);
}
return state;
}
@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(data[i])) result++;
}
return result;
}
#if !TYPE_OBJECT #if !TYPE_OBJECT
protected int findIndex(KEY_TYPE o) { protected int findIndex(KEY_TYPE o) {
for(int i = size-1;i>=0;i--) for(int i = size-1;i>=0;i--)
@@ -318,31 +521,11 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
throw new NoSuchElementException(); throw new NoSuchElementException();
} }
@Override public ARRAY_SET KEY_GENERIC_TYPE copy() {
public SORTED_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) { ARRAY_SET KEY_GENERIC_TYPE set = new ARRAY_SETBRACES();
int fromIndex = findIndex(fromElement); set.data = Arrays.copyOf(data, data.length);
int toIndex = findIndex(toElement); set.size = size;
if(fromIndex == -1 || toIndex == -1) throw new NoSuchElementException(); return set;
return new SubSet(fromIndex, toIndex - fromIndex + 1);
}
@Override
public SORTED_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) {
int toIndex = findIndex(toElement);
if(toIndex == -1) throw new NoSuchElementException();
return new SubSet(0, toIndex+1);
}
@Override
public SORTED_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement) {
int fromIndex = findIndex(fromElement);
if(fromIndex == -1) throw new NoSuchElementException();
return new SubSet(fromIndex, size - fromIndex);
}
@Override
public COMPARATOR KEY_GENERIC_TYPE comparator() {
return null;
} }
@Override @Override
@@ -355,313 +538,37 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
return size; return size;
} }
private class SubSet extends ABSTRACT_SET KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE {
int offset;
int length;
SubSet(int offset, int length) {
this.offset = offset;
this.length = length;
}
int end() { return offset+length; }
@Override
public boolean add(KEY_TYPE o) {
int index = findIndex(o);
if(index == -1) {
if(data.length == size) data = Arrays.copyOf(data, size == 0 ? 2 : size * 2);
if(end() != size) System.arraycopy(data, end(), data, end()+1, size-(offset+length));
data[end()] = o;
size++;
length++;
return true;
}
return false;
}
@Override
public boolean addAndMoveToFirst(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, offset, data, offset+1, size-offset);
data[offset] = o;
size++;
length++;
return true;
}
else if(index != 0) {
o = data[index];
System.arraycopy(data, offset, data, offset+1, index-offset);
data[offset] = o;
}
return false;
}
@Override
public boolean addAndMoveToLast(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, end()+1, data, end(), size-end());
data[end()] = o;
size++;
length++;
return true;
}
else if(index != 0) {
o = data[index];
System.arraycopy(data, offset+1, data, offset, index-offset);
data[offset+length] = o;
}
return false;
}
@Override
public boolean moveToFirst(KEY_TYPE o) {
int index = findIndex(o);
if(index > offset) {
o = data[index];
System.arraycopy(data, offset, data, offset+1, index-offset);
data[offset] = o;
return true;
}
return false;
}
@Override
public boolean moveToLast(KEY_TYPE o) {
int index = findIndex(o);
if(index != -1 && index < end()-1) {
o = data[index];
System.arraycopy(data, index+1, data, index, end()-index-1);
data[end()-1] = o;
return true;
}
return false;
}
#if !TYPE_OBJECT #if !TYPE_OBJECT
@Override @Override
public boolean contains(KEY_TYPE e) { public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) {
return findIndex(e) != -1; if(a == null || a.length < size()) return Arrays.copyOf(data, size());
} System.arraycopy(data, 0, a, 0, size());
if (a.length > size) a[size] = EMPTY_KEY_VALUE;
#endif return a;
@Override
public boolean contains(Object e) {
return findIndex(e) != -1;
}
@Override
public KEY_TYPE FIRST_KEY() {
if(length == 0) throw new NoSuchElementException();
return data[offset];
}
@Override
public KEY_TYPE LAST_KEY() {
if(length == 0) throw new NoSuchElementException();
return data[end()-1];
}
#if !TYPE_OBJECT
@Override
public boolean remove(KEY_TYPE o) {
int index = findIndex(o);
if(index != -1) {
size--;
length--;
if(index != size) System.arraycopy(data, index+1, data, index, size - index);
return true;
}
return false;
}
#endif
@Override
public boolean remove(Object o) {
int index = findIndex(o);
if(index != -1) {
size--;
length--;
if(index != size) System.arraycopy(data, index+1, data, index, size - index);
#if TYPE_OBJECT
data[size] = EMPTY_KEY_VALUE;
#endif
return true;
}
return false;
}
@Override
public KEY_TYPE POLL_FIRST_KEY() {
if(length == 0) throw new NoSuchElementException();
size--;
length--;
KEY_TYPE result = data[offset];
System.arraycopy(data, offset+1, data, offset, size-offset);
#if TYPE_OBJECT
data[size] = EMPTY_KEY_VALUE;
#endif
return result;
}
@Override
public KEY_TYPE POLL_LAST_KEY() {
if(length == 0) throw new NoSuchElementException();
KEY_TYPE result = data[offset+length];
size--;
length--;
System.arraycopy(data, end()+1, data, end(), size-end());
#if TYPE_OBJECT
data[size] = EMPTY_KEY_VALUE;
#endif
return result;
}
@Override
public COMPARATOR KEY_GENERIC_TYPE comparator() {
return null;
}
@Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator() {
return new SetIterator(offset);
}
@Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) {
int index = findIndex(fromElement);
if(index != -1) return new SetIterator(index);
throw new NoSuchElementException();
}
@Override
public SORTED_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) {
int fromIndex = findIndex(fromElement);
int toIndex = findIndex(toElement);
if(fromIndex == -1 || toIndex == -1) throw new NoSuchElementException();
return new SubSet(fromIndex, toIndex - fromIndex);
}
@Override
public SORTED_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) {
int toIndex = findIndex(toElement);
if(toIndex == -1) throw new NoSuchElementException();
return new SubSet(0, toIndex);
}
@Override
public SORTED_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement) {
int fromIndex = findIndex(fromElement);
if(fromIndex == -1) throw new NoSuchElementException();
return new SubSet(fromIndex, size - fromIndex);
}
@Override
public int size() {
return length;
}
#if !TYPE_OBJECT
protected int findIndex(KEY_TYPE o) {
for(int i = length-1;i>=0;i--)
if(KEY_EQUALS(data[offset+i], o)) return i + offset;
return -1;
}
#endif
protected int findIndex(Object o) {
for(int i = length-1;i>=0;i--)
if(EQUALS_KEY_TYPE(data[offset+i], o)) return i + offset;
return -1;
}
private class SetIterator implements LIST_ITERATOR KEY_GENERIC_TYPE {
int index;
int lastReturned = -1;
public SetIterator(int index) {
this.index = index;
}
@Override
public boolean hasNext() {
return index < size();
}
@Override
public KEY_TYPE NEXT() {
lastReturned = index;
return data[index++];
}
@Override
public boolean hasPrevious() {
return index > 0;
}
@Override
public KEY_TYPE PREVIOUS() {
lastReturned = index;
return data[index--];
}
@Override
public int nextIndex() {
return index;
}
@Override
public int previousIndex() {
return index-1;
}
@Override
public void remove() {
if(lastReturned == -1)
throw new IllegalStateException();
SubSet.this.remove(data[lastReturned]);
if(lastReturned < index)
index--;
lastReturned = -1;
}
#if TYPE_OBJECT
@Override
public void set(Object e) { throw new UnsupportedOperationException(); }
@Override
public void add(Object e) { throw new UnsupportedOperationException(); }
#else
@Override
public void set(KEY_TYPE e) { throw new UnsupportedOperationException(); }
@Override
public void add(KEY_TYPE e) { throw new UnsupportedOperationException(); }
#endif
@Override
public int skip(int amount) {
if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
int steps = Math.min(amount, (size() - 1) - index);
index += steps;
return steps;
}
@Override
public int back(int amount) {
if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
int steps = Math.min(amount, index);
index -= steps;
return steps;
}
}
} }
#endif
@Override
@Deprecated
public Object[] toArray() {
if(isEmpty()) return ObjectArrays.EMPTY_ARRAY;
Object[] obj = new Object[size()];
for(int i = 0;i<size();i++)
obj[i] = KEY_TO_OBJ(data[i]);
return obj;
}
@Override
@Primitive
public <E> E[] toArray(E[] a) {
if(a == null) a = (E[])new Object[size()];
else if(a.length < size()) a = (E[])ObjectArrays.newArray(a.getClass().getComponentType(), size());
for(int i = 0;i<size();i++)
a[i] = (E)KEY_TO_OBJ(data[i]);
if (a.length > size) a[size] = null;
return a;
}
private class SetIterator implements LIST_ITERATOR KEY_GENERIC_TYPE { private class SetIterator implements LIST_ITERATOR KEY_GENERIC_TYPE {
int index; int index;
int lastReturned = -1; int lastReturned = -1;
@@ -677,6 +584,7 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
@Override @Override
public KEY_TYPE NEXT() { public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
lastReturned = index; lastReturned = index;
return data[index++]; return data[index++];
} }
@@ -688,8 +596,9 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
@Override @Override
public KEY_TYPE PREVIOUS() { public KEY_TYPE PREVIOUS() {
lastReturned = index; if(!hasPrevious()) throw new NoSuchElementException();
return data[index--]; --index;
return data[(lastReturned = index)];
} }
@Override @Override
@@ -704,11 +613,9 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
@Override @Override
public void remove() { public void remove() {
if(lastReturned == -1) if(lastReturned == -1) throw new IllegalStateException();
throw new IllegalStateException();
ARRAY_SET.this.remove(data[lastReturned]); ARRAY_SET.this.remove(data[lastReturned]);
if(lastReturned < index) if(lastReturned < index) index--;
index--;
lastReturned = -1; lastReturned = -1;
} }
@@ -730,8 +637,9 @@ 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");
int steps = Math.min(amount, (size() - 1) - index); int steps = Math.min(amount, size() - index);
index += steps; index += steps;
if(steps > 0) lastReturned = Math.min(index-1, size()-1);
return steps; return steps;
} }
@@ -740,6 +648,7 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
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);
return steps; return steps;
} }
} }
@@ -0,0 +1,656 @@
package speiger.src.collections.PACKAGE.sets;
#if TYPE_OBJECT
import java.util.function.Consumer;
import java.util.function.BiFunction;
#endif
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
#if JDK_FUNCTION
import java.util.function.PREDICATE;
#endif
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR;
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif
import speiger.src.collections.ints.functions.consumer.BI_FROM_INT_CONSUMER;
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
#if !JDK_FUNCTION
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
#endif
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
import speiger.src.collections.PACKAGE.utils.ARRAYS;
#if !TYPE_OBJECT
import speiger.src.collections.objects.utils.ObjectArrays;
#endif
import speiger.src.collections.PACKAGE.utils.ITERATORS;
import speiger.src.collections.utils.HashUtil;
import speiger.src.collections.utils.SanityChecks;
/**
* A Type Specific Custom implementation of the HashSet
* Instead of using Wrapper Object Arrays for storing keys and values there is dedicated arrays for storing keys.
* Extra to that there is a couple quality of life functions provided
* @Type(T)
*/
public class IMMUTABLE_HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE
{
/** The Backing keys array */
protected transient KEY_TYPE[] keys;
/** The Backing array for links between nodes. Left 32 Bits => Previous Entry, Right 32 Bits => Next Entry */
protected transient long[] links;
/** If a null value is present */
protected transient boolean containsNull;
/** Index of the Null Value */
protected transient int nullIndex;
/** Max Index that is allowed to be searched through nullIndex - 1 */
protected transient int mask;
/** Amount of Elements stored in the HashSet */
protected int size;
/** The First Index in the Map */
protected int firstIndex = -1;
/** The Last Index in the Map */
protected int lastIndex = -1;
/**
* Helper constructor to optimize the copying
* Only accessible through implementations
*/
protected IMMUTABLE_HASH_SET() {}
/**
* Helper constructor that allow to create a set from unboxed values
* @param array the elements that should be put into the set
*/
public IMMUTABLE_HASH_SET(KEY_TYPE[] array) {
this(array, 0, array.length, HashUtil.DEFAULT_LOAD_FACTOR);
}
/**
* Helper constructor that allow to create a set from unboxed values
* @param array the elements that should be put into the set
* @param loadFactor the percentage of how full the backing array can be before they resize
* @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
*/
public IMMUTABLE_HASH_SET(KEY_TYPE[] array, float loadFactor) {
this(array, 0, array.length, loadFactor);
}
/**
* Helper constructor that allow to create a set from unboxed values
* @param array the elements that should be put into the set
* @param offset the starting index within the array that should be used
* @param length the amount of elements used from the array
* @throws IllegalStateException if offset and length causes to step outside of the arrays range
*/
public IMMUTABLE_HASH_SET(KEY_TYPE[] array, int offset, int length) {
this(array, offset, length, HashUtil.DEFAULT_LOAD_FACTOR);
}
/**
* Helper constructor that allow to create a set from unboxed values
* @param array the elements that should be put into the set
* @param offset the starting index within the array that should be used
* @param length the amount of elements used from the array
* @param loadFactor the percentage of how full the backing array can be before they resize
* @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
* @throws IllegalStateException if offset and length causes to step outside of the arrays range
*/
public IMMUTABLE_HASH_SET(KEY_TYPE[] array, int offset, int length, float loadFactor) {
init(array, offset, length, loadFactor);
}
/**
* A Helper constructor that allows to create a Set with exactly the same values as the provided collection.
* @param collection the set the elements should be added to the Set
*/
@Primitive
public IMMUTABLE_HASH_SET(Collection<? extends CLASS_TYPE> collection) {
this(collection, HashUtil.DEFAULT_LOAD_FACTOR);
}
/**
* A Helper constructor that allows to create a Set with exactly the same values as the provided collection.
* @param collection the set the elements should be added to the Set
* @param loadFactor the percentage of how full the backing array can be before they resize
* @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
*/
@Primitive
public IMMUTABLE_HASH_SET(Collection<? extends CLASS_TYPE> collection, float loadFactor) {
#if !TYPE_OBJECT
init(ARRAYS.unwrap(collection.toArray(NEW_CLASS_ARRAY(collection.size()))), 0, collection.size(), loadFactor);
#else
init(collection.toArray(NEW_CLASS_ARRAY(collection.size())), 0, collection.size(), loadFactor);
#endif
}
/**
* A Helper constructor that allows to create a Set with exactly the same values as the provided collection.
* @param collection the set the elements should be added to the Set
*/
public IMMUTABLE_HASH_SET(COLLECTION KEY_GENERIC_TYPE collection) {
this(collection, HashUtil.DEFAULT_LOAD_FACTOR);
}
/**
* A Helper constructor that allows to create a Set with exactly the same values as the provided collection.
* @param collection the set the elements should be added to the Set
* @param loadFactor the percentage of how full the backing array can be before they resize
* @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
*/
public IMMUTABLE_HASH_SET(COLLECTION KEY_GENERIC_TYPE collection, float loadFactor) {
init(collection.TO_ARRAY(NEW_KEY_ARRAY(collection.size())), 0, collection.size(), loadFactor);
}
/**
* A Helper constructor that allows to create a set from a iterator of an unknown size
* @param iterator the elements that should be added to the set
*/
public IMMUTABLE_HASH_SET(Iterator<CLASS_TYPE> iterator) {
this(iterator, HashUtil.DEFAULT_LOAD_FACTOR);
}
/**
* A Helper constructor that allows to create a set from a iterator of an unknown size
* @param iterator the elements that should be added to the set
* @param loadFactor the percentage of how full the backing array can be before they resize
* @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
*/
public IMMUTABLE_HASH_SET(Iterator<CLASS_TYPE> iterator, float loadFactor) {
this(ITERATORS.wrap(iterator), loadFactor);
}
/**
* A Helper constructor that allows to create a set from a iterator of an unknown size
* @param iterator the elements that should be added to the set
*/
public IMMUTABLE_HASH_SET(ITERATOR KEY_GENERIC_TYPE iterator) {
this(iterator, HashUtil.DEFAULT_LOAD_FACTOR);
}
/**
* A Helper constructor that allows to create a set from a iterator of an unknown size
* @param iterator the elements that should be added to the set
* @param loadFactor the percentage of how full the backing array can be before they resize
* @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
*/
public IMMUTABLE_HASH_SET(ITERATOR KEY_GENERIC_TYPE iterator, float loadFactor) {
KEY_TYPE[] array = ARRAYS.pour(iterator);
init(array, 0, array.length, loadFactor);
}
protected void init(KEY_TYPE[] a, int offset, int length, float loadFactor) {
SanityChecks.checkArrayCapacity(a.length, offset, length);
int newSize = HashUtil.arraySize(length+1, loadFactor);
int newMask = newSize - 1;
KEY_TYPE[] newKeys = NEW_KEY_ARRAY(newSize + 1);
long[] newLinks = new long[newSize + 1];
int prev = -1;
for(int i = offset,m=offset+length;i<m;i++)
{
KEY_TYPE o = a[i];
if(KEY_EQUALS_NULL(o)) {
if(!containsNull) {
size++;
if(prev != -1) {
newLinks[prev] ^= ((newLinks[prev] ^ (newSize & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
newLinks[newSize] ^= ((newLinks[newSize] ^ ((prev & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L);
prev = newSize;
}
else {
prev = firstIndex = newSize;
newLinks[newSize] = -1L;
}
}
containsNull = true;
continue;
}
boolean found = true;
int pos = HashUtil.mix(KEY_TO_HASH(o)) & newMask;
KEY_TYPE current = newKeys[pos];
if(KEY_EQUALS_NOT_NULL(current)) {
if(KEY_EQUALS(current, o)) continue;
while(KEY_EQUALS_NOT_NULL((current = newKeys[pos = (++pos & newMask)]))) {
if(KEY_EQUALS(current, o)) {
found = false;
break;
}
}
}
if(found) {
size++;
newKeys[pos] = o;
if(prev != -1) {
newLinks[prev] ^= ((newLinks[prev] ^ (pos & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
newLinks[pos] ^= ((newLinks[pos] ^ ((prev & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L);
prev = pos;
}
else {
prev = firstIndex = pos;
newLinks[pos] = -1L;
}
}
}
nullIndex = newSize;
mask = newMask;
keys = newKeys;
links = newLinks;
lastIndex = prev;
if(prev != -1) newLinks[prev] |= 0xFFFFFFFFL;
}
@Override
public boolean add(KEY_TYPE o) { throw new UnsupportedOperationException(); }
#if TYPE_OBJECT
@Override
public KEY_TYPE addOrGet(KEY_TYPE o) { throw new UnsupportedOperationException(); }
#endif
@Override
@Primitive
public boolean addAll(Collection<? extends CLASS_TYPE> c) { throw new UnsupportedOperationException(); }
@Override
public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); }
@Override
public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public boolean addAndMoveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public boolean moveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public boolean moveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public boolean contains(Object o) {
#if TYPE_OBJECT
if(o == null) return containsNull;
#else
if(o == null) return false;
if(o instanceof CLASS_TYPE && KEY_EQUALS(CLASS_TO_KEY(o), EMPTY_KEY_VALUE)) return containsNull;
#endif
int pos = HashUtil.mix(o.hashCode()) & mask;
KEY_TYPE current = keys[pos];
if(KEY_EQUALS_NULL(current)) return false;
if(EQUALS_KEY_TYPE(current, o)) return true;
while(true) {
if(KEY_EQUALS_NULL((current = keys[pos = (++pos & mask)]))) return false;
else if(EQUALS_KEY_TYPE(current, o)) return true;
}
}
@Override
public KEY_TYPE FIRST_KEY() {
if(size == 0) throw new NoSuchElementException();
return keys[firstIndex];
}
@Override
public KEY_TYPE POLL_FIRST_KEY() { throw new UnsupportedOperationException(); }
@Override
public KEY_TYPE LAST_KEY() {
if(size == 0) throw new NoSuchElementException();
return keys[lastIndex];
}
@Override
public KEY_TYPE POLL_LAST_KEY() { throw new UnsupportedOperationException(); }
@Override
public boolean remove(Object o) { throw new UnsupportedOperationException(); }
#if !TYPE_OBJECT
@Override
public boolean contains(KEY_TYPE o) {
if(KEY_EQUALS_NULL(o)) return containsNull;
int pos = HashUtil.mix(KEY_TO_HASH(o)) & mask;
KEY_TYPE current = keys[pos];
if(KEY_EQUALS_NULL(current)) return false;
if(KEY_EQUALS(current, o)) return true;
while(true) {
if(KEY_EQUALS_NULL((current = keys[pos = (++pos & mask)]))) return false;
else if(KEY_EQUALS(current, o)) return true;
}
}
@Override
public boolean remove(KEY_TYPE o) { throw new UnsupportedOperationException(); }
#endif
@Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
int index = firstIndex;
while(index != -1) {
action.accept(keys[index]);
index = (int)links[index];
}
}
@Override
public void forEachIndexed(BI_FROM_INT_CONSUMER KEY_GENERIC_TYPE action) {
Objects.requireNonNull(action);
int count = 0;
int index = firstIndex;
while(index != -1) {
action.accept(count++, keys[index]);
index = (int)links[index];
}
}
@Override
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
int index = firstIndex;
while(index != -1) {
action.accept(input, keys[index]);
index = (int)links[index];
}
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int index = firstIndex;
while(index != -1) {
if(filter.test(keys[index])) return true;
index = (int)links[index];
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int index = firstIndex;
while(index != -1) {
if(filter.test(keys[index])) return false;
index = (int)links[index];
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int index = firstIndex;
while(index != -1) {
if(!filter.test(keys[index])) return false;
index = (int)links[index];
}
return true;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
int index = firstIndex;
while(index != -1) {
state = operator.APPLY_VALUE(state, keys[index]);
index = (int)links[index];
}
return state;
}
#else
@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);
KEY_SPECIAL_TYPE state = identity;
int index = firstIndex;
while(index != -1) {
state = operator.APPLY_VALUE(state, keys[index]);
index = (int)links[index];
}
return state;
}
#endif
@Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_VALUE;
boolean empty = true;
int index = firstIndex;
while(index != -1) {
if(empty) {
state = keys[index];
empty = false;
}
else state = operator.APPLY_VALUE(state, keys[index]);
index = (int)links[index];
}
return state;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int index = firstIndex;
while(index != -1) {
if(filter.test(keys[index])) return keys[index];
index = (int)links[index];
}
return EMPTY_VALUE;
}
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int result = 0;
int index = firstIndex;
while(index != -1) {
if(filter.test(keys[index])) result++;
index = (int)links[index];
}
return result;
}
@Override
public LIST_ITERATOR KEY_GENERIC_TYPE iterator() {
return new SetIterator();
}
@Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) {
return new SetIterator(fromElement);
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) {
if(a == null || a.length < size()) a = new KEY_TYPE[size()];
for(int i = 0, index = firstIndex;index != -1;i++,index = (int)links[index]) {
a[i] = keys[index];
}
if (a.length > size) a[size] = EMPTY_KEY_VALUE;
return a;
}
#endif
@Override
@Deprecated
public Object[] toArray() {
if(isEmpty()) return ObjectArrays.EMPTY_ARRAY;
Object[] obj = new Object[size()];
for(int i = 0, index = firstIndex;index != -1;i++,index = (int)links[index]) {
obj[i] = KEY_TO_OBJ(keys[index]);
}
return obj;
}
@Override
@Primitive
public <E> E[] toArray(E[] a) {
if(a == null) a = (E[])new Object[size()];
else if(a.length < size()) a = (E[])ObjectArrays.newArray(a.getClass().getComponentType(), size());
for(int i = 0, index = firstIndex;index != -1;i++,index = (int)links[index]) {
a[i] = (E)KEY_TO_OBJ(keys[index]);
}
if (a.length > size) a[size] = null;
return a;
}
@Override
public IMMUTABLE_HASH_SET KEY_GENERIC_TYPE copy() {
IMMUTABLE_HASH_SET KEY_GENERIC_TYPE set = new IMMUTABLE_HASH_SETBRACES();
set.containsNull = containsNull;
set.firstIndex = firstIndex;
set.lastIndex = lastIndex;
set.size = size;
set.mask = mask;
set.nullIndex = nullIndex;
set.keys = Arrays.copyOf(keys, keys.length);
set.links = Arrays.copyOf(links, links.length);
return set;
}
@Override
public void clear() { throw new UnsupportedOperationException(); }
@Override
public int size() {
return size;
}
private class SetIterator implements LIST_ITERATOR KEY_GENERIC_TYPE {
int previous = -1;
int next = -1;
int current = -1;
int index = 0;
SetIterator() {
next = firstIndex;
}
SetIterator(KEY_TYPE from) {
if(KEY_EQUALS_NULL(from)) {
if(containsNull) {
next = (int) links[nullIndex];
previous = nullIndex;
}
else throw new NoSuchElementException("The null element is not in the set");
}
else if(KEY_EQUALS(keys[lastIndex], from)) {
previous = lastIndex;
index = size;
}
else {
int pos = HashUtil.mix(KEY_TO_HASH(from)) & mask;
while(KEY_EQUALS_NOT_NULL(keys[pos])) {
if(KEY_EQUALS(keys[pos], from)) {
next = (int)links[pos];
previous = pos;
break;
}
pos = ++pos & mask;
}
if(previous == -1 && next == -1)
throw new NoSuchElementException("The element was not found");
}
}
@Override
public int skip(int amount) {
int result = 0;
while(next != -1 && result != amount) {
current = previous = next;
next = (int)(links[current]);
result++;
}
if(index >= 0) index+=result;
return result;
}
@Override
public int back(int amount) {
int result = 0;
while(previous != -1 && result != amount) {
current = next = previous;
previous = (int)(links[current] >> 32);
result++;
}
if(index >= 0) index-=result;
return result;
}
@Override
public boolean hasNext() {
return next != -1;
}
@Override
public boolean hasPrevious() {
return previous != -1;
}
@Override
public int nextIndex() {
ensureIndexKnown();
return index;
}
@Override
public int previousIndex() {
ensureIndexKnown();
return index - 1;
}
@Override
public void remove() { throw new UnsupportedOperationException(); }
@Override
public KEY_TYPE PREVIOUS() {
if(!hasPrevious()) throw new NoSuchElementException();
current = next = previous;
previous = (int)(links[current] >> 32);
if(index >= 0) index--;
return keys[current];
}
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
current = previous = next;
next = (int)(links[current]);
if(index >= 0) index++;
return keys[current];
}
private void ensureIndexKnown() {
if(index == -1) {
if(previous == -1) {
index = 0;
}
else if(next == -1) {
index = size;
}
else {
index = 1;
for(int pos = firstIndex;pos != previous;pos = (int)links[pos], index++);
}
}
}
#if TYPE_OBJECT
@Override
public void set(Object e) { throw new UnsupportedOperationException(); }
@Override
public void add(Object e) { throw new UnsupportedOperationException(); }
#else
@Override
public void set(KEY_TYPE e) { throw new UnsupportedOperationException(); }
@Override
public void add(KEY_TYPE e) { throw new UnsupportedOperationException(); }
#endif
}
}
@@ -3,8 +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; import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
#endif
#if SETS_FEATURE
import speiger.src.collections.PACKAGE.utils.SETS;
#endif
/** /**
* A Type Specific Navigable Set interface with a couple helper methods * A Type Specific Navigable Set interface with a couple helper methods
@@ -115,7 +120,34 @@ public interface NAVIGABLE_SET KEY_GENERIC_TYPE extends NavigableSet<CLASS_TYPE>
/** @return a Type Specific desendingSet */ /** @return a Type Specific desendingSet */
@Override @Override
public NAVIGABLE_SET KEY_GENERIC_TYPE descendingSet(); public NAVIGABLE_SET KEY_GENERIC_TYPE descendingSet();
@Override
public NAVIGABLE_SET KEY_GENERIC_TYPE copy();
#if SETS_FEATURE
/**
* Creates a Wrapped NavigableSet that is Synchronized
* @return a new NavigableSet that is synchronized
* @see SETS#synchronize
*/
public default NAVIGABLE_SET KEY_GENERIC_TYPE synchronize() { return SETS.synchronize(this); }
/**
* Creates a Wrapped NavigableSet that is Synchronized
* @param mutex is the controller of the synchronization block
* @return a new NavigableSet Wrapper that is synchronized
* @see SETS#synchronize
*/
public default NAVIGABLE_SET KEY_GENERIC_TYPE synchronize(Object mutex) { return SETS.synchronize(this, mutex); }
/**
* Creates a Wrapped NavigableSet that is unmodifiable
* @return a new NavigableSet Wrapper that is unmodifiable
* @see SETS#unmodifiable
*/
public default NAVIGABLE_SET KEY_GENERIC_TYPE unmodifiable() { return SETS.unmodifiable(this); }
#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
@@ -123,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
@@ -144,10 +177,10 @@ public interface NAVIGABLE_SET KEY_GENERIC_TYPE extends NavigableSet<CLASS_TYPE>
default CLASS_TYPE last() { return SORTED_SET.super.last(); } default CLASS_TYPE last() { return SORTED_SET.super.last(); }
@Override @Override
@Deprecated @Deprecated
public default CLASS_TYPE pollFirst() { return KEY_TO_OBJ(POLL_FIRST_KEY()); } public default CLASS_TYPE pollFirst() { return isEmpty() ? null : KEY_TO_OBJ(POLL_FIRST_KEY()); }
@Override @Override
@Deprecated @Deprecated
public default CLASS_TYPE pollLast() { return KEY_TO_OBJ(POLL_LAST_KEY()); } public default CLASS_TYPE pollLast() { return isEmpty() ? null : KEY_TO_OBJ(POLL_LAST_KEY()); }
@Override @Override
@Deprecated @Deprecated
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,120 @@
package speiger.src.collections.PACKAGE.sets;
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.utils.SPLIT_ITERATORS;
#endif
#if SETS_FEATURE
import speiger.src.collections.PACKAGE.utils.SETS;
#endif
/**
* A Special Set Interface giving Access to some really usefull functions
* The Idea behind this interface is to allow access to functions that give control to the Order of elements.
* Since Linked implementations as examples can be reordered outside of the Insertion Order.
* This interface provides basic access to such functions while also providing some Sorted/NaivgableSet implementations that still fit into here.
*
* @Type(T)
*/
public interface ORDERED_SET KEY_GENERIC_TYPE extends SET KEY_GENERIC_TYPE
{
/**
* A customized add method that allows you to insert into the first index.
* @param o the element that should be inserted
* @return true if it was added
* @see java.util.Set#add(Object)
*/
public boolean addAndMoveToFirst(KEY_TYPE o);
/**
* A customized add method that allows you to insert into the last index.
* @param o the element that should be inserted
* @return true if it was added
* @see java.util.Set#add(Object)
*/
public boolean addAndMoveToLast(KEY_TYPE o);
/**
* A specific move method to move a given key to the first index.
* @param o that should be moved to the first index
* @return true if the value was moved.
* @note returns false if the value was not present in the first place
*/
public boolean moveToFirst(KEY_TYPE o);
/**
* A specific move method to move a given key to the last index.
* @param o that should be moved to the first last
* @return true if the value was moved.
* @note returns false if the value was not present in the first place
*/
public boolean moveToLast(KEY_TYPE o);
@Override
public ORDERED_SET KEY_GENERIC_TYPE copy();
@Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator();
/**
* A type Specific Iterator starting from a given key
* @param fromElement the element the iterator should start from
* @return a iterator starting from the given element
* @throws java.util.NoSuchElementException if fromElement isn't found
*/
public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement);
#if SPLIT_ITERATOR_FEATURE
/**
* A Type Specific Type Splititerator to reduce boxing/unboxing
* @return type specific splititerator
*/
@Override
default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createSplititerator(this, 0); }
#endif
/**
* A method to get the first element in the set
* @return first element in the set
*/
public KEY_TYPE FIRST_KEY();
/**
* A method to get and remove the first element in the set
* @return first element in the set
*/
public KEY_TYPE POLL_FIRST_KEY();
/**
* A method to get the last element in the set
* @return last element in the set
*/
public KEY_TYPE LAST_KEY();
/**
* A method to get and remove the last element in the set
* @return last element in the set
*/
public KEY_TYPE POLL_LAST_KEY();
#if SETS_FEATURE
/**
* Creates a Wrapped OrderedSet that is Synchronized
* @return a new OrderedSet that is synchronized
* @see SETS#synchronize
*/
public default ORDERED_SET KEY_GENERIC_TYPE synchronize() { return SETS.synchronize(this); }
/**
* Creates a Wrapped OrderedSet that is Synchronized
* @param mutex is the controller of the synchronization block
* @return a new OrderedSet Wrapper that is synchronized
* @see SETS#synchronize
*/
public default ORDERED_SET KEY_GENERIC_TYPE synchronize(Object mutex) { return SETS.synchronize(this, mutex); }
/**
* Creates a Wrapped OrderedSet that is unmodifiable
* @return a new OrderedSet Wrapper that is unmodifiable
* @see SETS#unmodifiable
*/
public default ORDERED_SET KEY_GENERIC_TYPE unmodifiable() { return SETS.unmodifiable(this); }
#endif
}
File diff suppressed because it is too large Load Diff
@@ -4,18 +4,27 @@ 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; import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
#endif
#if SETS_FEATURE
import speiger.src.collections.PACKAGE.utils.SETS;
#endif
/** /**
* A Type Specific Set class to reduce boxing/unboxing * A Type Specific Set class to reduce boxing/unboxing
* @Type(T) * @Type(T)
*/ */
public interface SET KEY_GENERIC_TYPE extends Set<CLASS_TYPE>, COLLECTION KEY_GENERIC_TYPE public interface SET KEY_GENERIC_TYPE extends Set<CLASS_TYPE>, COLLECTION KEY_GENERIC_TYPE
{ {
@Override @Override
public ITERATOR KEY_GENERIC_TYPE iterator(); public ITERATOR KEY_GENERIC_TYPE iterator();
@Override
public SET KEY_GENERIC_TYPE copy();
#if !TYPE_OBJECT #if !TYPE_OBJECT
/** /**
* A Type Specific remove function to reduce boxing/unboxing * A Type Specific remove function to reduce boxing/unboxing
@@ -46,11 +55,47 @@ public interface SET KEY_GENERIC_TYPE extends Set<CLASS_TYPE>, COLLECTION KEY_GE
public default boolean remove(Object o) { public default boolean remove(Object o) {
return COLLECTION.super.remove(o); return COLLECTION.super.remove(o);
} }
#else
/**
* A Helper method that allows to add a element or getting the already present implement.
* Allowing to make unique references reuseable.
* @param o the element to add
* @return either the inserted element or the present element.
*/
public KEY_TYPE addOrGet(KEY_TYPE o);
#endif #endif
#if SETS_FEATURE
/**
* Creates a Wrapped Set that is Synchronized
* @return a new Set that is synchronized
* @see SETS#synchronize
*/
public default SET KEY_GENERIC_TYPE synchronize() { return SETS.synchronize(this); }
/**
* Creates a Wrapped Set that is Synchronized
* @param mutex is the controller of the synchronization block
* @return a new Set Wrapper that is synchronized
* @see SETS#synchronize
*/
public default SET KEY_GENERIC_TYPE synchronize(Object mutex) { return SETS.synchronize(this, mutex); }
/**
* Creates a Wrapped Set that is unmodifiable
* @return a new Set Wrapper that is unmodifiable
* @see SETS#unmodifiable
*/
public default SET KEY_GENERIC_TYPE unmodifiable() { return SETS.unmodifiable(this); }
#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,56 +3,30 @@ 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
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
#endif #endif
#if SETS_FEATURE
import speiger.src.collections.PACKAGE.utils.SETS;
#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
* with a couple extra methods that allow greater control over sets. * with a couple extra methods that allow greater control over sets.
* @Type(T) * @Type(T)
* @note ORDERED_SET is only extended until 0.6.0 for Compat reasons.
* The supported classes already implement ORDERED_SET directly and will remove SORTED_SET implementations in favor of ORDERED_SET instead
*/ */
public interface SORTED_SET KEY_GENERIC_TYPE extends SET KEY_GENERIC_TYPE, SortedSet<CLASS_TYPE> public interface SORTED_SET KEY_GENERIC_TYPE extends SET KEY_GENERIC_TYPE, SortedSet<CLASS_TYPE>
{ {
/**
* A customized add method that allows you to insert into the first index.
* @param o the element that should be inserted
* @return true if it was added
* @see java.util.Set#add(Object)
* @note some implementations do not support this method
*/
public boolean addAndMoveToFirst(KEY_TYPE o);
/**
* A customized add method that allows you to insert into the last index.
* @param o the element that should be inserted
* @return true if it was added
* @see java.util.Set#add(Object)
* @note some implementations do not support this method
*/
public boolean addAndMoveToLast(KEY_TYPE o);
/**
* A specific move method to move a given key to the first index.
* @param o that should be moved to the first index
* @return true if the value was moved.
* @note returns false if the value was not present in the first place
* @note some implementations do not support this method
*/
public boolean moveToFirst(KEY_TYPE o);
/**
* A specific move method to move a given key to the last index.
* @param o that should be moved to the first last
* @return true if the value was moved.
* @note returns false if the value was not present in the first place
* @note some implementations do not support this method
*/
public boolean moveToLast(KEY_TYPE o);
/** /**
* A Type Specific Comparator method * A Type Specific Comparator method
* @return the type specific comparator * @return the type specific comparator
@@ -60,6 +34,9 @@ public interface SORTED_SET KEY_GENERIC_TYPE extends SET KEY_GENERIC_TYPE, Sorte
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator(); public COMPARATOR KEY_GENERIC_TYPE comparator();
@Override
public SORTED_SET KEY_GENERIC_TYPE copy();
@Override @Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator(); public BI_ITERATOR KEY_GENERIC_TYPE iterator();
/** /**
@@ -70,6 +47,31 @@ public interface SORTED_SET KEY_GENERIC_TYPE extends SET KEY_GENERIC_TYPE, Sorte
*/ */
public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement); public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement);
#if SETS_FEATURE
/**
* Creates a Wrapped SortedSet that is Synchronized
* @return a new SortedSet that is synchronized
* @see SETS#synchronize
*/
public default SORTED_SET KEY_GENERIC_TYPE synchronize() { return SETS.synchronize(this); }
/**
* Creates a Wrapped SortedSet that is Synchronized
* @param mutex is the controller of the synchronization block
* @return a new SortedSet Wrapper that is synchronized
* @see SETS#synchronize
*/
public default SORTED_SET KEY_GENERIC_TYPE synchronize(Object mutex) { return SETS.synchronize(this, mutex); }
/**
* Creates a Wrapped SortedSet that is unmodifiable
* @return a new SortedSet Wrapper that is unmodifiable
* @see SETS#unmodifiable
*/
public default SORTED_SET KEY_GENERIC_TYPE unmodifiable() { return SETS.unmodifiable(this); }
#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
@@ -77,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

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