Initial commit of split off of Utilities project

master
Robinson 2022-03-19 17:07:21 +01:00
commit a4c33b53d5
No known key found for this signature in database
GPG Key ID: 8E7DB78588BD6F5C
57 changed files with 19862 additions and 0 deletions

121
.gitignore vendored Normal file
View File

@ -0,0 +1,121 @@
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff:
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/dictionaries
.idea/**/codeStyles/
.idea/**/codeStyleSettings.xml
# Sensitive or high-churn files:
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.xml
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/shelf/
# Gradle:
.idea/**/gradle.xml
.idea/**/libraries
# CMake
cmake-build-debug/
# Mongo Explorer plugin:
.idea/**/mongoSettings.xml
## File-based project format:
*.iws
## Plugin-specific files:
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
######################
# End JetBrains IDEs #
######################
# From https://github.com/github/gitignore/blob/master/Gradle.gitignore
.gradle
/build/
# Ignore Gradle GUI config
gradle-app.setting
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar
!gradle-wrapper.properties
# Cache of project
.gradletasknamecache
# From https://github.com/github/gitignore/blob/master/Java.gitignore
*.class
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
*.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
##########################################################
# Specific to this module
# iml files are generated by intellij/gradle now
**/*.iml

29
LICENSE Normal file
View File

@ -0,0 +1,29 @@
- OS - Information about the system, Java runtime, OS, Window Manager, and Desktop Environment.
[The Apache Software License, Version 2.0]
https://git.dorkbox.com/dorkbox/OS
Copyright 2022
Dorkbox LLC
Extra license information
- Kotlin -
[The Apache Software License, Version 2.0]
https://github.com/JetBrains/kotlin
Copyright 2020
JetBrains s.r.o. and Kotlin Programming Language contributors
Kotlin Compiler, Test Data+Libraries, and Tools repository contain third-party code, to which different licenses may apply
See: https://github.com/JetBrains/kotlin/blob/master/license/README.md
- Updates - Software Update Management
[The Apache Software License, Version 2.0]
https://git.dorkbox.com/dorkbox/Updates
Copyright 2021
Dorkbox LLC
Extra license information
- Kotlin -
[The Apache Software License, Version 2.0]
https://github.com/JetBrains/kotlin
Copyright 2020
JetBrains s.r.o. and Kotlin Programming Language contributors
Kotlin Compiler, Test Data+Libraries, and Tools repository contain third-party code, to which different licenses may apply
See: https://github.com/JetBrains/kotlin/blob/master/license/README.md

218
LICENSE.Apachev2 Normal file
View File

@ -0,0 +1,218 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"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.
"You" (or "Your") shall mean an individual or Legal Entity
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.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"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).
"Derivative Works" shall mean any work, whether in Source or Object
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."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
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.
3. Grant of Patent 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
(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:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(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.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as 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 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, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
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 [yyyy] [name of copyright owner]
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.

39
README.md Executable file
View File

@ -0,0 +1,39 @@
Niche collections to augment what is already available.
###### [![Dorkbox](https://badge.dorkbox.com/dorkbox.svg "Dorkbox")](https://git.dorkbox.com/dorkbox/Collections) [![Github](https://badge.dorkbox.com/github.svg "Github")](https://github.com/dorkbox/Collections) [![Gitlab](https://badge.dorkbox.com/gitlab.svg "Gitlab")](https://gitlab.com/dorkbox/Collections)
* LockFree, performant collections/maps/sets/bi-maps
* Thread-safe concurrent iterators
* AhoCorasick finite state machine
* Performant, Primative Maps (int/long/float)
* TimSort
Maven Info
---------
```
<dependencies>
...
<dependency>
<groupId>com.dorkbox</groupId>
<artifactId>Collections</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
```
Gradle Info
---------
```
dependencies {
...
implementation("com.dorkbox:Collections:1.0")
}
```
License
---------
This project is © 2022 dorkbox llc, and is distributed under the terms of the Apache v2.0 License. See file "LICENSE" for further
references.

168
build.gradle.kts Normal file
View File

@ -0,0 +1,168 @@
/*
* Copyright 2020 dorkbox, llc
*
* 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.
*/
import java.time.Instant
///////////////////////////////
////// PUBLISH TO SONATYPE / MAVEN CENTRAL
////// TESTING : (to local maven repo) <'publish and release' - 'publishToMavenLocal'>
////// RELEASE : (to sonatype/maven central), <'publish and release' - 'publishToSonatypeAndRelease'>
///////////////////////////////
gradle.startParameter.showStacktrace = ShowStacktrace.ALWAYS // always show the stacktrace!
plugins {
id("com.dorkbox.GradleUtils") version "2.16"
id("com.dorkbox.Licensing") version "2.12"
id("com.dorkbox.VersionUpdate") version "2.4"
id("com.dorkbox.GradlePublish") version "1.12"
kotlin("jvm") version "1.6.10"
}
object Extras {
// set for the project
const val description = "Information about the system, Java runtime, OS, Window Manager, and Desktop Environment."
const val group = "com.dorkbox"
const val version = "1.0"
// set as project.ext
const val name = "Collections"
const val id = "Collections" // this is the maven ID!
const val vendor = "Dorkbox LLC"
const val vendorUrl = "https://dorkbox.com"
const val url = "https://git.dorkbox.com/dorkbox/Collections"
val buildDate = Instant.now().toString()
}
///////////////////////////////
///// assign 'Extras'
///////////////////////////////
GradleUtils.load("$projectDir/../../gradle.properties", Extras)
GradleUtils.defaults()
GradleUtils.compileConfiguration(JavaVersion.VERSION_1_8)
GradleUtils.jpms(JavaVersion.VERSION_1_9)
licensing {
license(License.APACHE_2) {
description(Extras.description)
author(Extras.vendor)
url(Extras.url)
extra("AhoCorasickDoubleArrayTrie", License.APACHE_2) {
description(Extras.description)
copyright(2018)
author("hankcs <me@hankcs.com>")
url("https://github.com/hankcs/AhoCorasickDoubleArrayTrie")
}
extra("Bias, BinarySearch", License.MIT) {
url(Extras.url)
url("https://github.com/timboudreau/util")
copyright(2013)
author("Tim Boudreau")
}
extra("ConcurrentEntry", License.APACHE_2) {
url(Extras.url)
copyright(2016)
author("bennidi")
author("dorkbox")
}
extra("Collection Utilities (Array, ArrayMap, BooleanArray, ByteArray, CharArray, FloatArray, IdentityMap, IntArray, IntFloatMap, IntIntMap, IntMap, IntSet, LongArray, LongMap, ObjectFloatMap, ObjectIntMap, ObjectMap, ObjectSet, OrderedMap, OrderedSet)", License.APACHE_2) {
url(Extras.url)
url("https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/utils")
copyright(2011)
author("LibGDX")
author("Mario Zechner (badlogicgames@gmail.com)")
author("Nathan Sweet (nathan.sweet@gmail.com)")
}
extra("Predicate", License.APACHE_2) {
url(Extras.url)
url("https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/utils")
copyright(2011)
author("LibGDX")
author("Mario Zechner (badlogicgames@gmail.com)")
author("Nathan Sweet (nathan.sweet@gmail.com)")
author("xoppa")
}
extra("Select, QuickSelect", License.APACHE_2) {
url(Extras.url)
url("https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/utils")
copyright(2011)
author("LibGDX")
author("Mario Zechner (badlogicgames@gmail.com)")
author("Nathan Sweet (nathan.sweet@gmail.com)")
author("Jon Renner")
}
extra("TimSort, ComparableTimSort", License.APACHE_2) {
url(Extras.url)
url("https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/utils")
copyright(2008)
author("The Android Open Source Project")
}
extra("ConcurrentWeakIdentityHashMap", License.APACHE_2) {
copyright(2016)
description("Concurrent WeakIdentity HashMap")
author("zhanhb")
url("https://github.com/spring-projects/spring-loaded/blob/master/springloaded/src/main/java/org/springsource/loaded/support/ConcurrentWeakIdentityHashMap.java")
}
}
}
tasks.jar.get().apply {
manifest {
// https://docs.oracle.com/javase/tutorial/deployment/jar/packageman.html
attributes["Name"] = Extras.name
attributes["Specification-Title"] = Extras.name
attributes["Specification-Version"] = Extras.version
attributes["Specification-Vendor"] = Extras.vendor
attributes["Implementation-Title"] = "${Extras.group}.${Extras.id}"
attributes["Implementation-Version"] = Extras.buildDate
attributes["Implementation-Vendor"] = Extras.vendor
}
}
dependencies {
api("com.dorkbox:Updates:1.1")
}
publishToSonatype {
groupId = Extras.group
artifactId = Extras.id
version = Extras.version
name = Extras.name
description = Extras.description
url = Extras.url
vendor = Extras.vendor
vendorUrl = Extras.vendorUrl
issueManagement {
url = "${Extras.url}/issues"
nickname = "Gitea Issues"
}
developer {
id = "dorkbox"
name = Extras.vendor
email = "email@dorkbox.com"
}
}

15
gradle.properties Normal file
View File

@ -0,0 +1,15 @@
# https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties
org.gradle.jvmargs=-Dfile.encoding=UTF-8
#org.gradle.warning.mode=(all,fail,none,summary)
org.gradle.warning.mode=all
#org.gradle.daemon=false
# default is 3 hours, this is 1 minute
org.gradle.daemon.idletimeout=60000
#org.gradle.console=(auto,plain,rich,verbose)
org.gradle.console=auto
#org.gradle.logging.level=(quiet,warn,lifecycle,info,debug)
org.gradle.logging.level=lifecycle

15
settings.gradle.kts Normal file
View File

@ -0,0 +1,15 @@
/*
* Copyright 2018 dorkbox, llc
*
* 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.
*/

View File

@ -0,0 +1,662 @@
/*******************************************************************************
* Copyright 2011 LibGDX.
* Mario Zechner <badlogicgames@gmail.com>
* Nathan Sweet <nathan.sweet@gmail.com>
*
* 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.
******************************************************************************/
package dorkbox.collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
/** A resizable, ordered or unordered array of objects. If unordered, this class avoids a memory copy when removing elements (the
* last element is moved to the removed element's position).
* @author Nathan Sweet */
@SuppressWarnings({"unchecked", "rawtypes", "SuspiciousSystemArraycopy", "unused", "NullableProblems", "DuplicatedCode"})
public class Array<T> implements Iterable<T> {
/** Provides direct access to the underlying array. If the Array's generic type is not Object, this field may only be accessed
* if the {@link Array#Array(boolean, int, Class)} constructor was used. */
public T[] items;
public int size;
public boolean ordered;
private ArrayIterable iterable;
private Predicate.PredicateIterable<T> predicateIterable;
/** Creates an ordered array with a capacity of 16. */
public Array () {
this(true, 16);
}
/** Creates an ordered array with the specified capacity. */
public Array (int capacity) {
this(true, capacity);
}
/** @param ordered If false, methods that remove elements may change the order of other elements in the array, which avoids a
* memory copy.
* @param capacity Any elements added beyond this will cause the backing array to be grown. */
public Array (boolean ordered, int capacity) {
this.ordered = ordered;
items = (T[])new Object[capacity];
}
/** Creates a new array with {@link #items} of the specified type.
* @param ordered If false, methods that remove elements may change the order of other elements in the array, which avoids a
* memory copy.
* @param capacity Any elements added beyond this will cause the backing array to be grown. */
public Array (boolean ordered, int capacity, Class arrayType) {
this.ordered = ordered;
items = (T[])java.lang.reflect.Array.newInstance(arrayType, capacity);
}
/** Creates an ordered array with {@link #items} of the specified type and a capacity of 16. */
public Array (Class arrayType) {
this(true, 16, arrayType);
}
/** Creates a new array containing the elements in the specified array. The new array will have the same type of backing array
* and will be ordered if the specified array is ordered. The capacity is set to the number of elements, so any subsequent
* elements added will cause the backing array to be grown. */
public Array (Array<? extends T> array) {
this(array.ordered, array.size, array.items.getClass().getComponentType());
size = array.size;
System.arraycopy(array.items, 0, items, 0, size);
}
/** Creates a new ordered array containing the elements in the specified array. The new array will have the same type of
* backing array. The capacity is set to the number of elements, so any subsequent elements added will cause the backing array
* to be grown. */
public Array (T[] array) {
this(true, array, 0, array.length);
}
/** Creates a new array containing the elements in the specified array. The new array will have the same type of backing array.
* The capacity is set to the number of elements, so any subsequent elements added will cause the backing array to be grown.
* @param ordered If false, methods that remove elements may change the order of other elements in the array, which avoids a
* memory copy. */
public Array (boolean ordered, T[] array, int start, int count) {
this(ordered, count, (Class)array.getClass().getComponentType());
size = count;
System.arraycopy(array, start, items, 0, size);
}
public void add (T value) {
T[] items = this.items;
if (size == items.length) items = resize(Math.max(8, (int)(size * 1.75f)));
items[size++] = value;
}
public void add (T value1, T value2) {
T[] items = this.items;
if (size + 1 >= items.length) items = resize(Math.max(8, (int)(size * 1.75f)));
items[size] = value1;
items[size + 1] = value2;
size += 2;
}
public void add (T value1, T value2, T value3) {
T[] items = this.items;
if (size + 2 >= items.length) items = resize(Math.max(8, (int)(size * 1.75f)));
items[size] = value1;
items[size + 1] = value2;
items[size + 2] = value3;
size += 3;
}
public void add (T value1, T value2, T value3, T value4) {
T[] items = this.items;
if (size + 3 >= items.length) items = resize(Math.max(8, (int)(size * 1.8f))); // 1.75 isn't enough when size=5.
items[size] = value1;
items[size + 1] = value2;
items[size + 2] = value3;
items[size + 3] = value4;
size += 4;
}
public void addAll (Array<? extends T> array) {
addAll(array.items, 0, array.size);
}
public void addAll (Array<? extends T> array, int start, int count) {
if (start + count > array.size)
throw new IllegalArgumentException("start + count must be <= size: " + start + " + " + count + " <= " + array.size);
addAll((T[])array.items, start, count);
}
public void addAll (T... array) {
addAll(array, 0, array.length);
}
public void addAll (T[] array, int start, int count) {
T[] items = this.items;
int sizeNeeded = size + count;
if (sizeNeeded > items.length) items = resize(Math.max(8, (int)(sizeNeeded * 1.75f)));
System.arraycopy(array, start, items, size, count);
size += count;
}
public T get (int index) {
if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size);
return items[index];
}
public void set (int index, T value) {
if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size);
items[index] = value;
}
public void insert (int index, T value) {
if (index > size) throw new IndexOutOfBoundsException("index can't be > size: " + index + " > " + size);
T[] items = this.items;
if (size == items.length) items = resize(Math.max(8, (int)(size * 1.75f)));
if (ordered)
System.arraycopy(items, index, items, index + 1, size - index);
else
items[size] = items[index];
size++;
items[index] = value;
}
public void swap (int first, int second) {
if (first >= size) throw new IndexOutOfBoundsException("first can't be >= size: " + first + " >= " + size);
if (second >= size) throw new IndexOutOfBoundsException("second can't be >= size: " + second + " >= " + size);
T[] items = this.items;
T firstValue = items[first];
items[first] = items[second];
items[second] = firstValue;
}
/** Returns if this array contains value.
* @param value May be null.
* @param identity If true, == comparison will be used. If false, .equals() comparison will be used.
* @return true if array contains value, false if it doesn't */
public boolean contains (T value, boolean identity) {
T[] items = this.items;
int i = size - 1;
if (identity || value == null) {
while (i >= 0)
if (items[i--] == value) return true;
} else {
while (i >= 0)
if (value.equals(items[i--])) return true;
}
return false;
}
/** Returns the index of first occurrence of value in the array, or -1 if no such value exists.
* @param value May be null.
* @param identity If true, == comparison will be used. If false, .equals() comparison will be used.
* @return An index of first occurrence of value in array or -1 if no such value exists */
public int indexOf (T value, boolean identity) {
T[] items = this.items;
if (identity || value == null) {
for (int i = 0, n = size; i < n; i++)
if (items[i] == value) return i;
} else {
for (int i = 0, n = size; i < n; i++)
if (value.equals(items[i])) return i;
}
return -1;
}
/** Returns an index of last occurrence of value in array or -1 if no such value exists. Search is started from the end of an
* array.
* @param value May be null.
* @param identity If true, == comparison will be used. If false, .equals() comparison will be used.
* @return An index of last occurrence of value in array or -1 if no such value exists */
public int lastIndexOf (T value, boolean identity) {
T[] items = this.items;
if (identity || value == null) {
for (int i = size - 1; i >= 0; i--)
if (items[i] == value) return i;
} else {
for (int i = size - 1; i >= 0; i--)
if (value.equals(items[i])) return i;
}
return -1;
}
/** Removes the first instance of the specified value in the array.
* @param value May be null.
* @param identity If true, == comparison will be used. If false, .equals() comparison will be used.
* @return true if value was found and removed, false otherwise */
public boolean removeValue (T value, boolean identity) {
T[] items = this.items;
if (identity || value == null) {
for (int i = 0, n = size; i < n; i++) {
if (items[i] == value) {
removeIndex(i);
return true;
}
}
} else {
for (int i = 0, n = size; i < n; i++) {
if (value.equals(items[i])) {
removeIndex(i);
return true;
}
}
}
return false;
}
/** Removes and returns the item at the specified index. */
public T removeIndex (int index) {
if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size);
T[] items = this.items;
T value = items[index];
size--;
if (ordered)
System.arraycopy(items, index + 1, items, index, size - index);
else
items[index] = items[size];
items[size] = null;
return value;
}
/** Removes the items between the specified indices, inclusive. */
public void removeRange (int start, int end) {
if (end >= size) throw new IndexOutOfBoundsException("end can't be >= size: " + end + " >= " + size);
if (start > end) throw new IndexOutOfBoundsException("start can't be > end: " + start + " > " + end);
T[] items = this.items;
int count = end - start + 1;
if (ordered)
System.arraycopy(items, start + count, items, start, size - (start + count));
else {
int lastIndex = this.size - 1;
for (int i = 0; i < count; i++)
items[start + i] = items[lastIndex - i];
}
size -= count;
}
/** Removes from this array all of elements contained in the specified array.
* @param identity True to use ==, false to use .equals().
* @return true if this array was modified. */
public boolean removeAll (Array<? extends T> array, boolean identity) {
int size = this.size;
int startSize = size;
T[] items = this.items;
if (identity) {
for (int i = 0, n = array.size; i < n; i++) {
T item = array.get(i);
for (int ii = 0; ii < size; ii++) {
if (item == items[ii]) {
removeIndex(ii);
size--;
break;
}
}
}
} else {
for (int i = 0, n = array.size; i < n; i++) {
T item = array.get(i);
for (int ii = 0; ii < size; ii++) {
if (item.equals(items[ii])) {
removeIndex(ii);
size--;
break;
}
}
}
}
return size != startSize;
}
/** Removes and returns the last item. */
public T pop () {
if (size == 0) throw new IllegalStateException("Array is empty.");
--size;
T item = items[size];
items[size] = null;
return item;
}
/** Returns the last item. */
public T peek () {
if (size == 0) throw new IllegalStateException("Array is empty.");
return items[size - 1];
}
/** Returns the first item. */
public T first () {
if (size == 0) throw new IllegalStateException("Array is empty.");
return items[0];
}
/** Returns true if the array is empty. */
public boolean isEmpty () {
return size == 0;
}
public void clear () {
T[] items = this.items;
for (int i = 0, n = size; i < n; i++)
items[i] = null;
size = 0;
}
/** Reduces the size of the backing array to the size of the actual items. This is useful to release memory when many items
* have been removed, or if it is known that more items will not be added.
* @return {@link #items} */
public T[] shrink () {
if (items.length != size) resize(size);
return items;
}
/** Increases the size of the backing array to accommodate the specified number of additional items. Useful before adding many
* items to avoid multiple backing array resizes.
* @return {@link #items} */
public T[] ensureCapacity (int additionalCapacity) {
if (additionalCapacity < 0) throw new IllegalArgumentException("additionalCapacity must be >= 0: " + additionalCapacity);
int sizeNeeded = size + additionalCapacity;
if (sizeNeeded > items.length) resize(Math.max(8, sizeNeeded));
return items;
}
/** Sets the array size, leaving any values beyond the current size null.
* @return {@link #items} */
public T[] setSize (int newSize) {
truncate(newSize);
if (newSize > items.length) resize(Math.max(8, newSize));
size = newSize;
return items;
}
/** Creates a new backing array with the specified size containing the current items. */
protected T[] resize (int newSize) {
T[] items = this.items;
T[] newItems = (T[])java.lang.reflect.Array.newInstance(items.getClass().getComponentType(), newSize);
System.arraycopy(items, 0, newItems, 0, Math.min(size, newItems.length));
this.items = newItems;
return newItems;
}
/** Sorts this array. The array elements must implement {@link Comparable}. This method is not thread safe (uses
* {@link Sort#instance()}). */
public void sort () {
Sort.instance().sort(items, 0, size);
}
/** Sorts the array. This method is not thread safe (uses {@link Sort#instance()}). */
public void sort (Comparator<? super T> comparator) {
Sort.instance().sort(items, comparator, 0, size);
}
/** Selects the nth-lowest element from the Array according to Comparator ranking. This might partially sort the Array. The
* array must have a size greater than 0, or a {@link RuntimeException} will be thrown.
* @see Select
* @param comparator used for comparison
* @param kthLowest rank of desired object according to comparison, n is based on ordinal numbers, not array indices. for min
* value use 1, for max value use size of array, using 0 results in runtime exception.
* @return the value of the Nth lowest ranked object. */
public T selectRanked (Comparator<T> comparator, int kthLowest) {
if (kthLowest < 1) {
throw new RuntimeException("nth_lowest must be greater than 0, 1 = first, 2 = second...");
}
return Select.instance().select(items, comparator, kthLowest, size);
}
/** @see Array#selectRanked(java.util.Comparator, int)
* @param comparator used for comparison
* @param kthLowest rank of desired object according to comparison, n is based on ordinal numbers, not array indices. for min
* value use 1, for max value use size of array, using 0 results in runtime exception.
* @return the index of the Nth lowest ranked object. */
public int selectRankedIndex (Comparator<T> comparator, int kthLowest) {
if (kthLowest < 1) {
throw new RuntimeException("nth_lowest must be greater than 0, 1 = first, 2 = second...");
}
return Select.instance().selectIndex(items, comparator, kthLowest, size);
}
public void reverse () {
T[] items = this.items;
for (int i = 0, lastIndex = size - 1, n = size / 2; i < n; i++) {
int ii = lastIndex - i;
T temp = items[i];
items[i] = items[ii];
items[ii] = temp;
}
}
public void shuffle () {
T[] items = this.items;
for (int i = size - 1; i >= 0; i--) {
int ii = MathUtil.random(i);
T temp = items[i];
items[i] = items[ii];
items[ii] = temp;
}
}
/** Returns an iterator for the items in the array. Remove is supported. Note that the same iterator instance is returned each
* time this method is called. Use the {@link ArrayIterator} constructor for nested or multithreaded iteration. */
@Override
public Iterator<T> iterator () {
if (iterable == null) iterable = new ArrayIterable(this);
return iterable.iterator();
}
/** Returns an iterable for the selected items in the array. Remove is supported, but not between hasNext() and next(). Note
* that the same iterable instance is returned each time this method is called. Use the {@link Predicate.PredicateIterable}
* constructor for nested or multithreaded iteration. */
public Iterable<T> select (Predicate<T> predicate) {
if (predicateIterable == null)
predicateIterable = new Predicate.PredicateIterable<T>(this, predicate);
else
predicateIterable.set(this, predicate);
return predicateIterable;
}
/** Reduces the size of the array to the specified size. If the array is already smaller than the specified size, no action is
* taken. */
public void truncate (int newSize) {
if (newSize < 0) throw new IllegalArgumentException("newSize must be >= 0: " + newSize);
if (size <= newSize) return;
for (int i = newSize; i < size; i++)
items[i] = null;
size = newSize;
}
/** Returns a random item from the array, or null if the array is empty. */
public T random () {
if (size == 0) return null;
return items[MathUtil.random(0, size - 1)];
}
/** Returns the items as an array. Note the array is typed, so the {@link #Array(Class)} constructor must have been used.
* Otherwise use {@link #toArray(Class)} to specify the array type. */
public T[] toArray () {
return (T[])toArray(items.getClass().getComponentType());
}
public <V> V[] toArray (Class<V> type) {
V[] result = (V[])java.lang.reflect.Array.newInstance(type, size);
System.arraycopy(items, 0, result, 0, size);
return result;
}
@Override
public int hashCode () {
if (!ordered) return super.hashCode();
Object[] items = this.items;
int h = 1;
for (int i = 0, n = size; i < n; i++) {
h *= 31;
Object item = items[i];
if (item != null) h += item.hashCode();
}
return h;
}
@Override
public boolean equals (Object object) {
if (object == this) return true;
if (!ordered) return false;
if (!(object instanceof Array)) return false;
Array array = (Array)object;
if (!array.ordered) return false;
int n = size;
if (n != array.size) return false;
Object[] items1 = this.items;
Object[] items2 = array.items;
for (int i = 0; i < n; i++) {
Object o1 = items1[i];
Object o2 = items2[i];
if (!(o1 == null ? o2 == null : o1.equals(o2))) return false;
}
return true;
}
@Override
public String toString () {
if (size == 0) return "[]";
T[] items = this.items;
StringBuilder buffer = new StringBuilder(32);
buffer.append('[');
buffer.append(items[0]);
for (int i = 1; i < size; i++) {
buffer.append(", ");
buffer.append(items[i]);
}
buffer.append(']');
return buffer.toString();
}
public String toString (String separator) {
if (size == 0) return "";
T[] items = this.items;
StringBuilder buffer = new StringBuilder(32);
buffer.append(items[0]);
for (int i = 1; i < size; i++) {
buffer.append(separator);
buffer.append(items[i]);
}
return buffer.toString();
}
/** @see #Array(Class) */
static public <T> Array<T> of (Class<T> arrayType) {
return new Array(arrayType);
}
/** @see #Array(boolean, int, Class) */
static public <T> Array<T> of (boolean ordered, int capacity, Class<T> arrayType) {
return new Array(ordered, capacity, arrayType);
}
/** @see #Array(Object[]) */
static public <T> Array<T> with (T... array) {
return new Array(array);
}
@SuppressWarnings("NullableProblems")
static public class ArrayIterator<T> implements Iterator<T>, Iterable<T> {
private final Array<T> array;
private final boolean allowRemove;
int index;
boolean valid = true;
// ArrayIterable<T> iterable;
public ArrayIterator (Array<T> array) {
this(array, true);
}
public ArrayIterator (Array<T> array, boolean allowRemove) {
this.array = array;
this.allowRemove = allowRemove;
}
@Override
public boolean hasNext () {
if (!valid) {
// System.out.println(iterable.lastAcquire);
throw new RuntimeException("#iterator() cannot be used nested.");
}
return index < array.size;
}
@Override
public T next () {
if (index >= array.size) throw new NoSuchElementException(String.valueOf(index));
if (!valid) {
// System.out.println(iterable.lastAcquire);
throw new RuntimeException("#iterator() cannot be used nested.");
}
return array.items[index++];
}
@Override
public void remove () {
if (!allowRemove) throw new RuntimeException("Remove not allowed.");
index--;
array.removeIndex(index);
}
public void reset () {
index = 0;
}
@Override
public Iterator<T> iterator () {
return this;
}
}
@SuppressWarnings({"unchecked", "NullableProblems"})
static public class ArrayIterable<T> implements Iterable<T> {
private final Array<T> array;
private final boolean allowRemove;
private ArrayIterator iterator1, iterator2;
// java.io.StringWriter lastAcquire = new java.io.StringWriter();
public ArrayIterable (Array<T> array) {
this(array, true);
}
public ArrayIterable (Array<T> array, boolean allowRemove) {
this.array = array;
this.allowRemove = allowRemove;
}
@Override
public Iterator<T> iterator () {
// lastAcquire.getBuffer().setLength(0);
// new Throwable().printStackTrace(new java.io.PrintWriter(lastAcquire));
if (iterator1 == null) {
iterator1 = new ArrayIterator(array, allowRemove);
iterator2 = new ArrayIterator(array, allowRemove);
// iterator1.iterable = this;
// iterator2.iterable = this;
}
if (!iterator1.valid) {
iterator1.index = 0;
iterator1.valid = true;
iterator2.valid = false;
return iterator1;
}
iterator2.index = 0;
iterator2.valid = true;
iterator1.valid = false;
return iterator2;
}
}
}

View File

@ -0,0 +1,660 @@
/*******************************************************************************
* Copyright 2011 LibGDX.
* Mario Zechner <badlogicgames@gmail.com>
* Nathan Sweet <nathan.sweet@gmail.com>
*
* 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.
******************************************************************************/
package dorkbox.collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import dorkbox.collections.ObjectMap.Entry;
/** An ordered or unordered map of objects. This implementation uses arrays to store the keys and values, which means
* {@link #getKey(Object, boolean) gets} do a comparison for each key in the map. This is slower than a typical hash map
* implementation, but may be acceptable for small maps and has the benefits that keys and values can be accessed by index, which
* makes iteration fast. Like {@link Array}, if ordered is false, this class avoids a memory copy when removing elements (the last
* element is moved to the removed element's position).
* @author Nathan Sweet */
@SuppressWarnings({"unchecked", "rawtypes", "unused", "SuspiciousSystemArraycopy", "NullableProblems"})
public class ArrayMap<K, V> implements Iterable<Entry<K, V>> {
public K[] keys;
public V[] values;
public int size;
public boolean ordered;
private Entries entries1, entries2;
private Values valuesIter1, valuesIter2;
private Keys keysIter1, keysIter2;
/** Creates an ordered map with a capacity of 16. */
public ArrayMap () {
this(true, 16);
}
/** Creates an ordered map with the specified capacity. */
public ArrayMap (int capacity) {
this(true, capacity);
}
/** @param ordered If false, methods that remove elements may change the order of other elements in the arrays, which avoids a
* memory copy.
* @param capacity Any elements added beyond this will cause the backing arrays to be grown. */
public ArrayMap (boolean ordered, int capacity) {
this.ordered = ordered;
keys = (K[])new Object[capacity];
values = (V[])new Object[capacity];
}
/** Creates a new map with {@link #keys} and {@link #values} of the specified type.
* @param ordered If false, methods that remove elements may change the order of other elements in the arrays, which avoids a
* memory copy.
* @param capacity Any elements added beyond this will cause the backing arrays to be grown. */
public ArrayMap (boolean ordered, int capacity, Class keyArrayType, Class valueArrayType) {
this.ordered = ordered;
keys = (K[])java.lang.reflect.Array.newInstance(keyArrayType, capacity);
values = (V[])java.lang.reflect.Array.newInstance(valueArrayType, capacity);
}
/** Creates an ordered map with {@link #keys} and {@link #values} of the specified type and a capacity of 16. */
public ArrayMap (Class keyArrayType, Class valueArrayType) {
this(false, 16, keyArrayType, valueArrayType);
}
/** Creates a new map containing the elements in the specified map. The new map will have the same type of backing arrays and
* will be ordered if the specified map is ordered. The capacity is set to the number of elements, so any subsequent elements
* added will cause the backing arrays to be grown. */
@SuppressWarnings("CopyConstructorMissesField")
public ArrayMap (ArrayMap array) {
this(array.ordered, array.size, array.keys.getClass().getComponentType(), array.values.getClass().getComponentType());
size = array.size;
System.arraycopy(array.keys, 0, keys, 0, size);
System.arraycopy(array.values, 0, values, 0, size);
}
public int put (K key, V value) {
int index = indexOfKey(key);
if (index == -1) {
if (size == keys.length) resize(Math.max(8, (int)(size * 1.75f)));
index = size++;
}
keys[index] = key;
values[index] = value;
return index;
}
public int put (K key, V value, int index) {
int existingIndex = indexOfKey(key);
if (existingIndex != -1)
removeIndex(existingIndex);
else if (size == keys.length) //
resize(Math.max(8, (int)(size * 1.75f)));
System.arraycopy(keys, index, keys, index + 1, size - index);
System.arraycopy(values, index, values, index + 1, size - index);
keys[index] = key;
values[index] = value;
size++;
return index;
}
public void putAll (ArrayMap<? extends K, ? extends V> map) {
putAll(map, 0, map.size);
}
public void putAll (ArrayMap<? extends K, ? extends V> map, int offset, int length) {
if (offset + length > map.size)
throw new IllegalArgumentException("offset + length must be <= size: " + offset + " + " + length + " <= " + map.size);
int sizeNeeded = size + length - offset;
if (sizeNeeded >= keys.length) resize(Math.max(8, (int)(sizeNeeded * 1.75f)));
System.arraycopy(map.keys, offset, keys, size, length);
System.arraycopy(map.values, offset, values, size, length);
size += length;
}
/** Returns the value for the specified key. Note this does a .equals() comparison of each key in reverse order until the
* specified key is found. */
public V get (K key) {
Object[] keys = this.keys;
int i = size - 1;
if (key == null) {
for (; i >= 0; i--)
if (keys[i] == key) return values[i];
} else {
for (; i >= 0; i--)
if (key.equals(keys[i])) return values[i];
}
return null;
}
/** Returns the key for the specified value. Note this does a comparison of each value in reverse order until the specified
* value is found.
* @param identity If true, == comparison will be used. If false, .equals() comparison will be used. */
public K getKey (V value, boolean identity) {
Object[] values = this.values;
int i = size - 1;
if (identity || value == null) {
for (; i >= 0; i--)
if (values[i] == value) return keys[i];
} else {
for (; i >= 0; i--)
if (value.equals(values[i])) return keys[i];
}
return null;
}
public K getKeyAt (int index) {
if (index >= size) throw new IndexOutOfBoundsException(String.valueOf(index));
return keys[index];
}
public V getValueAt (int index) {
if (index >= size) throw new IndexOutOfBoundsException(String.valueOf(index));
return values[index];
}
public K firstKey () {
if (size == 0) throw new IllegalStateException("Map is empty.");
return keys[0];
}
public V firstValue () {
if (size == 0) throw new IllegalStateException("Map is empty.");
return values[0];
}
public void setKey (int index, K key) {
if (index >= size) throw new IndexOutOfBoundsException(String.valueOf(index));
keys[index] = key;
}
public void setValue (int index, V value) {
if (index >= size) throw new IndexOutOfBoundsException(String.valueOf(index));
values[index] = value;
}
public void insert (int index, K key, V value) {
if (index > size) throw new IndexOutOfBoundsException(String.valueOf(index));
if (size == keys.length) resize(Math.max(8, (int)(size * 1.75f)));
if (ordered) {
System.arraycopy(keys, index, keys, index + 1, size - index);
System.arraycopy(values, index, values, index + 1, size - index);
} else {
keys[size] = keys[index];
values[size] = values[index];
}
size++;
keys[index] = key;
values[index] = value;
}
public boolean containsKey (K key) {
K[] keys = this.keys;
int i = size - 1;
if (key == null) {
while (i >= 0)
if (keys[i--] == key) return true;
} else {
while (i >= 0)
if (key.equals(keys[i--])) return true;
}
return false;
}
/** @param identity If true, == comparison will be used. If false, .equals() comparison will be used. */
public boolean containsValue (V value, boolean identity) {
V[] values = this.values;
int i = size - 1;
if (identity || value == null) {
while (i >= 0)
if (values[i--] == value) return true;
} else {
while (i >= 0)
if (value.equals(values[i--])) return true;