diff --git a/.github/workflows/develop.yml b/.github/workflows/develop.yml index 9a61f8f9..65dc3dd1 100644 --- a/.github/workflows/develop.yml +++ b/.github/workflows/develop.yml @@ -8,13 +8,13 @@ on: jobs: build: - runs-on: ubuntu-latest permissions: - contents: read - + contents: write + pull-requests: write steps: - uses: actions/checkout@v4 + - name: Set up JDK 21 uses: actions/setup-java@v4 with: @@ -30,14 +30,28 @@ jobs: - name: Run tests for all modules run: ./gradlew test - dependency-submission: + - name: Generate jacoco reports + run: ./gradlew jacocoTestReport + + - name: Generate aggregated jacoco report + run: ./gradlew test-coverage:testCodeCoverageReport + - name: Add coverage to PR + id: jacoco + uses: madrapps/jacoco-report@v1.7.2 + with: + paths: ${{ github.workspace }}/test-coverage/build/reports/jacoco/testCodeCoverageReport/testCodeCoverageReport.xml + token: ${{ secrets.GITHUB_TOKEN }} + min-coverage-overall: 40 + min-coverage-changed-files: 60 + + dependency-submission: runs-on: ubuntu-latest permissions: contents: write - steps: - uses: actions/checkout@v4 + - name: Set up JDK 21 uses: actions/setup-java@v4 with: diff --git a/build.gradle b/build.gradle index c5069b27..112634ac 100644 --- a/build.gradle +++ b/build.gradle @@ -1,4 +1,4 @@ -rootProject.version = "9.10.0" +rootProject.version = "10.0.alpha" group = 'javasabr.rlib' subprojects { @@ -8,6 +8,8 @@ subprojects { } apply plugin: "java-library" + apply plugin: "jacoco" + apply plugin: "jacoco-report-aggregation" apply plugin: "java-test-fixtures" apply plugin: 'maven-publish' @@ -119,6 +121,15 @@ subprojects { tasks.withType(Test).configureEach { maxParallelForks = Runtime.runtime.availableProcessors() } + + jacocoTestReport { + dependsOn test + reports { + xml.required = false + csv.required = false + html.outputLocation = layout.buildDirectory.dir('jacocoHtml') + } + } } wrapper { diff --git a/rlib-classpath/src/main/java/javasabr/rlib/classpath/impl/ClassPathScannerImpl.java b/rlib-classpath/src/main/java/javasabr/rlib/classpath/impl/ClassPathScannerImpl.java index af6ae860..13fce9f5 100644 --- a/rlib-classpath/src/main/java/javasabr/rlib/classpath/impl/ClassPathScannerImpl.java +++ b/rlib-classpath/src/main/java/javasabr/rlib/classpath/impl/ClassPathScannerImpl.java @@ -18,9 +18,9 @@ import javasabr.rlib.collections.array.Array; import javasabr.rlib.collections.array.ArrayFactory; import javasabr.rlib.collections.array.MutableArray; +import javasabr.rlib.common.util.ArrayUtils; import javasabr.rlib.io.impl.ReuseBytesInputStream; import javasabr.rlib.io.impl.ReuseBytesOutputStream; -import javasabr.rlib.common.util.ArrayUtils; import javasabr.rlib.io.util.IoUtils; import javasabr.rlib.logger.api.Logger; import javasabr.rlib.logger.api.LoggerManager; diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/array/Array.java b/rlib-collections/src/main/java/javasabr/rlib/collections/array/Array.java index 4da6f45b..de066a26 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/array/Array.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/array/Array.java @@ -3,6 +3,7 @@ import java.io.Serializable; import java.util.Collection; import java.util.Iterator; +import java.util.List; import java.util.Optional; import java.util.RandomAccess; import java.util.function.Function; @@ -203,4 +204,6 @@ default Iterator iterator() { ArrayIterationFunctions iterations(); UnsafeArray asUnsafe(); + + List toList(); } diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/array/IntArray.java b/rlib-collections/src/main/java/javasabr/rlib/collections/array/IntArray.java index 7fdbeddf..eac241ab 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/array/IntArray.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/array/IntArray.java @@ -34,6 +34,10 @@ static IntArray of(int... elements) { return new ImmutableIntArray(elements); } + static IntArray copyOf(IntArray intArray) { + return new ImmutableIntArray(intArray.toArray()); + } + int size(); boolean contains(int value); diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/array/LockableArray.java b/rlib-collections/src/main/java/javasabr/rlib/collections/array/LockableArray.java index c1acb41b..e8a89a40 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/array/LockableArray.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/array/LockableArray.java @@ -1,7 +1,7 @@ package javasabr.rlib.collections.array; import javasabr.rlib.collections.operation.LockableSource; -import javasabr.rlib.common.util.ThreadSafe; +import javasabr.rlib.common.ThreadSafe; public interface LockableArray extends MutableArray, LockableSource, ThreadSafe { } diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/array/LongArray.java b/rlib-collections/src/main/java/javasabr/rlib/collections/array/LongArray.java index 0b6a8e36..e497f22c 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/array/LongArray.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/array/LongArray.java @@ -34,6 +34,10 @@ static LongArray of(long... elements) { return new ImmutableLongArray(elements); } + static LongArray copyOf(LongArray intArray) { + return new ImmutableLongArray(intArray.toArray()); + } + int size(); boolean contains(long value); diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/array/impl/AbstractArray.java b/rlib-collections/src/main/java/javasabr/rlib/collections/array/impl/AbstractArray.java index ebe68081..e73f7b2a 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/array/impl/AbstractArray.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/array/impl/AbstractArray.java @@ -4,6 +4,7 @@ import java.util.Arrays; import java.util.Collection; +import java.util.List; import java.util.function.Consumer; import java.util.function.Function; import javasabr.rlib.collections.array.Array; @@ -246,4 +247,12 @@ public int hashCode() { public UnsafeArray asUnsafe() { return this; } + + @Override + public List toList() { + if (isEmpty()) { + return List.of(); + } + return List.of(Arrays.copyOf(wrapped(), size())); + } } diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/array/impl/CopyOnWriteMutableArray.java b/rlib-collections/src/main/java/javasabr/rlib/collections/array/impl/CopyOnWriteMutableArray.java index 8e94b296..35857c4f 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/array/impl/CopyOnWriteMutableArray.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/array/impl/CopyOnWriteMutableArray.java @@ -6,8 +6,8 @@ import java.util.concurrent.atomic.AtomicReference; import javasabr.rlib.collections.array.Array; import javasabr.rlib.collections.array.UnsafeMutableArray; +import javasabr.rlib.common.ThreadSafe; import javasabr.rlib.common.util.ArrayUtils; -import javasabr.rlib.common.util.ThreadSafe; import lombok.AccessLevel; import lombok.experimental.FieldDefaults; import org.jspecify.annotations.Nullable; diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/Dictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/Dictionary.java index 876f0ca1..d0500950 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/Dictionary.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/Dictionary.java @@ -1,5 +1,6 @@ package javasabr.rlib.collections.dictionary; +import java.util.Collection; import java.util.Optional; import javasabr.rlib.collections.array.Array; import javasabr.rlib.collections.array.MutableArray; @@ -26,10 +27,14 @@ public interface Dictionary extends Iterable { @Nullable V getOrDefault(K key, V def); + > C keys(C container); + MutableArray keys(MutableArray container); Array keys(Class type); + > C values(C container); + MutableArray values(MutableArray container); Array values(Class type); diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/DictionaryCollectors.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/DictionaryCollectors.java index 527e0234..d93d13a2 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/DictionaryCollectors.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/DictionaryCollectors.java @@ -44,28 +44,28 @@ static class CollectorImpl implements Collector { } } - public static Collector, RefDictionary> toRefDictionary( + public static Collector, RefToRefDictionary> toRefToRefDictionary( Function keyMapper) { return new CollectorImpl<>( - DictionaryFactory::mutableRefDictionary, + DictionaryFactory::mutableRefToRefDictionary, uniqKeysAccumulator(keyMapper, Function.identity()), - MutableRefDictionary::append, - MutableRefDictionary::toReadOnly, + MutableRefToRefDictionary::append, + MutableRefToRefDictionary::toReadOnly, CH_ID); } - public static Collector, RefDictionary> toRefDictionary( + public static Collector, RefToRefDictionary> toRefToRefDictionary( Function keyMapper, Function valueMapper) { return new CollectorImpl<>( - DictionaryFactory::mutableRefDictionary, + DictionaryFactory::mutableRefToRefDictionary, uniqKeysAccumulator(keyMapper, valueMapper), - MutableRefDictionary::append, - MutableRefDictionary::toReadOnly, + MutableRefToRefDictionary::append, + MutableRefToRefDictionary::toReadOnly, CH_ID); } - private static BiConsumer, T> uniqKeysAccumulator( + private static BiConsumer, T> uniqKeysAccumulator( Function keyMapper, Function valueMapper) { return (map, element) -> { diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/DictionaryFactory.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/DictionaryFactory.java index 580eb746..34a6fc1b 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/DictionaryFactory.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/DictionaryFactory.java @@ -1,28 +1,38 @@ package javasabr.rlib.collections.dictionary; -import javasabr.rlib.collections.dictionary.impl.DefaultMutableHashBasedRefDictionary; -import javasabr.rlib.collections.dictionary.impl.StampedLockBasedHashBasedRefDictionary; +import javasabr.rlib.collections.dictionary.impl.DefaultMutableHashBasedIntToRefDictionary; +import javasabr.rlib.collections.dictionary.impl.DefaultMutableHashBasedLongToRefDictionary; +import javasabr.rlib.collections.dictionary.impl.DefaultMutableHashBasedRefToRefDictionary; +import javasabr.rlib.collections.dictionary.impl.StampedLockBasedHashBasedRefToRefDictionary; import lombok.experimental.UtilityClass; @UtilityClass public class DictionaryFactory { - public static MutableRefDictionary mutableRefDictionary() { - return new DefaultMutableHashBasedRefDictionary<>(); + public static MutableRefToRefDictionary mutableRefToRefDictionary() { + return new DefaultMutableHashBasedRefToRefDictionary<>(); } - public static MutableRefDictionary mutableRefDictionary( + public static MutableIntToRefDictionary mutableIntToRefDictionary() { + return new DefaultMutableHashBasedIntToRefDictionary<>(); + } + + public static MutableLongToRefDictionary mutableLongToRefDictionary() { + return new DefaultMutableHashBasedLongToRefDictionary<>(); + } + + public static MutableRefToRefDictionary mutableRefToRefDictionary( Class keyType, Class valueType) { - return new DefaultMutableHashBasedRefDictionary<>(); + return new DefaultMutableHashBasedRefToRefDictionary<>(); } - public static LockableRefDictionary stampedLockBasedRefDictionary() { - return new StampedLockBasedHashBasedRefDictionary<>(); + public static LockableRefToRefDictionary stampedLockBasedRefToRefDictionary() { + return new StampedLockBasedHashBasedRefToRefDictionary<>(); } - public static LockableRefDictionary stampedLockBasedRefDictionary( + public static LockableRefToRefDictionary stampedLockBasedRefToRefDictionary( Class keyType, Class valueType) { - return new StampedLockBasedHashBasedRefDictionary<>(); + return new StampedLockBasedHashBasedRefToRefDictionary<>(); } } diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/HashEntry.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/HashEntry.java index 86079db4..885f43f0 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/HashEntry.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/HashEntry.java @@ -1,5 +1,5 @@ package javasabr.rlib.collections.dictionary; -public interface HashEntry extends Entry { +public interface HashEntry { int hash(); } diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/IntToRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/IntToRefDictionary.java new file mode 100644 index 00000000..98d9bf8c --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/IntToRefDictionary.java @@ -0,0 +1,53 @@ +package javasabr.rlib.collections.dictionary; + +import java.util.Optional; +import javasabr.rlib.collections.array.IntArray; +import javasabr.rlib.collections.array.MutableIntArray; +import javasabr.rlib.collections.dictionary.impl.ImmutableHashBasedIntToRefDictionary; +import javasabr.rlib.collections.dictionary.impl.SimpleIntToRefEntry; +import javasabr.rlib.functions.IntObjConsumer; +import org.jspecify.annotations.Nullable; + +public interface IntToRefDictionary extends Dictionary { + + static IntToRefEntry entry(int key, @Nullable V value) { + return new SimpleIntToRefEntry<>(key, value); + } + + static IntToRefDictionary empty() { + return ImmutableHashBasedIntToRefDictionary.empty(); + } + + static IntToRefDictionary of(int key, @Nullable V value) { + return ofEntries(entry(key, value)); + } + + static IntToRefDictionary of(int k1, @Nullable V v1, int k2, @Nullable V v2) { + return ofEntries(entry(k1, v1), entry(k2, v2)); + } + + @SafeVarargs + static IntToRefDictionary ofEntries(IntToRefEntry... entries) { + MutableIntToRefDictionary mutable = DictionaryFactory.mutableIntToRefDictionary(); + for (var entry : entries) { + mutable.put(entry.key(), entry.value()); + } + return mutable.toReadOnly(); + } + + boolean containsKey(int key); + + @Nullable + V get(int key); + + Optional getOptional(int key); + + @Nullable + V getOrDefault(int key, V def); + + MutableIntArray keys(MutableIntArray container); + + IntArray keys(); + + void forEach(IntObjConsumer consumer); +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/IntToRefEntry.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/IntToRefEntry.java new file mode 100644 index 00000000..2aa7c172 --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/IntToRefEntry.java @@ -0,0 +1,7 @@ +package javasabr.rlib.collections.dictionary; + +public interface IntToRefEntry extends RefEntry { + + int key(); + void key(int key); +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/LinkedEntry.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/LinkedEntry.java index 55cc05e5..c3312877 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/LinkedEntry.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/LinkedEntry.java @@ -2,7 +2,7 @@ import org.jspecify.annotations.Nullable; -public interface LinkedEntry extends Entry { +public interface LinkedEntry { @Nullable N next(); void next(@Nullable N next); diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/LinkedHashEntry.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/LinkedHashEntry.java index 8f45ace1..7d472f8c 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/LinkedHashEntry.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/LinkedHashEntry.java @@ -1,5 +1,5 @@ package javasabr.rlib.collections.dictionary; public interface LinkedHashEntry> - extends LinkedEntry, HashEntry { + extends LinkedEntry, HashEntry, RefToRefEntry { } diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/LinkedHashIntToRefEntry.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/LinkedHashIntToRefEntry.java new file mode 100644 index 00000000..a2b74e79 --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/LinkedHashIntToRefEntry.java @@ -0,0 +1,5 @@ +package javasabr.rlib.collections.dictionary; + +public interface LinkedHashIntToRefEntry> + extends LinkedEntry, HashEntry, IntToRefEntry { +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/LinkedHashLongToRefEntry.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/LinkedHashLongToRefEntry.java new file mode 100644 index 00000000..21ad18db --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/LinkedHashLongToRefEntry.java @@ -0,0 +1,5 @@ +package javasabr.rlib.collections.dictionary; + +public interface LinkedHashLongToRefEntry> + extends LinkedEntry, HashEntry, LongToRefEntry { +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/LockableRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/LockableRefDictionary.java deleted file mode 100644 index b6a175b4..00000000 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/LockableRefDictionary.java +++ /dev/null @@ -1,10 +0,0 @@ -package javasabr.rlib.collections.dictionary; - -import javasabr.rlib.collections.operation.LockableOperations; -import javasabr.rlib.collections.operation.LockableSource; -import javasabr.rlib.common.util.ThreadSafe; - -public interface LockableRefDictionary extends MutableRefDictionary, LockableSource, ThreadSafe { - - LockableOperations> operations(); -} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/LockableRefToRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/LockableRefToRefDictionary.java new file mode 100644 index 00000000..07d16c71 --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/LockableRefToRefDictionary.java @@ -0,0 +1,11 @@ +package javasabr.rlib.collections.dictionary; + +import javasabr.rlib.collections.operation.LockableOperations; +import javasabr.rlib.collections.operation.LockableSource; +import javasabr.rlib.common.ThreadSafe; + +public interface LockableRefToRefDictionary extends MutableRefToRefDictionary, + LockableSource, ThreadSafe { + + LockableOperations> operations(); +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/LongToRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/LongToRefDictionary.java new file mode 100644 index 00000000..3ce830b3 --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/LongToRefDictionary.java @@ -0,0 +1,53 @@ +package javasabr.rlib.collections.dictionary; + +import java.util.Optional; +import javasabr.rlib.collections.array.LongArray; +import javasabr.rlib.collections.array.MutableLongArray; +import javasabr.rlib.collections.dictionary.impl.ImmutableHashBasedLongToRefDictionary; +import javasabr.rlib.collections.dictionary.impl.SimpleLongToRefEntry; +import javasabr.rlib.functions.LongObjConsumer; +import org.jspecify.annotations.Nullable; + +public interface LongToRefDictionary extends Dictionary { + + static LongToRefEntry entry(long key, @Nullable V value) { + return new SimpleLongToRefEntry<>(key, value); + } + + static LongToRefDictionary empty() { + return ImmutableHashBasedLongToRefDictionary.empty(); + } + + static LongToRefDictionary of(long key, @Nullable V value) { + return ofEntries(entry(key, value)); + } + + static LongToRefDictionary of(long k1, @Nullable V v1, long k2, @Nullable V v2) { + return ofEntries(entry(k1, v1), entry(k2, v2)); + } + + @SafeVarargs + static LongToRefDictionary ofEntries(LongToRefEntry... entries) { + MutableLongToRefDictionary mutable = DictionaryFactory.mutableLongToRefDictionary(); + for (var entry : entries) { + mutable.put(entry.key(), entry.value()); + } + return mutable.toReadOnly(); + } + + boolean containsKey(long key); + + @Nullable + V get(long key); + + Optional getOptional(long key); + + @Nullable + V getOrDefault(long key, V def); + + MutableLongArray keys(MutableLongArray container); + + LongArray keys(); + + void forEach(LongObjConsumer consumer); +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/LongToRefEntry.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/LongToRefEntry.java new file mode 100644 index 00000000..142feced --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/LongToRefEntry.java @@ -0,0 +1,6 @@ +package javasabr.rlib.collections.dictionary; + +public interface LongToRefEntry extends RefEntry { + long key(); + void key(long key); +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/MutableIntToRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/MutableIntToRefDictionary.java new file mode 100644 index 00000000..5d6035e8 --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/MutableIntToRefDictionary.java @@ -0,0 +1,52 @@ +package javasabr.rlib.collections.dictionary; + +import java.util.Optional; +import java.util.function.Function; +import java.util.function.IntFunction; +import java.util.function.Supplier; +import javasabr.rlib.collections.dictionary.impl.DefaultMutableHashBasedIntToRefDictionary; +import org.jspecify.annotations.Nullable; + +public interface MutableIntToRefDictionary extends IntToRefDictionary { + + static MutableIntToRefDictionary ofTypes(Class valueType) { + return new DefaultMutableHashBasedIntToRefDictionary<>(); + } + + @Nullable + V getOrCompute(int key, Supplier factory); + + @Nullable + V getOrCompute(int key, IntFunction factory); + + @Nullable + V getOrCompute(int key, T arg1, Function factory); + + /** + * @return the previous value for the key or null. + */ + @Nullable + V put(int key, @Nullable V value); + + void putAll(IntToRefDictionary dictionary); + + MutableIntToRefDictionary append(IntToRefDictionary dictionary); + + /** + * @return the optional value of the previous value for the key. + */ + Optional putOptional(int key, @Nullable V value); + + /** + * @return the previous value for the key or null. + */ + @Nullable + V remove(int key); + + /** + * @return the optional value of the previous value for the key. + */ + Optional removeOptional(int key); + + IntToRefDictionary toReadOnly(); +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/MutableLongToRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/MutableLongToRefDictionary.java new file mode 100644 index 00000000..ae5d38ab --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/MutableLongToRefDictionary.java @@ -0,0 +1,52 @@ +package javasabr.rlib.collections.dictionary; + +import java.util.Optional; +import java.util.function.Function; +import java.util.function.LongFunction; +import java.util.function.Supplier; +import javasabr.rlib.collections.dictionary.impl.DefaultMutableHashBasedLongToRefDictionary; +import org.jspecify.annotations.Nullable; + +public interface MutableLongToRefDictionary extends LongToRefDictionary { + + static MutableLongToRefDictionary ofTypes(Class valueType) { + return new DefaultMutableHashBasedLongToRefDictionary<>(); + } + + @Nullable + V getOrCompute(long key, Supplier factory); + + @Nullable + V getOrCompute(long key, LongFunction factory); + + @Nullable + V getOrCompute(long key, T arg1, Function factory); + + /** + * @return the previous value for the key or null. + */ + @Nullable + V put(long key, @Nullable V value); + + void putAll(LongToRefDictionary dictionary); + + MutableLongToRefDictionary append(LongToRefDictionary dictionary); + + /** + * @return the optional value of the previous value for the key. + */ + Optional putOptional(long key, @Nullable V value); + + /** + * @return the previous value for the key or null. + */ + @Nullable + V remove(long key); + + /** + * @return the optional value of the previous value for the key. + */ + Optional removeOptional(long key); + + LongToRefDictionary toReadOnly(); +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/MutableRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/MutableRefToRefDictionary.java similarity index 68% rename from rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/MutableRefDictionary.java rename to rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/MutableRefToRefDictionary.java index 0a296a0a..a88dba5c 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/MutableRefDictionary.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/MutableRefToRefDictionary.java @@ -3,15 +3,15 @@ import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; -import javasabr.rlib.collections.dictionary.impl.DefaultMutableHashBasedRefDictionary; +import javasabr.rlib.collections.dictionary.impl.DefaultMutableHashBasedRefToRefDictionary; import org.jspecify.annotations.Nullable; -public interface MutableRefDictionary extends RefDictionary { +public interface MutableRefToRefDictionary extends RefToRefDictionary { - static MutableRefDictionary ofTypes( + static MutableRefToRefDictionary ofTypes( Class keyType, Class valueType) { - return new DefaultMutableHashBasedRefDictionary<>(); + return new DefaultMutableHashBasedRefToRefDictionary<>(); } @Nullable @@ -29,9 +29,9 @@ static MutableRefDictionary ofTypes( @Nullable V put(K key, @Nullable V value); - void putAll(RefDictionary dictionary); + void putAll(RefToRefDictionary dictionary); - MutableRefDictionary append(RefDictionary dictionary); + MutableRefToRefDictionary append(RefToRefDictionary dictionary); /** * @return the optional value of the previous value for the key. @@ -49,5 +49,5 @@ static MutableRefDictionary ofTypes( */ Optional removeOptional(K key); - RefDictionary toReadOnly(); + RefToRefDictionary toReadOnly(); } diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/RefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/RefDictionary.java deleted file mode 100644 index 438389ab..00000000 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/RefDictionary.java +++ /dev/null @@ -1,36 +0,0 @@ -package javasabr.rlib.collections.dictionary; - -import java.util.function.BiConsumer; -import javasabr.rlib.collections.dictionary.impl.ImmutableHashBasedRefDictionary; -import javasabr.rlib.collections.dictionary.impl.SimpleEntry; -import org.jspecify.annotations.Nullable; - -public interface RefDictionary extends Dictionary { - - static Entry entry(K key, @Nullable V value) { - return new SimpleEntry<>(key, value); - } - - static RefDictionary empty() { - return ImmutableHashBasedRefDictionary.empty(); - } - - static RefDictionary of(K key, @Nullable V value) { - return ofEntries(entry(key, value)); - } - - static RefDictionary of(K k1, @Nullable V v1, K k2, @Nullable V v2) { - return ofEntries(entry(k1, v1), entry(k2, v2)); - } - - @SafeVarargs - static RefDictionary ofEntries(Entry... entries) { - MutableRefDictionary mutable = DictionaryFactory.mutableRefDictionary(); - for (Entry entry : entries) { - mutable.put(entry.key(), entry.value()); - } - return mutable.toReadOnly(); - } - - void forEach(BiConsumer consumer); -} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/Entry.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/RefEntry.java similarity index 69% rename from rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/Entry.java rename to rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/RefEntry.java index 0f7d775c..dd2f75b0 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/Entry.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/RefEntry.java @@ -2,11 +2,7 @@ import org.jspecify.annotations.Nullable; -public interface Entry { - - K key(); - void key(K key); - +public interface RefEntry { @Nullable V value(); void value(@Nullable V value); } diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/RefToRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/RefToRefDictionary.java new file mode 100644 index 00000000..86bf9806 --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/RefToRefDictionary.java @@ -0,0 +1,36 @@ +package javasabr.rlib.collections.dictionary; + +import java.util.function.BiConsumer; +import javasabr.rlib.collections.dictionary.impl.ImmutableHashBasedRefToRefDictionary; +import javasabr.rlib.collections.dictionary.impl.SimpleRefToRefEntry; +import org.jspecify.annotations.Nullable; + +public interface RefToRefDictionary extends Dictionary { + + static RefToRefEntry entry(K key, @Nullable V value) { + return new SimpleRefToRefEntry<>(key, value); + } + + static RefToRefDictionary empty() { + return ImmutableHashBasedRefToRefDictionary.empty(); + } + + static RefToRefDictionary of(K key, @Nullable V value) { + return ofEntries(entry(key, value)); + } + + static RefToRefDictionary of(K k1, @Nullable V v1, K k2, @Nullable V v2) { + return ofEntries(entry(k1, v1), entry(k2, v2)); + } + + @SafeVarargs + static RefToRefDictionary ofEntries(RefToRefEntry... entries) { + MutableRefToRefDictionary mutable = DictionaryFactory.mutableRefToRefDictionary(); + for (var entry : entries) { + mutable.put(entry.key(), entry.value()); + } + return mutable.toReadOnly(); + } + + void forEach(BiConsumer consumer); +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/RefToRefEntry.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/RefToRefEntry.java new file mode 100644 index 00000000..ea14f74e --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/RefToRefEntry.java @@ -0,0 +1,6 @@ +package javasabr.rlib.collections.dictionary; + +public interface RefToRefEntry extends RefEntry { + K key(); + void key(K key); +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/UnsafeRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/UnsafeIntToRefDictionary.java similarity index 53% rename from rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/UnsafeRefDictionary.java rename to rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/UnsafeIntToRefDictionary.java index 6783c971..b80b63e9 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/UnsafeRefDictionary.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/UnsafeIntToRefDictionary.java @@ -2,7 +2,7 @@ import org.jspecify.annotations.Nullable; -public interface UnsafeRefDictionary> extends RefDictionary { +public interface UnsafeIntToRefDictionary> extends IntToRefDictionary { @Nullable E[] entries(); } diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/UnsafeLongToRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/UnsafeLongToRefDictionary.java new file mode 100644 index 00000000..bd52c2c3 --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/UnsafeLongToRefDictionary.java @@ -0,0 +1,8 @@ +package javasabr.rlib.collections.dictionary; + +import org.jspecify.annotations.Nullable; + +public interface UnsafeLongToRefDictionary> extends LongToRefDictionary { + + @Nullable E[] entries(); +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/UnsafeMutableIntToRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/UnsafeMutableIntToRefDictionary.java new file mode 100644 index 00000000..6a1fecb8 --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/UnsafeMutableIntToRefDictionary.java @@ -0,0 +1,6 @@ +package javasabr.rlib.collections.dictionary; + +public interface UnsafeMutableIntToRefDictionary> + extends MutableIntToRefDictionary, UnsafeIntToRefDictionary { + +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/UnsafeMutableLongToRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/UnsafeMutableLongToRefDictionary.java new file mode 100644 index 00000000..1ed37350 --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/UnsafeMutableLongToRefDictionary.java @@ -0,0 +1,6 @@ +package javasabr.rlib.collections.dictionary; + +public interface UnsafeMutableLongToRefDictionary> + extends MutableLongToRefDictionary, UnsafeLongToRefDictionary { + +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/UnsafeMutableRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/UnsafeMutableRefDictionary.java deleted file mode 100644 index 23fac3de..00000000 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/UnsafeMutableRefDictionary.java +++ /dev/null @@ -1,6 +0,0 @@ -package javasabr.rlib.collections.dictionary; - -public interface UnsafeMutableRefDictionary> - extends MutableRefDictionary, UnsafeRefDictionary { - -} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/UnsafeMutableRefToRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/UnsafeMutableRefToRefDictionary.java new file mode 100644 index 00000000..c4c98de2 --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/UnsafeMutableRefToRefDictionary.java @@ -0,0 +1,6 @@ +package javasabr.rlib.collections.dictionary; + +public interface UnsafeMutableRefToRefDictionary> + extends MutableRefToRefDictionary, UnsafeRefToRefDictionary { + +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/UnsafeRefToRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/UnsafeRefToRefDictionary.java new file mode 100644 index 00000000..97e8bca9 --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/UnsafeRefToRefDictionary.java @@ -0,0 +1,9 @@ +package javasabr.rlib.collections.dictionary; + +import org.jspecify.annotations.Nullable; + +public interface UnsafeRefToRefDictionary> + extends RefToRefDictionary { + + @Nullable E[] entries(); +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractHashBasedIntToRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractHashBasedIntToRefDictionary.java new file mode 100644 index 00000000..d8da55cf --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractHashBasedIntToRefDictionary.java @@ -0,0 +1,209 @@ +package javasabr.rlib.collections.dictionary.impl; + +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.Objects; +import java.util.Optional; +import javasabr.rlib.collections.array.Array; +import javasabr.rlib.collections.array.ArrayFactory; +import javasabr.rlib.collections.array.IntArray; +import javasabr.rlib.collections.array.MutableArray; +import javasabr.rlib.collections.array.MutableIntArray; +import javasabr.rlib.collections.array.UnsafeMutableArray; +import javasabr.rlib.collections.array.UnsafeMutableIntArray; +import javasabr.rlib.collections.dictionary.LinkedHashIntToRefEntry; +import javasabr.rlib.collections.dictionary.UnsafeIntToRefDictionary; +import javasabr.rlib.functions.IntObjConsumer; +import org.jspecify.annotations.Nullable; + +public abstract class AbstractHashBasedIntToRefDictionary> + extends AbstractHashBasedDictionary + implements UnsafeIntToRefDictionary { + + @Override + public boolean containsKey(Integer key) { + return findEntry(key) != null; + } + + @Override + public boolean containsKey(int key) { + return findEntry(key) != null; + } + + @Override + public boolean containsValue(V value) { + + for (E entry : entries()) { + for (E nextEntry = entry; nextEntry != null; nextEntry = nextEntry.next()) { + if (Objects.equals(value, nextEntry.value())) { + return true; + } + } + } + + return false; + } + + @Nullable + @Override + public V get(Integer key) { + return get(key.intValue()); + } + + @Nullable + @Override + public V get(int key) { + E entry = findEntry(key); + return entry == null ? null : entry.value(); + } + + @Nullable + @Override + public V getOrDefault(Integer key, V def) { + return getOrDefault(key.intValue(), def); + } + + @Nullable + @Override + public V getOrDefault(int key, V def) { + E entry = findEntry(key); + return entry == null ? def : entry.value(); + } + + @Override + public Optional getOptional(Integer key) { + return getOptional(key.intValue()); + } + + @Override + public Optional getOptional(int key) { + return Optional.ofNullable(get(key)); + } + + @Override + public Iterator iterator() { + if (isEmpty()) { + return Collections.emptyIterator(); + } + return new LinkedRefEntryIterator<>(entries()); + } + + @Nullable + protected E findEntry(int key) { + + @Nullable E[] entries = entries(); + int hash = hash(key); + int entryIndex = indexFor(hash, entries.length); + + for (E entry = entries[entryIndex]; entry != null; entry = entry.next()) { + if (entry.hash() == hash && key == entry.key()) { + return entry; + } + } + + return null; + } + + @Override + public void forEach(IntObjConsumer consumer) { + for (E entry : entries()) { + while (entry != null) { + //noinspection DataFlowIssue + consumer.accept(entry.key(), entry.value()); + entry = entry.next(); + } + } + } + + @Override + public IntArray keys() { + return IntArray.copyOf(keys(ArrayFactory.mutableIntArray())); + } + + @Override + public MutableIntArray keys(MutableIntArray container) { + + UnsafeMutableIntArray unsafe = container.asUnsafe(); + unsafe.prepareForSize(container.size() + size()); + + for (E entry : entries()) { + while (entry != null) { + unsafe.unsafeAdd(entry.key()); + entry = entry.next(); + } + } + + return container; + } + + @Override + public Array keys(Class type) { + return keys(MutableArray.ofType(Integer.class)); + } + + @Override + public MutableArray keys(MutableArray container) { + + UnsafeMutableArray unsafe = container.asUnsafe(); + unsafe.prepareForSize(container.size() + size()); + + for (E entry : entries()) { + while (entry != null) { + unsafe.unsafeAdd(entry.key()); + entry = entry.next(); + } + } + + return container; + } + + @Override + public > C keys(C container) { + for (E entry : entries()) { + while (entry != null) { + container.add(entry.key()); + entry = entry.next(); + } + } + return container; + } + + @Override + public Array values(Class type) { + return Array.copyOf(values(ArrayFactory.mutableArray(type, size()))); + } + + @Override + public > C values(C container) { + for (E entry : entries()) { + while (entry != null) { + V value = entry.value(); + if (value != null) { + container.add(value); + } + entry = entry.next(); + } + } + return container; + } + + @Override + public MutableArray values(MutableArray container) { + + UnsafeMutableArray unsafe = container.asUnsafe(); + unsafe.prepareForSize(container.size() + size()); + + for (E entry : entries()) { + while (entry != null) { + V value = entry.value(); + if (value != null) { + unsafe.unsafeAdd(value); + } + entry = entry.next(); + } + } + + return container; + } +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractHashBasedLongToRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractHashBasedLongToRefDictionary.java new file mode 100644 index 00000000..2b5dcb45 --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractHashBasedLongToRefDictionary.java @@ -0,0 +1,209 @@ +package javasabr.rlib.collections.dictionary.impl; + +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.Objects; +import java.util.Optional; +import javasabr.rlib.collections.array.Array; +import javasabr.rlib.collections.array.ArrayFactory; +import javasabr.rlib.collections.array.LongArray; +import javasabr.rlib.collections.array.MutableArray; +import javasabr.rlib.collections.array.MutableLongArray; +import javasabr.rlib.collections.array.UnsafeMutableArray; +import javasabr.rlib.collections.array.UnsafeMutableLongArray; +import javasabr.rlib.collections.dictionary.LinkedHashLongToRefEntry; +import javasabr.rlib.collections.dictionary.UnsafeLongToRefDictionary; +import javasabr.rlib.functions.LongObjConsumer; +import org.jspecify.annotations.Nullable; + +public abstract class AbstractHashBasedLongToRefDictionary> + extends AbstractHashBasedDictionary + implements UnsafeLongToRefDictionary { + + @Override + public boolean containsKey(Long key) { + return findEntry(key) != null; + } + + @Override + public boolean containsKey(long key) { + return findEntry(key) != null; + } + + @Override + public boolean containsValue(V value) { + + for (E entry : entries()) { + for (E nextEntry = entry; nextEntry != null; nextEntry = nextEntry.next()) { + if (Objects.equals(value, nextEntry.value())) { + return true; + } + } + } + + return false; + } + + @Nullable + @Override + public V get(Long key) { + return get(key.longValue()); + } + + @Nullable + @Override + public V get(long key) { + E entry = findEntry(key); + return entry == null ? null : entry.value(); + } + + @Nullable + @Override + public V getOrDefault(Long key, V def) { + return getOrDefault(key.longValue(), def); + } + + @Nullable + @Override + public V getOrDefault(long key, V def) { + E entry = findEntry(key); + return entry == null ? def : entry.value(); + } + + @Override + public Optional getOptional(Long key) { + return getOptional(key.longValue()); + } + + @Override + public Optional getOptional(long key) { + return Optional.ofNullable(get(key)); + } + + @Override + public Iterator iterator() { + if (isEmpty()) { + return Collections.emptyIterator(); + } + return new LinkedRefEntryIterator<>(entries()); + } + + @Nullable + protected E findEntry(long key) { + + @Nullable E[] entries = entries(); + int hash = hash(Long.hashCode(key)); + int entryIndex = indexFor(hash, entries.length); + + for (E entry = entries[entryIndex]; entry != null; entry = entry.next()) { + if (entry.hash() == hash && key == entry.key()) { + return entry; + } + } + + return null; + } + + @Override + public void forEach(LongObjConsumer consumer) { + for (E entry : entries()) { + while (entry != null) { + //noinspection DataFlowIssue + consumer.accept(entry.key(), entry.value()); + entry = entry.next(); + } + } + } + + @Override + public LongArray keys() { + return LongArray.copyOf(keys(ArrayFactory.mutableLongArray())); + } + + @Override + public MutableLongArray keys(MutableLongArray container) { + + UnsafeMutableLongArray unsafe = container.asUnsafe(); + unsafe.prepareForSize(container.size() + size()); + + for (E entry : entries()) { + while (entry != null) { + unsafe.unsafeAdd(entry.key()); + entry = entry.next(); + } + } + + return container; + } + + @Override + public Array keys(Class type) { + return keys(MutableArray.ofType(Long.class)); + } + + @Override + public MutableArray keys(MutableArray container) { + + UnsafeMutableArray unsafe = container.asUnsafe(); + unsafe.prepareForSize(container.size() + size()); + + for (E entry : entries()) { + while (entry != null) { + unsafe.unsafeAdd(entry.key()); + entry = entry.next(); + } + } + + return container; + } + + @Override + public > C keys(C container) { + for (E entry : entries()) { + while (entry != null) { + container.add(entry.key()); + entry = entry.next(); + } + } + return container; + } + + @Override + public Array values(Class type) { + return Array.copyOf(values(ArrayFactory.mutableArray(type, size()))); + } + + @Override + public > C values(C container) { + for (E entry : entries()) { + while (entry != null) { + V value = entry.value(); + if (value != null) { + container.add(value); + } + entry = entry.next(); + } + } + return container; + } + + @Override + public MutableArray values(MutableArray container) { + + UnsafeMutableArray unsafe = container.asUnsafe(); + unsafe.prepareForSize(container.size() + size()); + + for (E entry : entries()) { + while (entry != null) { + V value = entry.value(); + if (value != null) { + unsafe.unsafeAdd(value); + } + entry = entry.next(); + } + } + + return container; + } +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractHashBasedRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractHashBasedRefToRefDictionary.java similarity index 67% rename from rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractHashBasedRefDictionary.java rename to rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractHashBasedRefToRefDictionary.java index 62274774..e66b2baf 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractHashBasedRefDictionary.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractHashBasedRefToRefDictionary.java @@ -1,5 +1,6 @@ package javasabr.rlib.collections.dictionary.impl; +import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Objects; @@ -10,12 +11,12 @@ import javasabr.rlib.collections.array.MutableArray; import javasabr.rlib.collections.array.UnsafeMutableArray; import javasabr.rlib.collections.dictionary.LinkedHashEntry; -import javasabr.rlib.collections.dictionary.UnsafeRefDictionary; +import javasabr.rlib.collections.dictionary.UnsafeRefToRefDictionary; import org.jspecify.annotations.Nullable; -public abstract class AbstractHashBasedRefDictionary> +public abstract class AbstractHashBasedRefToRefDictionary> extends AbstractHashBasedDictionary - implements UnsafeRefDictionary { + implements UnsafeRefToRefDictionary { @Override public boolean containsKey(K key) { @@ -60,7 +61,7 @@ public Iterator iterator() { if (isEmpty()) { return Collections.emptyIterator(); } - return new LinkedEntryIterator<>(entries()); + return new LinkedRefEntryIterator<>(entries()); } @Nullable @@ -95,6 +96,17 @@ public Array keys(Class type) { return Array.copyOf(keys(ArrayFactory.mutableArray(type, size()))); } + @Override + public > C keys(C container) { + for (E entry : entries()) { + while (entry != null) { + container.add(entry.key()); + entry = entry.next(); + } + } + return container; + } + @Override public MutableArray keys(MutableArray container) { @@ -116,6 +128,20 @@ public Array values(Class type) { return Array.copyOf(values(ArrayFactory.mutableArray(type, size()))); } + @Override + public > C values(C container) { + for (E entry : entries()) { + while (entry != null) { + V value = entry.value(); + if (value != null) { + container.add(value); + } + entry = entry.next(); + } + } + return container; + } + @Override public MutableArray values(MutableArray container) { @@ -134,4 +160,38 @@ public MutableArray values(MutableArray container) { return container; } + + @Override + public String toString() { + + if (isEmpty()) { + return "[]"; + } + + StringBuilder builder = new StringBuilder("["); + + for (E entry : entries()) { + while (entry != null) { + builder + .append('\'') + .append(entry.key()) + .append('\'') + .append(":") + .append('\'') + .append(entry.value()) + .append('\'') + .append(", "); + + entry = entry.next(); + } + } + + if (builder.length() > 1) { + builder.delete(builder.length() - 2, builder.length()); + } + + builder.append("]"); + + return builder.toString(); + } } diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractLockableHashBasedRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractLockableHashBasedRefToRefDictionary.java similarity index 76% rename from rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractLockableHashBasedRefDictionary.java rename to rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractLockableHashBasedRefToRefDictionary.java index 121f27e3..a9b59ce1 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractLockableHashBasedRefDictionary.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractLockableHashBasedRefToRefDictionary.java @@ -3,8 +3,8 @@ import java.util.Arrays; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; -import javasabr.rlib.collections.dictionary.LockableRefDictionary; -import javasabr.rlib.collections.dictionary.RefDictionary; +import javasabr.rlib.collections.dictionary.LockableRefToRefDictionary; +import javasabr.rlib.collections.dictionary.RefToRefDictionary; import javasabr.rlib.collections.operation.LockableOperations; import javasabr.rlib.collections.operation.impl.DefaultLockableOperations; import lombok.AccessLevel; @@ -12,19 +12,20 @@ import org.jspecify.annotations.Nullable; @FieldDefaults(level = AccessLevel.PROTECTED) -public abstract class AbstractLockableHashBasedRefDictionary extends - AbstractMutableHashBasedRefDictionary> implements LockableRefDictionary { +public abstract class AbstractLockableHashBasedRefToRefDictionary extends + AbstractMutableHashBasedRefToRefDictionary> implements + LockableRefToRefDictionary { final AtomicReference<@Nullable DefaultLinkedHashEntry[]> entries; final AtomicInteger size; int threshold; - public AbstractLockableHashBasedRefDictionary() { + public AbstractLockableHashBasedRefToRefDictionary() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR); } - public AbstractLockableHashBasedRefDictionary(int initCapacity, float loadFactor) { + public AbstractLockableHashBasedRefToRefDictionary(int initCapacity, float loadFactor) { super(loadFactor); //noinspection unchecked,rawtypes this.entries = new AtomicReference<>(new DefaultLinkedHashEntry[initCapacity]); @@ -89,14 +90,14 @@ protected DefaultLinkedHashEntry[] allocate(int length) { } @Override - public RefDictionary toReadOnly() { + public RefToRefDictionary toReadOnly() { @Nullable DefaultLinkedHashEntry[] currentEntries = entries.get(); @Nullable DefaultLinkedHashEntry[] copied = Arrays.copyOf(currentEntries, currentEntries.length); - return new ImmutableHashBasedRefDictionary<>(copied, size.get()); + return new ImmutableHashBasedRefToRefDictionary<>(copied, size.get()); } @Override - public LockableOperations> operations() { + public LockableOperations> operations() { return new DefaultLockableOperations<>(this); } } diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractMutableHashBasedIntToRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractMutableHashBasedIntToRefDictionary.java new file mode 100644 index 00000000..10c3ae0f --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractMutableHashBasedIntToRefDictionary.java @@ -0,0 +1,221 @@ +package javasabr.rlib.collections.dictionary.impl; + +import java.util.Optional; +import java.util.function.Function; +import java.util.function.IntFunction; +import java.util.function.Supplier; +import javasabr.rlib.collections.dictionary.IntToRefDictionary; +import javasabr.rlib.collections.dictionary.LinkedHashIntToRefEntry; +import javasabr.rlib.collections.dictionary.MutableIntToRefDictionary; +import javasabr.rlib.collections.dictionary.UnsafeMutableIntToRefDictionary; +import lombok.AccessLevel; +import lombok.RequiredArgsConstructor; +import lombok.experimental.FieldDefaults; +import org.jspecify.annotations.Nullable; + +@RequiredArgsConstructor +@FieldDefaults(level = AccessLevel.PROTECTED) +public abstract class AbstractMutableHashBasedIntToRefDictionary> + extends AbstractHashBasedIntToRefDictionary implements UnsafeMutableIntToRefDictionary { + + protected static final int DEFAULT_INITIAL_CAPACITY = 16; + protected static final int DEFAULT_MAXIMUM_CAPACITY = 1 << 30; + protected static final float DEFAULT_LOAD_FACTOR = 0.75f; + + final float loadFactor; + + @Nullable + @Override + public V getOrCompute(int key, IntFunction factory) { + + E entry = findEntry(key); + if (entry != null) { + return entry.value(); + } + + V newValue = factory.apply(key); + put(key, newValue); + return newValue; + } + + @Nullable + @Override + public V getOrCompute(int key, Supplier factory) { + E entry = findEntry(key); + if (entry != null) { + return entry.value(); + } + + V newValue = factory.get(); + put(key, newValue); + return newValue; + } + + @Nullable + @Override + public V getOrCompute(int key, T arg1, Function factory) { + E entry = findEntry(key); + if (entry != null) { + return entry.value(); + } + + V newValue = factory.apply(arg1); + put(key, newValue); + return newValue; + } + + @Nullable + @Override + public V put(int key, V value) { + + @Nullable E[] entries = entries(); + int hash = hash(key); + int entryIndex = indexFor(hash, entries.length); + + for (E entry = entries[entryIndex]; entry != null; entry = entry.next()) { + if (entry.hash() == hash && key == entry.key()) { + V prev = entry.value(); + entry.value(value); + return prev; + } + } + + addEntry(hash, key, value, entryIndex); + return null; + } + + @Override + public Optional putOptional(int key, V value) { + return Optional.ofNullable(put(key, value)); + } + + @Override + public void putAll(IntToRefDictionary dictionary) { + if (dictionary instanceof AbstractHashBasedIntToRefDictionary hashBased) { + for (var entry : hashBased.entries()) { + while (entry != null) { + //noinspection DataFlowIssue,unchecked + put(entry.key(), (V) entry.value()); + entry = entry.next(); + } + } + } else { + dictionary.forEach(this::put); + } + } + + @Override + public MutableIntToRefDictionary append(IntToRefDictionary dictionary) { + putAll(dictionary); + return this; + } + + @Nullable + @Override + public V remove(int key) { + E removed = removeEntryForKey(key); + if (removed == null) { + return null; + } + return removed.value(); + } + + @Override + public Optional removeOptional(int key) { + return Optional.ofNullable(remove(key)); + } + + @Nullable + protected E removeEntryForKey(int key) { + + @Nullable E[] entries = entries(); + int hash = hash(key); + int entryIndex = indexFor(hash, entries.length); + + E previosEntry = entries[entryIndex]; + E entry = previosEntry; + + while (entry != null) { + E nextEntry = entry.next(); + if (entry.hash() == hash && key == entry.key()) { + decrementSize(); + if (previosEntry == entry) { + entries[entryIndex] = nextEntry; + } else { + previosEntry.next(nextEntry); + } + return entry; + } + previosEntry = entry; + entry = nextEntry; + } + + return null; + } + + protected void addEntry(int hash, int key, @Nullable V value, int index) { + + @Nullable E[] entries = entries(); + E currentEntry = entries[index]; + + var newEntry = allocate(hash, key, value, currentEntry); + entries[index] = newEntry; + + if (incrementSize() >= threshold()) { + resize(2 * entries.length); + } + } + + protected abstract int threshold(); + protected abstract void threshold(int threshold); + + protected abstract int incrementSize(); + protected abstract int decrementSize(); + + protected abstract void entries(@Nullable E[] entries); + + protected abstract E allocate(int hash, int key, @Nullable V value, @Nullable E next); + + @Nullable + protected abstract E[] allocate(int length); + + protected final void resize(int newLength) { + + @Nullable E[] currentEntries = entries(); + int oldLength = currentEntries.length; + + if (oldLength >= DEFAULT_MAXIMUM_CAPACITY) { + threshold(Integer.MAX_VALUE); + return; + } + + @Nullable E[] newEntries = allocate(newLength); + + transfer(currentEntries, newEntries); + entries(newEntries); + threshold((int) (newLength * loadFactor)); + } + + protected void transfer( + @Nullable E[] currentEntries, + @Nullable E[] newEntries) { + + int newCapacity = newEntries.length; + + for (E entry : currentEntries) { + if (entry == null) { + continue; + } + do { + + E nextEntry = entry.next(); + int newIndex = indexFor(entry.hash(), newCapacity); + + entry.next(newEntries[newIndex]); + newEntries[newIndex] = entry; + entry = nextEntry; + + } while (entry != null); + } + } +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractMutableHashBasedLongToRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractMutableHashBasedLongToRefDictionary.java new file mode 100644 index 00000000..394965f3 --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractMutableHashBasedLongToRefDictionary.java @@ -0,0 +1,221 @@ +package javasabr.rlib.collections.dictionary.impl; + +import java.util.Optional; +import java.util.function.Function; +import java.util.function.LongFunction; +import java.util.function.Supplier; +import javasabr.rlib.collections.dictionary.LinkedHashLongToRefEntry; +import javasabr.rlib.collections.dictionary.LongToRefDictionary; +import javasabr.rlib.collections.dictionary.MutableLongToRefDictionary; +import javasabr.rlib.collections.dictionary.UnsafeMutableLongToRefDictionary; +import lombok.AccessLevel; +import lombok.RequiredArgsConstructor; +import lombok.experimental.FieldDefaults; +import org.jspecify.annotations.Nullable; + +@RequiredArgsConstructor +@FieldDefaults(level = AccessLevel.PROTECTED) +public abstract class AbstractMutableHashBasedLongToRefDictionary> + extends AbstractHashBasedLongToRefDictionary implements UnsafeMutableLongToRefDictionary { + + protected static final int DEFAULT_INITIAL_CAPACITY = 16; + protected static final int DEFAULT_MAXIMUM_CAPACITY = 1 << 30; + protected static final float DEFAULT_LOAD_FACTOR = 0.75f; + + final float loadFactor; + + @Nullable + @Override + public V getOrCompute(long key, LongFunction factory) { + + E entry = findEntry(key); + if (entry != null) { + return entry.value(); + } + + V newValue = factory.apply(key); + put(key, newValue); + return newValue; + } + + @Nullable + @Override + public V getOrCompute(long key, Supplier factory) { + E entry = findEntry(key); + if (entry != null) { + return entry.value(); + } + + V newValue = factory.get(); + put(key, newValue); + return newValue; + } + + @Nullable + @Override + public V getOrCompute(long key, T arg1, Function factory) { + E entry = findEntry(key); + if (entry != null) { + return entry.value(); + } + + V newValue = factory.apply(arg1); + put(key, newValue); + return newValue; + } + + @Nullable + @Override + public V put(long key, V value) { + + @Nullable E[] entries = entries(); + int hash = hash(Long.hashCode(key)); + int entryIndex = indexFor(hash, entries.length); + + for (E entry = entries[entryIndex]; entry != null; entry = entry.next()) { + if (entry.hash() == hash && key == entry.key()) { + V prev = entry.value(); + entry.value(value); + return prev; + } + } + + addEntry(hash, key, value, entryIndex); + return null; + } + + @Override + public Optional putOptional(long key, V value) { + return Optional.ofNullable(put(key, value)); + } + + @Override + public void putAll(LongToRefDictionary dictionary) { + if (dictionary instanceof AbstractHashBasedLongToRefDictionary hashBased) { + for (var entry : hashBased.entries()) { + while (entry != null) { + //noinspection DataFlowIssue,unchecked + put(entry.key(), (V) entry.value()); + entry = entry.next(); + } + } + } else { + dictionary.forEach(this::put); + } + } + + @Override + public MutableLongToRefDictionary append(LongToRefDictionary dictionary) { + putAll(dictionary); + return this; + } + + @Nullable + @Override + public V remove(long key) { + E removed = removeEntryForKey(key); + if (removed == null) { + return null; + } + return removed.value(); + } + + @Override + public Optional removeOptional(long key) { + return Optional.ofNullable(remove(key)); + } + + @Nullable + protected E removeEntryForKey(long key) { + + @Nullable E[] entries = entries(); + int hash = hash(Long.hashCode(key)); + int entryIndex = indexFor(hash, entries.length); + + E previosEntry = entries[entryIndex]; + E entry = previosEntry; + + while (entry != null) { + E nextEntry = entry.next(); + if (entry.hash() == hash && key == entry.key()) { + decrementSize(); + if (previosEntry == entry) { + entries[entryIndex] = nextEntry; + } else { + previosEntry.next(nextEntry); + } + return entry; + } + previosEntry = entry; + entry = nextEntry; + } + + return null; + } + + protected void addEntry(int hash, long key, @Nullable V value, int index) { + + @Nullable E[] entries = entries(); + E currentEntry = entries[index]; + + var newEntry = allocate(hash, key, value, currentEntry); + entries[index] = newEntry; + + if (incrementSize() >= threshold()) { + resize(2 * entries.length); + } + } + + protected abstract int threshold(); + protected abstract void threshold(int threshold); + + protected abstract int incrementSize(); + protected abstract int decrementSize(); + + protected abstract void entries(@Nullable E[] entries); + + protected abstract E allocate(int hash, long key, @Nullable V value, @Nullable E next); + + @Nullable + protected abstract E[] allocate(int length); + + protected final void resize(int newLength) { + + @Nullable E[] currentEntries = entries(); + int oldLength = currentEntries.length; + + if (oldLength >= DEFAULT_MAXIMUM_CAPACITY) { + threshold(Integer.MAX_VALUE); + return; + } + + @Nullable E[] newEntries = allocate(newLength); + + transfer(currentEntries, newEntries); + entries(newEntries); + threshold((int) (newLength * loadFactor)); + } + + protected void transfer( + @Nullable E[] currentEntries, + @Nullable E[] newEntries) { + + int newCapacity = newEntries.length; + + for (E entry : currentEntries) { + if (entry == null) { + continue; + } + do { + + E nextEntry = entry.next(); + int newIndex = indexFor(entry.hash(), newCapacity); + + entry.next(newEntries[newIndex]); + newEntries[newIndex] = entry; + entry = nextEntry; + + } while (entry != null); + } + } +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractMutableHashBasedRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractMutableHashBasedRefToRefDictionary.java similarity index 87% rename from rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractMutableHashBasedRefDictionary.java rename to rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractMutableHashBasedRefToRefDictionary.java index a4ab095a..3c9fa93e 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractMutableHashBasedRefDictionary.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/AbstractMutableHashBasedRefToRefDictionary.java @@ -4,9 +4,9 @@ import java.util.function.Function; import java.util.function.Supplier; import javasabr.rlib.collections.dictionary.LinkedHashEntry; -import javasabr.rlib.collections.dictionary.MutableRefDictionary; -import javasabr.rlib.collections.dictionary.RefDictionary; -import javasabr.rlib.collections.dictionary.UnsafeMutableRefDictionary; +import javasabr.rlib.collections.dictionary.MutableRefToRefDictionary; +import javasabr.rlib.collections.dictionary.RefToRefDictionary; +import javasabr.rlib.collections.dictionary.UnsafeMutableRefToRefDictionary; import lombok.AccessLevel; import lombok.RequiredArgsConstructor; import lombok.experimental.FieldDefaults; @@ -14,8 +14,8 @@ @RequiredArgsConstructor @FieldDefaults(level = AccessLevel.PROTECTED) -public abstract class AbstractMutableHashBasedRefDictionary> - extends AbstractHashBasedRefDictionary implements UnsafeMutableRefDictionary { +public abstract class AbstractMutableHashBasedRefToRefDictionary> + extends AbstractHashBasedRefToRefDictionary implements UnsafeMutableRefToRefDictionary { protected static final int DEFAULT_INITIAL_CAPACITY = 16; protected static final int DEFAULT_MAXIMUM_CAPACITY = 1 << 30; @@ -89,8 +89,8 @@ public Optional putOptional(K key, V value) { } @Override - public void putAll(RefDictionary dictionary) { - if (dictionary instanceof AbstractHashBasedRefDictionary hashBased) { + public void putAll(RefToRefDictionary dictionary) { + if (dictionary instanceof AbstractHashBasedRefToRefDictionary hashBased) { for (var entry : hashBased.entries()) { while (entry != null) { //noinspection DataFlowIssue,unchecked @@ -104,7 +104,7 @@ public void putAll(RefDictionary dictionary) { } @Override - public MutableRefDictionary append(RefDictionary dictionary) { + public MutableRefToRefDictionary append(RefToRefDictionary dictionary) { putAll(dictionary); return this; } diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/DefaultLinkedHashIntToRefEntry.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/DefaultLinkedHashIntToRefEntry.java new file mode 100644 index 00000000..d9c5504c --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/DefaultLinkedHashIntToRefEntry.java @@ -0,0 +1,37 @@ +package javasabr.rlib.collections.dictionary.impl; + +import javasabr.rlib.collections.dictionary.LinkedHashIntToRefEntry; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.Setter; +import lombok.experimental.Accessors; +import lombok.experimental.FieldDefaults; +import org.jspecify.annotations.Nullable; + +@Getter +@Setter +@Accessors(fluent = true, chain = false) +@FieldDefaults(level = AccessLevel.PRIVATE) +public class DefaultLinkedHashIntToRefEntry implements + LinkedHashIntToRefEntry> { + + @Nullable + DefaultLinkedHashIntToRefEntry next; + + int key; + @Nullable + V value; + + int hash; + + public DefaultLinkedHashIntToRefEntry( + @Nullable DefaultLinkedHashIntToRefEntry next, + int key, + @Nullable V value, + int hash) { + this.next = next; + this.key = key; + this.value = value; + this.hash = hash; + } +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/DefaultLinkedHashLongToRefEntry.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/DefaultLinkedHashLongToRefEntry.java new file mode 100644 index 00000000..6471f356 --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/DefaultLinkedHashLongToRefEntry.java @@ -0,0 +1,37 @@ +package javasabr.rlib.collections.dictionary.impl; + +import javasabr.rlib.collections.dictionary.LinkedHashLongToRefEntry; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.Setter; +import lombok.experimental.Accessors; +import lombok.experimental.FieldDefaults; +import org.jspecify.annotations.Nullable; + +@Getter +@Setter +@Accessors(fluent = true, chain = false) +@FieldDefaults(level = AccessLevel.PRIVATE) +public class DefaultLinkedHashLongToRefEntry implements + LinkedHashLongToRefEntry> { + + @Nullable + DefaultLinkedHashLongToRefEntry next; + + long key; + @Nullable + V value; + + int hash; + + public DefaultLinkedHashLongToRefEntry( + @Nullable DefaultLinkedHashLongToRefEntry next, + long key, + @Nullable V value, + int hash) { + this.next = next; + this.key = key; + this.value = value; + this.hash = hash; + } +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/DefaultMutableHashBasedIntToRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/DefaultMutableHashBasedIntToRefDictionary.java new file mode 100644 index 00000000..b7081081 --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/DefaultMutableHashBasedIntToRefDictionary.java @@ -0,0 +1,78 @@ +package javasabr.rlib.collections.dictionary.impl; + +import java.util.Arrays; +import javasabr.rlib.collections.dictionary.IntToRefDictionary; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.experimental.Accessors; +import lombok.experimental.FieldDefaults; +import org.jspecify.annotations.Nullable; + +@Getter +@Accessors(fluent = true) +@FieldDefaults(level = AccessLevel.PROTECTED) +public class DefaultMutableHashBasedIntToRefDictionary extends + AbstractMutableHashBasedIntToRefDictionary> { + + @Nullable DefaultLinkedHashIntToRefEntry[] entries; + int size; + int threshold; + + public DefaultMutableHashBasedIntToRefDictionary() { + this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR); + } + + public DefaultMutableHashBasedIntToRefDictionary(int initCapacity, float loadFactor) { + super(loadFactor); + //noinspection unchecked + this.entries = new DefaultLinkedHashIntToRefEntry[initCapacity]; + this.threshold = (int) (initCapacity * loadFactor); + } + + @Override + public boolean isEmpty() { + return size < 1; + } + + @Override + protected int incrementSize() { + return size++; + } + + @Override + protected int decrementSize() { + return size--; + } + + @Override + protected void threshold(int threshold) { + this.threshold = threshold; + } + + @Override + protected void entries(@Nullable DefaultLinkedHashIntToRefEntry[] entries) { + this.entries = entries; + } + + @Override + protected DefaultLinkedHashIntToRefEntry allocate( + int hash, + int key, + @Nullable V value, + @Nullable DefaultLinkedHashIntToRefEntry next) { + return new DefaultLinkedHashIntToRefEntry<>(next, key, value, hash); + } + + @Nullable + @Override + protected DefaultLinkedHashIntToRefEntry[] allocate(int length) { + //noinspection unchecked + return new DefaultLinkedHashIntToRefEntry[length]; + } + + @Override + public IntToRefDictionary toReadOnly() { + @Nullable DefaultLinkedHashIntToRefEntry[] copied = Arrays.copyOf(entries, entries.length); + return new ImmutableHashBasedIntToRefDictionary<>(copied, size); + } +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/DefaultMutableHashBasedLongToRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/DefaultMutableHashBasedLongToRefDictionary.java new file mode 100644 index 00000000..68818fc9 --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/DefaultMutableHashBasedLongToRefDictionary.java @@ -0,0 +1,78 @@ +package javasabr.rlib.collections.dictionary.impl; + +import java.util.Arrays; +import javasabr.rlib.collections.dictionary.LongToRefDictionary; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.experimental.Accessors; +import lombok.experimental.FieldDefaults; +import org.jspecify.annotations.Nullable; + +@Getter +@Accessors(fluent = true) +@FieldDefaults(level = AccessLevel.PROTECTED) +public class DefaultMutableHashBasedLongToRefDictionary extends + AbstractMutableHashBasedLongToRefDictionary> { + + @Nullable DefaultLinkedHashLongToRefEntry[] entries; + int size; + int threshold; + + public DefaultMutableHashBasedLongToRefDictionary() { + this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR); + } + + public DefaultMutableHashBasedLongToRefDictionary(int initCapacity, float loadFactor) { + super(loadFactor); + //noinspection unchecked + this.entries = new DefaultLinkedHashLongToRefEntry[initCapacity]; + this.threshold = (int) (initCapacity * loadFactor); + } + + @Override + public boolean isEmpty() { + return size < 1; + } + + @Override + protected int incrementSize() { + return size++; + } + + @Override + protected int decrementSize() { + return size--; + } + + @Override + protected void threshold(int threshold) { + this.threshold = threshold; + } + + @Override + protected void entries(@Nullable DefaultLinkedHashLongToRefEntry[] entries) { + this.entries = entries; + } + + @Override + protected DefaultLinkedHashLongToRefEntry allocate( + int hash, + long key, + @Nullable V value, + @Nullable DefaultLinkedHashLongToRefEntry next) { + return new DefaultLinkedHashLongToRefEntry<>(next, key, value, hash); + } + + @Nullable + @Override + protected DefaultLinkedHashLongToRefEntry[] allocate(int length) { + //noinspection unchecked + return new DefaultLinkedHashLongToRefEntry[length]; + } + + @Override + public LongToRefDictionary toReadOnly() { + @Nullable DefaultLinkedHashLongToRefEntry[] copied = Arrays.copyOf(entries, entries.length); + return new ImmutableHashBasedLongToRefDictionary<>(copied, size); + } +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/DefaultMutableHashBasedRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/DefaultMutableHashBasedRefToRefDictionary.java similarity index 76% rename from rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/DefaultMutableHashBasedRefDictionary.java rename to rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/DefaultMutableHashBasedRefToRefDictionary.java index 974c9357..3429704e 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/DefaultMutableHashBasedRefDictionary.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/DefaultMutableHashBasedRefToRefDictionary.java @@ -1,7 +1,7 @@ package javasabr.rlib.collections.dictionary.impl; import java.util.Arrays; -import javasabr.rlib.collections.dictionary.RefDictionary; +import javasabr.rlib.collections.dictionary.RefToRefDictionary; import lombok.AccessLevel; import lombok.Getter; import lombok.experimental.Accessors; @@ -11,18 +11,18 @@ @Getter @Accessors(fluent = true) @FieldDefaults(level = AccessLevel.PROTECTED) -public class DefaultMutableHashBasedRefDictionary extends - AbstractMutableHashBasedRefDictionary> { +public class DefaultMutableHashBasedRefToRefDictionary extends + AbstractMutableHashBasedRefToRefDictionary> { @Nullable DefaultLinkedHashEntry[] entries; int size; int threshold; - public DefaultMutableHashBasedRefDictionary() { + public DefaultMutableHashBasedRefToRefDictionary() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR); } - public DefaultMutableHashBasedRefDictionary(int initCapacity, float loadFactor) { + public DefaultMutableHashBasedRefToRefDictionary(int initCapacity, float loadFactor) { super(loadFactor); //noinspection unchecked this.entries = new DefaultLinkedHashEntry[initCapacity]; @@ -71,8 +71,8 @@ protected DefaultLinkedHashEntry[] allocate(int length) { } @Override - public RefDictionary toReadOnly() { + public RefToRefDictionary toReadOnly() { @Nullable DefaultLinkedHashEntry[] copied = Arrays.copyOf(entries, entries.length); - return new ImmutableHashBasedRefDictionary<>(copied, size); + return new ImmutableHashBasedRefToRefDictionary<>(copied, size); } } diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/ImmutableHashBasedIntToRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/ImmutableHashBasedIntToRefDictionary.java new file mode 100644 index 00000000..fa31ad1e --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/ImmutableHashBasedIntToRefDictionary.java @@ -0,0 +1,34 @@ +package javasabr.rlib.collections.dictionary.impl; + +import javasabr.rlib.collections.dictionary.IntToRefDictionary; +import javasabr.rlib.collections.dictionary.LinkedHashIntToRefEntry; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.experimental.Accessors; +import lombok.experimental.FieldDefaults; +import org.jspecify.annotations.Nullable; + +@Getter +@Accessors(fluent = true) +@RequiredArgsConstructor +@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true) +public class ImmutableHashBasedIntToRefDictionary> + extends AbstractHashBasedIntToRefDictionary { + + private static final IntToRefDictionary EMPTY = + new ImmutableHashBasedIntToRefDictionary<>(new DefaultLinkedHashIntToRefEntry[0], 0); + + public static IntToRefDictionary empty() { + //noinspection unchecked + return (IntToRefDictionary) EMPTY; + } + + @Nullable E[] entries; + int size; + + @Override + public boolean isEmpty() { + return size < 1; + } +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/ImmutableHashBasedLongToRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/ImmutableHashBasedLongToRefDictionary.java new file mode 100644 index 00000000..00feb16b --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/ImmutableHashBasedLongToRefDictionary.java @@ -0,0 +1,34 @@ +package javasabr.rlib.collections.dictionary.impl; + +import javasabr.rlib.collections.dictionary.LinkedHashLongToRefEntry; +import javasabr.rlib.collections.dictionary.LongToRefDictionary; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.experimental.Accessors; +import lombok.experimental.FieldDefaults; +import org.jspecify.annotations.Nullable; + +@Getter +@Accessors(fluent = true) +@RequiredArgsConstructor +@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true) +public class ImmutableHashBasedLongToRefDictionary> + extends AbstractHashBasedLongToRefDictionary { + + private static final LongToRefDictionary EMPTY = + new ImmutableHashBasedLongToRefDictionary<>(new DefaultLinkedHashLongToRefEntry[0], 0); + + public static LongToRefDictionary empty() { + //noinspection unchecked + return (LongToRefDictionary) EMPTY; + } + + @Nullable E[] entries; + int size; + + @Override + public boolean isEmpty() { + return size < 1; + } +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/ImmutableHashBasedRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/ImmutableHashBasedRefToRefDictionary.java similarity index 56% rename from rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/ImmutableHashBasedRefDictionary.java rename to rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/ImmutableHashBasedRefToRefDictionary.java index 43a6de7c..293365c0 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/ImmutableHashBasedRefDictionary.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/ImmutableHashBasedRefToRefDictionary.java @@ -1,7 +1,7 @@ package javasabr.rlib.collections.dictionary.impl; import javasabr.rlib.collections.dictionary.LinkedHashEntry; -import javasabr.rlib.collections.dictionary.RefDictionary; +import javasabr.rlib.collections.dictionary.RefToRefDictionary; import lombok.AccessLevel; import lombok.Getter; import lombok.RequiredArgsConstructor; @@ -13,15 +13,15 @@ @Accessors(fluent = true) @RequiredArgsConstructor @FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true) -public class ImmutableHashBasedRefDictionary> - extends AbstractHashBasedRefDictionary { +public class ImmutableHashBasedRefToRefDictionary> + extends AbstractHashBasedRefToRefDictionary { - private static final RefDictionary EMPTY = - new ImmutableHashBasedRefDictionary<>(new DefaultLinkedHashEntry[0], 0); + private static final RefToRefDictionary EMPTY = + new ImmutableHashBasedRefToRefDictionary<>(new DefaultLinkedHashEntry[0], 0); - public static RefDictionary empty() { + public static RefToRefDictionary empty() { //noinspection unchecked - return (RefDictionary) EMPTY; + return (RefToRefDictionary) EMPTY; } @Nullable E[] entries; diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/LinkedEntryIterator.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/LinkedRefEntryIterator.java similarity index 79% rename from rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/LinkedEntryIterator.java rename to rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/LinkedRefEntryIterator.java index fa3af0cd..874136ee 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/LinkedEntryIterator.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/LinkedRefEntryIterator.java @@ -2,12 +2,13 @@ import java.util.Iterator; import javasabr.rlib.collections.dictionary.LinkedEntry; +import javasabr.rlib.collections.dictionary.RefEntry; import lombok.AccessLevel; import lombok.experimental.FieldDefaults; import org.jspecify.annotations.Nullable; @FieldDefaults(level = AccessLevel.PRIVATE) -public class LinkedEntryIterator> implements Iterator<@Nullable V> { +public class LinkedRefEntryIterator & RefEntry> implements Iterator<@Nullable V> { final @Nullable E[] entries; @@ -16,7 +17,7 @@ public class LinkedEntryIterator> implement int index; - public LinkedEntryIterator(@Nullable E[] entries) { + public LinkedRefEntryIterator(@Nullable E[] entries) { this.entries = entries; findNext(); } diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/SimpleIntToRefEntry.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/SimpleIntToRefEntry.java new file mode 100644 index 00000000..db290d9c --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/SimpleIntToRefEntry.java @@ -0,0 +1,18 @@ +package javasabr.rlib.collections.dictionary.impl; + +import javasabr.rlib.collections.dictionary.IntToRefEntry; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.experimental.Accessors; +import lombok.experimental.FieldDefaults; +import org.jspecify.annotations.Nullable; + +@Data +@AllArgsConstructor +@Accessors(fluent = true, chain = false) +@FieldDefaults(level = AccessLevel.PRIVATE) +public class SimpleIntToRefEntry implements IntToRefEntry { + int key; + @Nullable V value; +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/SimpleLongToRefEntry.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/SimpleLongToRefEntry.java new file mode 100644 index 00000000..687977e5 --- /dev/null +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/SimpleLongToRefEntry.java @@ -0,0 +1,18 @@ +package javasabr.rlib.collections.dictionary.impl; + +import javasabr.rlib.collections.dictionary.LongToRefEntry; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.experimental.Accessors; +import lombok.experimental.FieldDefaults; +import org.jspecify.annotations.Nullable; + +@Data +@AllArgsConstructor +@Accessors(fluent = true, chain = false) +@FieldDefaults(level = AccessLevel.PRIVATE) +public class SimpleLongToRefEntry implements LongToRefEntry { + long key; + @Nullable V value; +} diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/SimpleEntry.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/SimpleRefToRefEntry.java similarity index 75% rename from rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/SimpleEntry.java rename to rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/SimpleRefToRefEntry.java index 61d73e98..f2f15be1 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/SimpleEntry.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/SimpleRefToRefEntry.java @@ -1,6 +1,6 @@ package javasabr.rlib.collections.dictionary.impl; -import javasabr.rlib.collections.dictionary.Entry; +import javasabr.rlib.collections.dictionary.RefToRefEntry; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Data; @@ -12,7 +12,7 @@ @AllArgsConstructor @Accessors(fluent = true, chain = false) @FieldDefaults(level = AccessLevel.PRIVATE) -public class SimpleEntry implements Entry { +public class SimpleRefToRefEntry implements RefToRefEntry { K key; @Nullable V value; } diff --git a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/StampedLockBasedHashBasedRefDictionary.java b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/StampedLockBasedHashBasedRefToRefDictionary.java similarity index 77% rename from rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/StampedLockBasedHashBasedRefDictionary.java rename to rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/StampedLockBasedHashBasedRefToRefDictionary.java index b4eb0485..084ec0b3 100644 --- a/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/StampedLockBasedHashBasedRefDictionary.java +++ b/rlib-collections/src/main/java/javasabr/rlib/collections/dictionary/impl/StampedLockBasedHashBasedRefToRefDictionary.java @@ -5,15 +5,16 @@ import lombok.experimental.FieldDefaults; @FieldDefaults(level = AccessLevel.PROTECTED, makeFinal = true) -public class StampedLockBasedHashBasedRefDictionary extends AbstractLockableHashBasedRefDictionary { +public class StampedLockBasedHashBasedRefToRefDictionary extends + AbstractLockableHashBasedRefToRefDictionary { StampedLock stampedLock; - public StampedLockBasedHashBasedRefDictionary() { + public StampedLockBasedHashBasedRefToRefDictionary() { this.stampedLock = new StampedLock(); } - public StampedLockBasedHashBasedRefDictionary(int initCapacity, float loadFactor) { + public StampedLockBasedHashBasedRefToRefDictionary(int initCapacity, float loadFactor) { super(initCapacity, loadFactor); this.stampedLock = new StampedLock(); } diff --git a/rlib-collections/src/test/java/javasabr/rlib/collections/array/ArrayTest.java b/rlib-collections/src/test/java/javasabr/rlib/collections/array/ArrayTest.java index 533f06bf..90fdbc2f 100644 --- a/rlib-collections/src/test/java/javasabr/rlib/collections/array/ArrayTest.java +++ b/rlib-collections/src/test/java/javasabr/rlib/collections/array/ArrayTest.java @@ -1,7 +1,11 @@ package javasabr.rlib.collections.array; +import java.util.stream.Stream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** * @author JavaSaBr @@ -37,12 +41,36 @@ void arrayOfTest() { Assertions.assertFalse(array.contains("test")); } - @Test - void toArrayTest() { + @ParameterizedTest + @MethodSource("generateArrays") + void shouldCorrectlyTakeValues(Array array) { - // when: - Array array = Array.of("First", "Second", "Third", " "); + // then: + Assertions.assertEquals(4, array.size()); + Assertions.assertEquals("First", array.get(0)); + Assertions.assertEquals("Second", array.get(1)); + Assertions.assertEquals("Third", array.get(2)); + Assertions.assertEquals(" ", array.get(3)); + Assertions.assertEquals("First", array.first()); + Assertions.assertEquals(" ", array.last()); + + // then: + Assertions.assertArrayEquals( + new String[]{ + "First", + "Second", + "Third", + " " + }, array.stream().toArray()); + + // then: + Assertions.assertTrue(array.contains("Second")); + Assertions.assertFalse(array.contains("test")); + } + @ParameterizedTest + @MethodSource("generateArrays") + void shouldCorrectlyTransformToNativeArray(Array array) { // then: Assertions.assertArrayEquals( new String[]{ @@ -66,4 +94,19 @@ void toArrayTest() { " " }, array.toArray(String.class)); } + + private static Stream generateArrays() { + Array array = Array.of("First", "Second", "Third", " "); + MutableArray mutableArray = ArrayFactory.mutableArray(String.class); + mutableArray.addAll(array); + MutableArray copyOnModifyArray = ArrayFactory.copyOnModifyArray(String.class); + copyOnModifyArray.addAll(array); + LockableArray stampedLockBasedArray = ArrayFactory.stampedLockBasedArray(String.class); + stampedLockBasedArray.addAll(array); + return Stream.of( + Arguments.of(array), + Arguments.of(mutableArray), + Arguments.of(copyOnModifyArray), + Arguments.of(stampedLockBasedArray)); + } } diff --git a/rlib-collections/src/test/java/javasabr/rlib/collections/array/MutableRefToRefDictionaryTest.java b/rlib-collections/src/test/java/javasabr/rlib/collections/array/MutableRefToRefDictionaryTest.java new file mode 100644 index 00000000..26f237c3 --- /dev/null +++ b/rlib-collections/src/test/java/javasabr/rlib/collections/array/MutableRefToRefDictionaryTest.java @@ -0,0 +1,111 @@ +package javasabr.rlib.collections.array; + +import static javasabr.rlib.collections.dictionary.RefToRefDictionary.entry; + +import java.util.stream.Stream; +import javasabr.rlib.collections.dictionary.DictionaryFactory; +import javasabr.rlib.collections.dictionary.MutableRefToRefDictionary; +import javasabr.rlib.collections.dictionary.RefToRefDictionary; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class MutableRefToRefDictionaryTest { + + @ParameterizedTest + @MethodSource("generateDictionaries") + void shouldPutNewPairs(MutableRefToRefDictionary dictionary) { + // when: + dictionary.put("key1", "val1"); + dictionary.put("key4", "val4"); + dictionary.put("key7", "val7"); + dictionary.put("key55", "val55"); + + // then: + Assertions.assertEquals("val1", dictionary.get("key1")); + Assertions.assertEquals("val4", dictionary.get("key4")); + Assertions.assertEquals("val55", dictionary.get("key55")); + Assertions.assertTrue(dictionary.containsKey("key1")); + Assertions.assertTrue(dictionary.containsKey("key4")); + Assertions.assertTrue(dictionary.containsKey("key55")); + Assertions.assertNull(dictionary.get("key10")); + Assertions.assertEquals(4, dictionary.size()); + } + + @ParameterizedTest + @MethodSource("generateDictionaries") + void shouldRemoveByKeys(MutableRefToRefDictionary dictionary) { + // given: + dictionary.put("key1", "val1"); + dictionary.put("key4", "val4"); + dictionary.put("key7", "val7"); + dictionary.put("key55", "val55"); + + // when: + String removed1 = dictionary.remove("key1"); + String removed2 = dictionary.remove("key55"); + + // then: + Assertions.assertEquals("val1", removed1); + Assertions.assertEquals("val55", removed2); + Assertions.assertEquals("val4", dictionary.get("key4")); + Assertions.assertEquals("val7", dictionary.get("key7")); + Assertions.assertNull(dictionary.get("key1")); + Assertions.assertNull(dictionary.get("key55")); + Assertions.assertFalse(dictionary.containsKey("key1")); + Assertions.assertFalse(dictionary.containsKey("key55")); + Assertions.assertEquals(2, dictionary.size()); + } + + @ParameterizedTest + @MethodSource("generateDictionaries") + void shouldCorrectlyComputeOnGet(MutableRefToRefDictionary dictionary) { + // when: + var computed1 = dictionary.getOrCompute("key1", () -> "val1"); + var computed2 = dictionary.getOrCompute("key4", key -> "val4"); + var computed3 = dictionary.getOrCompute("key10", 5, arg1 -> "val10"); + + // then: + Assertions.assertEquals("val1", computed1); + Assertions.assertEquals("val4", computed2); + Assertions.assertEquals("val10", computed3); + Assertions.assertEquals("val1", dictionary.get("key1")); + Assertions.assertEquals("val4", dictionary.get("key4")); + Assertions.assertEquals("val10", dictionary.get("key10")); + Assertions.assertTrue(dictionary.containsKey("key1")); + Assertions.assertTrue(dictionary.containsKey("key4")); + Assertions.assertTrue(dictionary.containsKey("key10")); + Assertions.assertEquals(3, dictionary.size()); + } + + @ParameterizedTest + @MethodSource("generateDictionaries") + void shouldAppendDictionary(MutableRefToRefDictionary dictionary) { + // given: + RefToRefDictionary source = RefToRefDictionary.ofEntries( + entry("key1", "val1"), + entry("key2", "val2"), + entry("key3", "val3"), + entry("key4", "val4"), + entry("key5", "val5")); + + // when: + dictionary.append(source); + + // then: + Assertions.assertEquals("val1", dictionary.get("key1")); + Assertions.assertEquals("val4", dictionary.get("key4")); + Assertions.assertEquals("val5", dictionary.get("key5")); + Assertions.assertTrue(dictionary.containsKey("key3")); + Assertions.assertFalse(dictionary.containsKey("key55")); + Assertions.assertNull(dictionary.get("key10")); + Assertions.assertEquals(5, dictionary.size()); + } + + private static Stream generateDictionaries() { + return Stream.of( + Arguments.of(DictionaryFactory.mutableRefToRefDictionary()), + Arguments.of(DictionaryFactory.stampedLockBasedRefToRefDictionary())); + } +} diff --git a/rlib-collections/src/test/java/javasabr/rlib/collections/array/RefToRefDictionaryTest.java b/rlib-collections/src/test/java/javasabr/rlib/collections/array/RefToRefDictionaryTest.java new file mode 100644 index 00000000..1466a4cf --- /dev/null +++ b/rlib-collections/src/test/java/javasabr/rlib/collections/array/RefToRefDictionaryTest.java @@ -0,0 +1,144 @@ +package javasabr.rlib.collections.array; + +import static javasabr.rlib.collections.dictionary.RefToRefDictionary.entry; + +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Stream; +import javasabr.rlib.collections.dictionary.DictionaryFactory; +import javasabr.rlib.collections.dictionary.RefToRefDictionary; +import javasabr.rlib.common.tuple.Tuple; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class RefToRefDictionaryTest { + + @ParameterizedTest + @MethodSource("generateDictionaries") + void shouldFindValuesByKeys(RefToRefDictionary dictionary) { + // then: + Assertions.assertEquals("val1", dictionary.get("key1")); + Assertions.assertEquals("val3", dictionary.get("key3")); + Assertions.assertEquals("val4", dictionary.get("key4")); + Assertions.assertNull(dictionary.get("key10")); + } + + @ParameterizedTest + @MethodSource("generateDictionaries") + void shouldCheckContainsKeys(RefToRefDictionary dictionary) { + // then: + Assertions.assertTrue(dictionary.containsKey("key1")); + Assertions.assertTrue(dictionary.containsKey("key2")); + Assertions.assertTrue(dictionary.containsKey("key5")); + Assertions.assertFalse(dictionary.containsKey("key10")); + } + + @ParameterizedTest + @MethodSource("generateDictionaries") + void shouldCheckContainsValues(RefToRefDictionary dictionary) { + // then: + Assertions.assertTrue(dictionary.containsValue("val1")); + Assertions.assertTrue(dictionary.containsValue("val3")); + Assertions.assertTrue(dictionary.containsValue("val4")); + Assertions.assertFalse(dictionary.containsValue("val10")); + } + + @ParameterizedTest + @MethodSource("generateDictionaries") + void shouldHaveExpectedKeys(RefToRefDictionary dictionary) { + + // given: + var expectedArray = Array.typed(String.class, "key4", "key3", "key5", "key2", "key1"); + var expectedSet = Set.copyOf(expectedArray.toList()); + + // when: + Array keys = dictionary.keys(String.class); + + // then: + Assertions.assertEquals(expectedArray, keys); + + // when: + Array keys2 = dictionary.keys(MutableArray.ofType(String.class)); + + // then: + Assertions.assertEquals(expectedArray, keys2); + + // when: + Set keys3 = dictionary.keys(new HashSet<>()); + + // then: + Assertions.assertEquals(expectedSet, keys3); + } + + @ParameterizedTest + @MethodSource("generateDictionaries") + void shouldHaveExpectedValues(RefToRefDictionary dictionary) { + + // given: + var expectedArray = Array.typed(String.class, "val4", "val3", "val5", "val2", "val1"); + var expectedSet = Set.copyOf(expectedArray.toList()); + + // when: + Array values = dictionary.values(String.class); + + // then: + Assertions.assertEquals(expectedArray, values); + + // when: + Array values2 = dictionary.values(MutableArray.ofType(String.class)); + + // then: + Assertions.assertEquals(expectedArray, values2); + + // when: + Set keys3 = dictionary.values(new HashSet<>()); + + // then: + Assertions.assertEquals(expectedSet, keys3); + } + + @ParameterizedTest + @MethodSource("generateDictionaries") + void shouldHaveExpectedResultFromForEach(RefToRefDictionary dictionary) { + + // given: + var expectedArray = Array.typed(String.class, "val4", "val3", "val5", "val2", "val1"); + var expectedPairs = Array.typed(Tuple.class, + new Tuple<>("key4", "val4"), + new Tuple<>("key3", "val3"), + new Tuple<>("key5", "val5"), + new Tuple<>("key2", "val2"), + new Tuple<>("key1", "val1")); + + // when: + MutableArray values = MutableArray.ofType(String.class); + dictionary.forEach(values::add); + + // then: + Assertions.assertEquals(expectedArray, values); + + // when: + MutableArray pairs = MutableArray.ofType(Tuple.class); + dictionary.forEach((key, value) -> pairs.add(new Tuple<>(key, value))); + + // then: + Assertions.assertEquals(expectedPairs, pairs); + } + + private static Stream generateDictionaries() { + + RefToRefDictionary source = RefToRefDictionary.ofEntries( + entry("key1", "val1"), + entry("key2", "val2"), + entry("key3", "val3"), + entry("key4", "val4"), + entry("key5", "val5")); + + return Stream.of( + Arguments.of(source), + Arguments.of(DictionaryFactory.mutableRefToRefDictionary().append(source)), + Arguments.of(DictionaryFactory.stampedLockBasedRefToRefDictionary().append(source))); + } +} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/Copyable.java b/rlib-common/src/main/java/javasabr/rlib/common/Copyable.java new file mode 100644 index 00000000..880af8e0 --- /dev/null +++ b/rlib-common/src/main/java/javasabr/rlib/common/Copyable.java @@ -0,0 +1,5 @@ +package javasabr.rlib.common; + +public interface Copyable { + T copy(); +} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ThreadSafe.java b/rlib-common/src/main/java/javasabr/rlib/common/ThreadSafe.java similarity index 72% rename from rlib-common/src/main/java/javasabr/rlib/common/util/ThreadSafe.java rename to rlib-common/src/main/java/javasabr/rlib/common/ThreadSafe.java index 9227eaee..7d60d159 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ThreadSafe.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/ThreadSafe.java @@ -1,4 +1,4 @@ -package javasabr.rlib.common.util; +package javasabr.rlib.common; /** * Interface to mark a class that it's a thread safe. diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/BiIntPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/BiIntPredicate.java deleted file mode 100644 index a2428be8..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/BiIntPredicate.java +++ /dev/null @@ -1,10 +0,0 @@ -package javasabr.rlib.common.function; - -/** - * @author JavaSaBr - */ -@FunctionalInterface -public interface BiIntPredicate { - - boolean test(int first, int second); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/BiObjectIntConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/BiObjectIntConsumer.java deleted file mode 100644 index f8c16f27..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/BiObjectIntConsumer.java +++ /dev/null @@ -1,23 +0,0 @@ -package javasabr.rlib.common.function; - -import org.jspecify.annotations.Nullable; - -/** - * The function. - * - * @param the type parameter - * @param the type parameter - * @author JavaSaBr - */ -@FunctionalInterface -public interface BiObjectIntConsumer { - - /** - * Accept. - * - * @param first the first - * @param second the second - * @param third the third - */ - void accept(@Nullable F first, @Nullable S second, int third); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/BooleanFloatConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/BooleanFloatConsumer.java deleted file mode 100644 index 7506b866..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/BooleanFloatConsumer.java +++ /dev/null @@ -1,18 +0,0 @@ -package javasabr.rlib.common.function; - -/** - * The function. - * - * @author JavaSaBr - */ -@FunctionalInterface -public interface BooleanFloatConsumer { - - /** - * Accept. - * - * @param first the first - * @param second the second - */ - void accept(boolean first, float second); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ByteFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ByteFunction.java deleted file mode 100644 index f55dd45f..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ByteFunction.java +++ /dev/null @@ -1,10 +0,0 @@ -package javasabr.rlib.common.function; - -/** - * @author JavaSaBr - */ -@FunctionalInterface -public interface ByteFunction { - - R apply(byte value); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/FiveObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/FiveObjectConsumer.java deleted file mode 100644 index 10d7b7da..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/FiveObjectConsumer.java +++ /dev/null @@ -1,29 +0,0 @@ -package javasabr.rlib.common.function; - -import org.jspecify.annotations.NullUnmarked; - -/** - * The consumer with 5 arguments. - * - * @param the type parameter - * @param the type parameter - * @param the type parameter - * @param the type parameter - * @param the type parameter - * @author JavaSaBr - */ -@NullUnmarked -@FunctionalInterface -public interface FiveObjectConsumer { - - /** - * Accept. - * - * @param first the first - * @param second the second - * @param third the third - * @param fourth the fourth - * @param five the five - */ - void accept(F first, S second, T third, FO fourth, FI five); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/FloatFloatConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/FloatFloatConsumer.java deleted file mode 100644 index ed44e770..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/FloatFloatConsumer.java +++ /dev/null @@ -1,18 +0,0 @@ -package javasabr.rlib.common.function; - -/** - * The function. - * - * @author JavaSaBr - */ -@FunctionalInterface -public interface FloatFloatConsumer { - - /** - * Accept. - * - * @param first the first - * @param second the second - */ - void accept(float first, float second); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/FloatObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/FloatObjectConsumer.java deleted file mode 100644 index 0370d84f..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/FloatObjectConsumer.java +++ /dev/null @@ -1,21 +0,0 @@ -package javasabr.rlib.common.function; - -import org.jspecify.annotations.Nullable; - -/** - * The function to consume float and object. - * - * @param the consumed object's type. - * @author JavaSaBr - */ -@FunctionalInterface -public interface FloatObjectConsumer { - - /** - * Accept the two parameters. - * - * @param first the first. - * @param second the second. - */ - void accept(float first, @Nullable T second); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/FourObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/FourObjectConsumer.java deleted file mode 100644 index eba827b6..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/FourObjectConsumer.java +++ /dev/null @@ -1,27 +0,0 @@ -package javasabr.rlib.common.function; - -import org.jspecify.annotations.NullUnmarked; - -/** - * The consumer with 4 arguments. - * - * @param the type parameter - * @param the type parameter - * @param the type parameter - * @param the type parameter - * @author JavaSaBr - */ -@NullUnmarked -@FunctionalInterface -public interface FourObjectConsumer { - - /** - * Accept. - * - * @param first the first - * @param second the second - * @param third the third - * @param fourth the fourth - */ - void accept(F first, S second, T third, FO fourth); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/LongObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/LongObjectConsumer.java deleted file mode 100644 index 7f57c686..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/LongObjectConsumer.java +++ /dev/null @@ -1,21 +0,0 @@ -package javasabr.rlib.common.function; - -import org.jspecify.annotations.Nullable; - -/** - * The function. - * - * @param the type parameter - * @author JavaSaBr - */ -@FunctionalInterface -public interface LongObjectConsumer { - - /** - * Accept. - * - * @param first the first - * @param second the second - */ - void accept(long first, @Nullable T second); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiFunction.java deleted file mode 100644 index d4fab15a..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiFunction.java +++ /dev/null @@ -1,10 +0,0 @@ -package javasabr.rlib.common.function; - -import java.util.function.BiFunction; - -@FunctionalInterface -public interface NotNullBiFunction extends BiFunction { - - @Override - R apply(T first, U second); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiPredicate.java deleted file mode 100644 index 027fca77..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullBiPredicate.java +++ /dev/null @@ -1,10 +0,0 @@ -package javasabr.rlib.common.function; - -import java.util.function.BiPredicate; - -@FunctionalInterface -public interface NotNullBiPredicate extends BiPredicate { - - @Override - boolean test(T first, U second); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFloatBiObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFloatBiObjectConsumer.java deleted file mode 100644 index 94072b5a..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFloatBiObjectConsumer.java +++ /dev/null @@ -1,11 +0,0 @@ -package javasabr.rlib.common.function; - -/** - * @author JavaSaBr - */ -@FunctionalInterface -public interface NotNullFloatBiObjectConsumer extends FloatBiObjectConsumer { - - @Override - void accept(float first, S second, T third); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFunction.java deleted file mode 100644 index 4783928e..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFunction.java +++ /dev/null @@ -1,10 +0,0 @@ -package javasabr.rlib.common.function; - -import java.util.function.Function; - -@FunctionalInterface -public interface NotNullFunction extends Function { - - @Override - R apply(T object); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFunctionInt.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFunctionInt.java deleted file mode 100644 index 50b9a7d0..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullFunctionInt.java +++ /dev/null @@ -1,7 +0,0 @@ -package javasabr.rlib.common.function; - -@FunctionalInterface -public interface NotNullFunctionInt extends FunctionInt { - - int apply(T object); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullIntBiObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullIntBiObjectConsumer.java deleted file mode 100644 index 055b85ac..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullIntBiObjectConsumer.java +++ /dev/null @@ -1,11 +0,0 @@ -package javasabr.rlib.common.function; - -/** - * @author JavaSaBr - */ -@FunctionalInterface -public interface NotNullIntBiObjectConsumer extends IntBiObjectConsumer { - - @Override - void accept(int first, S second, T third); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullIntObjectPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullIntObjectPredicate.java deleted file mode 100644 index da03fb4c..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullIntObjectPredicate.java +++ /dev/null @@ -1,10 +0,0 @@ -package javasabr.rlib.common.function; - -/** - * @author JavaSaBr - */ -@FunctionalInterface -public interface NotNullIntObjectPredicate extends IntObjectPredicate { - - boolean test(int first, T second); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullLongBiObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullLongBiObjectConsumer.java deleted file mode 100644 index 59070ea8..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullLongBiObjectConsumer.java +++ /dev/null @@ -1,11 +0,0 @@ -package javasabr.rlib.common.function; - -/** - * @author JavaSaBr - */ -@FunctionalInterface -public interface NotNullLongBiObjectConsumer extends LongBiObjectConsumer { - - @Override - void accept(long first, S second, T third); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullLongObjectPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullLongObjectPredicate.java deleted file mode 100644 index 6d0e778c..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullLongObjectPredicate.java +++ /dev/null @@ -1,10 +0,0 @@ -package javasabr.rlib.common.function; - -/** - * @author JavaSaBr - */ -@FunctionalInterface -public interface NotNullLongObjectPredicate extends LongObjectPredicate { - - boolean test(long first, T second); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableBiFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableBiFunction.java deleted file mode 100644 index 2597fb0d..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableBiFunction.java +++ /dev/null @@ -1,11 +0,0 @@ -package javasabr.rlib.common.function; - -import java.util.function.BiFunction; -import org.jspecify.annotations.Nullable; - -@FunctionalInterface -public interface NotNullNullableBiFunction extends BiFunction { - - @Override - @Nullable R apply(T first, U second); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableFunction.java deleted file mode 100644 index 070fdf9a..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableFunction.java +++ /dev/null @@ -1,12 +0,0 @@ -package javasabr.rlib.common.function; - -import java.util.function.Function; -import org.jspecify.annotations.Nullable; - -@FunctionalInterface -public interface NotNullNullableFunction extends Function { - - @Override - @Nullable - R apply(T object); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableTripleFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableTripleFunction.java deleted file mode 100644 index e762720e..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullNullableTripleFunction.java +++ /dev/null @@ -1,10 +0,0 @@ -package javasabr.rlib.common.function; - -import org.jspecify.annotations.Nullable; - -@FunctionalInterface -public interface NotNullNullableTripleFunction extends TripleFunction { - - @Override - @Nullable R apply(F first, S second, T third); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullObjectIntPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullObjectIntPredicate.java deleted file mode 100644 index eacd8586..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullObjectIntPredicate.java +++ /dev/null @@ -1,11 +0,0 @@ -package javasabr.rlib.common.function; - -/** - * @author JavaSaBr - */ -@FunctionalInterface -public interface NotNullObjectIntPredicate extends ObjectIntPredicate { - - @Override - boolean test(T first, int second); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullObjectLongPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullObjectLongPredicate.java deleted file mode 100644 index 2629b863..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullObjectLongPredicate.java +++ /dev/null @@ -1,8 +0,0 @@ -package javasabr.rlib.common.function; - -@FunctionalInterface -public interface NotNullObjectLongPredicate extends ObjectLongPredicate { - - @Override - boolean test(T first, long second); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullPredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullPredicate.java deleted file mode 100644 index ced6424e..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullPredicate.java +++ /dev/null @@ -1,10 +0,0 @@ -package javasabr.rlib.common.function; - -import java.util.function.Predicate; - -@FunctionalInterface -public interface NotNullPredicate extends Predicate { - - @Override - boolean test(T object); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSupplier.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSupplier.java deleted file mode 100644 index d9c144a1..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullSupplier.java +++ /dev/null @@ -1,10 +0,0 @@ -package javasabr.rlib.common.function; - -import java.util.function.Supplier; - -@FunctionalInterface -public interface NotNullSupplier extends Supplier { - - @Override - T get(); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullTripleConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullTripleConsumer.java deleted file mode 100644 index 720ec4e1..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullTripleConsumer.java +++ /dev/null @@ -1,11 +0,0 @@ -package javasabr.rlib.common.function; - -/** - * @author JavaSaBr - */ -@FunctionalInterface -public interface NotNullTripleConsumer extends TripleConsumer { - - @Override - void accept(F first, S second, T third); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullTriplePredicate.java b/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullTriplePredicate.java deleted file mode 100644 index 1029aa40..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/NotNullTriplePredicate.java +++ /dev/null @@ -1,10 +0,0 @@ -package javasabr.rlib.common.function; - -/** - * @author JavaSaBr - */ -@FunctionalInterface -public interface NotNullTriplePredicate extends TriplePredicate { - - boolean test(F first, S second, T third); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatConsumer.java deleted file mode 100644 index e69df57c..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatConsumer.java +++ /dev/null @@ -1,21 +0,0 @@ -package javasabr.rlib.common.function; - -import org.jspecify.annotations.Nullable; - -/** - * The function. - * - * @param the type parameter - * @author JavaSaBr - */ -@FunctionalInterface -public interface ObjectFloatConsumer { - - /** - * Apply. - * - * @param first the first - * @param second the second - */ - void apply(@Nullable T first, float second); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatFunction.java deleted file mode 100644 index e6b8c206..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatFunction.java +++ /dev/null @@ -1,23 +0,0 @@ -package javasabr.rlib.common.function; - -import org.jspecify.annotations.Nullable; - -/** - * The function. - * - * @param the type parameter - * @param the type parameter - * @author JavaSaBr - */ -@FunctionalInterface -public interface ObjectFloatFunction { - - /** - * Apply r. - * - * @param first the first - * @param second the second - * @return the r - */ - @Nullable R apply(@Nullable T first, float second); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatObjectConsumer.java deleted file mode 100644 index acff3db3..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectFloatObjectConsumer.java +++ /dev/null @@ -1,23 +0,0 @@ -package javasabr.rlib.common.function; - -import org.jspecify.annotations.Nullable; - -/** - * The consumer with 3 arguments. - * - * @param the type parameter - * @param the type parameter - * @author JavaSaBr - */ -@FunctionalInterface -public interface ObjectFloatObjectConsumer { - - /** - * Accept. - * - * @param first the first - * @param second the second - * @param third the third - */ - void accept(@Nullable F first, float second, @Nullable T third); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntConsumer.java deleted file mode 100644 index 7306b275..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntConsumer.java +++ /dev/null @@ -1,21 +0,0 @@ -package javasabr.rlib.common.function; - -import org.jspecify.annotations.Nullable; - -/** - * The function. - * - * @param the type parameter - * @author JavaSaBr - */ -@FunctionalInterface -public interface ObjectIntConsumer { - - /** - * Accept. - * - * @param first the first - * @param second the second - */ - void accept(@Nullable T first, int second); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntObjectConsumer.java deleted file mode 100644 index c8ddcb46..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntObjectConsumer.java +++ /dev/null @@ -1,23 +0,0 @@ -package javasabr.rlib.common.function; - -import org.jspecify.annotations.Nullable; - -/** - * The function. - * - * @param the type parameter - * @param the type parameter - * @author JavaSaBr - */ -@FunctionalInterface -public interface ObjectIntObjectConsumer { - - /** - * Accept. - * - * @param first the first - * @param second the second - * @param third the third - */ - void accept(@Nullable F first, int second, @Nullable T third); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntObjectFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntObjectFunction.java deleted file mode 100644 index e23cad0c..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectIntObjectFunction.java +++ /dev/null @@ -1,25 +0,0 @@ -package javasabr.rlib.common.function; - -import org.jspecify.annotations.Nullable; - -/** - * The function. - * - * @param the type parameter - * @param the type parameter - * @param the type parameter - * @author JavaSaBr - */ -@FunctionalInterface -public interface ObjectIntObjectFunction { - - /** - * Apply r. - * - * @param first the first - * @param second the second - * @param third the third - * @return the r - */ - @Nullable R apply(@Nullable F first, int second, @Nullable T third); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongConsumer.java deleted file mode 100644 index ba62e39b..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongConsumer.java +++ /dev/null @@ -1,21 +0,0 @@ -package javasabr.rlib.common.function; - -import org.jspecify.annotations.Nullable; - -/** - * The function. - * - * @param the type parameter - * @author JavaSaBr - */ -@FunctionalInterface -public interface ObjectLongConsumer { - - /** - * Accept. - * - * @param first the first - * @param second the second - */ - void accept(@Nullable T first, long second); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongObjectConsumer.java deleted file mode 100644 index 0b90c249..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/ObjectLongObjectConsumer.java +++ /dev/null @@ -1,23 +0,0 @@ -package javasabr.rlib.common.function; - -import org.jspecify.annotations.Nullable; - -/** - * The function. - * - * @param the type parameter - * @param the type parameter - * @author JavaSaBr - */ -@FunctionalInterface -public interface ObjectLongObjectConsumer { - - /** - * Accept. - * - * @param first the first - * @param second the second - * @param third the third - */ - void accept(@Nullable F first, long second, @Nullable T third); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTripleConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTripleConsumer.java deleted file mode 100644 index 9401dd91..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTripleConsumer.java +++ /dev/null @@ -1,26 +0,0 @@ -package javasabr.rlib.common.function; - -import org.jspecify.annotations.NullUnmarked; - -/** - * The function. - * - * @param the type parameter - * @param the type parameter - * @param the type parameter - * @author JavaSaBr - */ -@NullUnmarked -@FunctionalInterface -public interface SafeTripleConsumer { - - /** - * Accept. - * - * @param first the first - * @param second the second - * @param third the third - * @throws Exception the exception - */ - void accept(F first, S second, T third) throws Exception; -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTripleFunction.java b/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTripleFunction.java deleted file mode 100644 index 4ae269ed..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/SafeTripleFunction.java +++ /dev/null @@ -1,28 +0,0 @@ -package javasabr.rlib.common.function; - -import org.jspecify.annotations.NullUnmarked; - -/** - * The function. - * - * @param the type parameter - * @param the type parameter - * @param the type parameter - * @param the type parameter - * @author JavaSaBr - */ -@NullUnmarked -@FunctionalInterface -public interface SafeTripleFunction { - - /** - * Apply r. - * - * @param first the first - * @param second the second - * @param third the third - * @return the r - * @throws Exception the exception - */ - R apply(F first, S second, T third) throws Exception; -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/function/SixObjectConsumer.java b/rlib-common/src/main/java/javasabr/rlib/common/function/SixObjectConsumer.java deleted file mode 100644 index 974ab1e9..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/function/SixObjectConsumer.java +++ /dev/null @@ -1,31 +0,0 @@ -package javasabr.rlib.common.function; - -import org.jspecify.annotations.NullUnmarked; - -/** - * The consumer with 5 arguments. - * - * @param the type parameter - * @param the type parameter - * @param the type parameter - * @param the type parameter - * @param the type parameter - * @param the type parameter - * @author JavaSaBr - */ -@NullUnmarked -@FunctionalInterface -public interface SixObjectConsumer { - - /** - * Accept. - * - * @param first the first - * @param second the second - * @param third the third - * @param fourth the fourth - * @param five the five - * @param six the six - */ - void accept(F first, S second, T third, FO fourth, FI five, SX six); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/graphics/color/ColorRGBA.java b/rlib-common/src/main/java/javasabr/rlib/common/graphics/color/ColorRGBA.java deleted file mode 100644 index bd8cad88..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/graphics/color/ColorRGBA.java +++ /dev/null @@ -1,275 +0,0 @@ -package javasabr.rlib.common.graphics.color; - -import java.io.Serial; -import java.io.Serializable; -import org.jspecify.annotations.NullMarked; - -/** - * THe implementation of a color class. - * - * @author JavaSaBr - */ -@NullMarked -public final class ColorRGBA implements Cloneable, Serializable { - - @Serial - private static final long serialVersionUID = -3342702659372723983L; - - /** - * The red channel. - */ - public float r; - - /** - * The green channel. - */ - public float g; - - /** - * The blue channel. - */ - public float b; - - /** - * The alpha channel. - */ - public float a; - - /** - * Instantiates a new Color rgba. - */ - public ColorRGBA() { - r = g = b = a = 1.0f; - } - - /** - * Instantiates a new Color rgba. - * - * @param rgba the rgba - */ - public ColorRGBA(ColorRGBA rgba) { - this.a = rgba.a; - this.r = rgba.r; - this.g = rgba.g; - this.b = rgba.b; - } - - /** - * Instantiates a new Color rgba. - * - * @param r the r - * @param g the g - * @param b the b - */ - public ColorRGBA(float r, float g, float b) { - this.r = r; - this.g = g; - this.b = b; - this.a = 1F; - } - - /** - * Instantiates a new Color rgba. - * - * @param r the r - * @param g the g - * @param b the b - * @param a the a - */ - public ColorRGBA(float r, float g, float b, float a) { - this.r = r; - this.g = g; - this.b = b; - this.a = a; - } - - /** - * Instantiates a new Color rgba. - * - * @param array the array - */ - public ColorRGBA(float[] array) { - this.r = array[0]; - this.g = array.length > 1 ? array[1] : 1F; - this.b = array.length > 2 ? array[2] : 1F; - this.a = array.length > 3 ? array[3] : 1F; - } - - /** - * As int abgr int. - * - * @return the int - */ - public int asIntABGR() { - return - ((int) (a * 255) & 0xFF) << 24 | - ((int) (b * 255) & 0xFF) << 16 | - ((int) (g * 255) & 0xFF) << 8 | - (int) (r * 255) & 0xFF; - } - - /** - * As int argb int. - * - * @return the int - */ - public int asIntARGB() { - return - ((int) (a * 255) & 0xFF) << 24 | - ((int) (r * 255) & 0xFF) << 16 | - ((int) (g * 255) & 0xFF) << 8 | - (int) (b * 255) & 0xFF; - } - - /** - * As int rgba int. - * - * @return the int - */ - public int asIntRGBA() { - return - ((int) (r * 255) & 0xFF) << 24 | - ((int) (g * 255) & 0xFF) << 16 | - ((int) (b * 255) & 0xFF) << 8 | - (int) (a * 255) & 0xFF; - } - - @Override - public boolean equals(Object o) { - - if (!(o instanceof ColorRGBA comp)) { - return false; - } else if (this == o) { - return true; - } - - if (Float.compare(r, comp.r) != 0) { - return false; - } else if (Float.compare(g, comp.g) != 0) { - return false; - } else if (Float.compare(b, comp.b) != 0) { - return false; - } else { - return Float.compare(a, comp.a) == 0; - } - } - - /** - * From int argb. - * - * @param color the color - */ - public void fromIntARGB(int color) { - a = ((byte) (color >> 24) & 0xFF) / 255f; - r = ((byte) (color >> 16) & 0xFF) / 255f; - g = ((byte) (color >> 8) & 0xFF) / 255f; - b = ((byte) color & 0xFF) / 255f; - } - - /** - * From int rgba. - * - * @param color the color - */ - public void fromIntRGBA(int color) { - r = ((byte) (color >> 24) & 0xFF) / 255f; - g = ((byte) (color >> 16) & 0xFF) / 255f; - b = ((byte) (color >> 8) & 0xFF) / 255f; - a = ((byte) color & 0xFF) / 255f; - } - - /** - * Gets alpha. - * - * @return the alpha channel. - */ - public float getAlpha() { - return a; - } - - /** - * Gets blue. - * - * @return the blue channel. - */ - public float getBlue() { - return b; - } - - /** - * Gets green. - * - * @return the green channel. - */ - public float getGreen() { - return g; - } - - /** - * Gets red. - * - * @return the red channel. - */ - public float getRed() { - return r; - } - - @Override - public int hashCode() { - int hash = 37; - hash += 37 * hash + Float.floatToIntBits(r); - hash += 37 * hash + Float.floatToIntBits(g); - hash += 37 * hash + Float.floatToIntBits(b); - hash += 37 * hash + Float.floatToIntBits(a); - return hash; - } - - /** - * Interpolate. - * - * @param beginColor the begin color - * @param finalColor the final color - * @param changeAmnt the change amnt - */ - public void interpolate(ColorRGBA beginColor, ColorRGBA finalColor, float changeAmnt) { - this.r = (1 - changeAmnt) * beginColor.r + changeAmnt * finalColor.r; - this.g = (1 - changeAmnt) * beginColor.g + changeAmnt * finalColor.g; - this.b = (1 - changeAmnt) * beginColor.b + changeAmnt * finalColor.b; - this.a = (1 - changeAmnt) * beginColor.a + changeAmnt * finalColor.a; - } - - /** - * Interpolate. - * - * @param finalColor the final color - * @param changeAmnt the change amnt - */ - public void interpolate(ColorRGBA finalColor, float changeAmnt) { - this.r = (1 - changeAmnt) * this.r + changeAmnt * finalColor.r; - this.g = (1 - changeAmnt) * this.g + changeAmnt * finalColor.g; - this.b = (1 - changeAmnt) * this.b + changeAmnt * finalColor.b; - this.a = (1 - changeAmnt) * this.a + changeAmnt * finalColor.a; - } - - /** - * Set color rgba. - * - * @param r the r - * @param g the g - * @param b the b - * @param a the a - * @return the color rgba - */ - public ColorRGBA set(float r, float g, float b, float a) { - this.r = r; - this.g = g; - this.b = b; - this.a = a; - return this; - } - - @Override - public String toString() { - return "ColorRGBA{" + "red=" + r + ", green=" + g + ", blue=" + b + ", alpha=" + a + '}'; - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/manager/InitializeManager.java b/rlib-common/src/main/java/javasabr/rlib/common/manager/InitializeManager.java deleted file mode 100644 index 73a97b37..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/manager/InitializeManager.java +++ /dev/null @@ -1,83 +0,0 @@ -package javasabr.rlib.common.manager; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayDeque; -import java.util.Deque; -import java.util.Iterator; -import javasabr.rlib.logger.api.Logger; -import javasabr.rlib.logger.api.LoggerManager; -import org.jspecify.annotations.NullMarked; - -/** - * The manager to initialize singletons in some order. - * - * @author JavaSaBr - */ -@NullMarked -public final class InitializeManager { - - private static final Logger LOGGER = LoggerManager.getLogger(InitializeManager.class); - - private static final String METHOD_NAME = "getInstance"; - - private static final Deque> QUEUE = new ArrayDeque<>(); - - /** - * Initialize. - */ - public synchronized static void initialize() { - - for (Iterator> iterator = QUEUE.iterator(); iterator.hasNext(); ) { - - Class next = iterator.next(); - try { - - Method method = next.getMethod(METHOD_NAME); - Object instance = method.invoke(null); - - if (instance == null) { - LOGGER.warning("no initialize class " + next); - } - - iterator.remove(); - - } catch (InvocationTargetException e) { - LOGGER.warning(e.getTargetException()); - } catch (Throwable e) { - LOGGER.warning(e); - } - } - } - - /** - * Add a class with static method 'getInstance' to initialization queue. - * - * @param cs the class. - */ - public static synchronized void register(Class cs) { - - try { - cs.getMethod(METHOD_NAME); - } catch (NoSuchMethodException e) { - throw new RuntimeException(e); - } - - QUEUE.add(cs); - } - - /** - * Check validity of the class in initialization order. - * - * @param cs the class. - */ - public static synchronized void valid(Class cs) { - if (QUEUE.getFirst() != cs) { - throw new IllegalStateException("The class has invalid initialization position."); - } - } - - private InitializeManager() { - throw new RuntimeException(); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/monitoring/MemoryMonitoring.java b/rlib-common/src/main/java/javasabr/rlib/common/monitoring/MemoryMonitoring.java deleted file mode 100644 index 2d634677..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/monitoring/MemoryMonitoring.java +++ /dev/null @@ -1,241 +0,0 @@ -package javasabr.rlib.common.monitoring; - -import java.lang.management.ManagementFactory; -import java.lang.management.MemoryMXBean; -import java.lang.management.MemoryPoolMXBean; -import java.lang.management.MemoryUsage; -import java.util.List; -import org.jspecify.annotations.Nullable; - -/** - * The class to monitor memory usage. - * - * @author JavaSaBr - */ -public class MemoryMonitoring { - - /** - * The constant MEMORY_POOL_CODE_CACHE. - */ - public static final String MEMORY_POOL_CODE_CACHE = "Code Cache"; - /** - * The constant MEMORY_POOL_COMPRESSED_CLASS_SPACE. - */ - public static final String MEMORY_POOL_COMPRESSED_CLASS_SPACE = "Compressed Class Space"; - /** - * The constant MEMORY_POOL_METASPACE. - */ - public static final String MEMORY_POOL_METASPACE = "Metaspace"; - /** - * The constant MEMORY_POOL_EDEN_SPACE. - */ - public static final String MEMORY_POOL_EDEN_SPACE = "PS Eden Space"; - /** - * The constant MEMORY_POOL_SURVIVOR_SPACE. - */ - public static final String MEMORY_POOL_SURVIVOR_SPACE = "PS Survivor Space"; - /** - * The constant MEMORY_POOL_OLD_GEN. - */ - public static final String MEMORY_POOL_OLD_GEN = "PS Old Gen"; - - /** - * The list of memory pools. - */ - private final List memoryPoolMXBeans; - - /** - * The memory manager. - */ - private final MemoryMXBean memoryMXBean; - - /** - * Instantiates a new Memory monitoring. - */ - public MemoryMonitoring() { - this.memoryMXBean = ManagementFactory.getMemoryMXBean(); - this.memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans(); - } - - /** - * Find a memory pool been by a name. - * - * @param name the name. - * @return the found bean or null. - */ - @Nullable - private MemoryPoolMXBean findMemoryPoolMXBeen(String name) { - return memoryPoolMXBeans - .stream() - .filter(bean -> bean - .getName() - .contains(name)) - .findAny() - .orElse(null); - } - - /** - * Get max heap size. - * - * @return the max heap size. - */ - public long getHeapMaxSize() { - return getHeapMaxSize(memoryMXBean.getHeapMemoryUsage()); - } - - private long getHeapMaxSize(MemoryUsage memoryUsage) { - return memoryUsage.getMax(); - } - - /** - * Get current heap size. - * - * @return the current heap size. - */ - public long getHeapSize() { - return getHeapSize(memoryMXBean.getHeapMemoryUsage()); - } - - private long getHeapSize(MemoryUsage memoryUsage) { - return memoryUsage.getCommitted(); - } - - /** - * Get heap usage percent. - * - * @return the heap usage percent. - */ - public double getHeapUsagePercent() { - return getHeapUsagePercent(memoryMXBean.getHeapMemoryUsage()); - } - - private double getHeapUsagePercent(MemoryUsage memoryUsage) { - return getHeapUsedSize(memoryUsage) / (double) getHeapSize(memoryUsage) * 100; - } - - /** - * Get heap usage size. - * - * @return the heap usage size. - */ - public long getHeapUsedSize() { - return getHeapUsedSize(memoryMXBean.getHeapMemoryUsage()); - } - - private long getHeapUsedSize(MemoryUsage memoryUsage) { - return memoryUsage.getUsed(); - } - - /** - * Get max size of a memory pool. - * - * @param name the name of a memory pool. - * @return the max size. - */ - public long getMemoryPoolMaxSize(String name) { - - MemoryPoolMXBean mxBean = findMemoryPoolMXBeen(name); - if (mxBean == null) { - throw new IllegalArgumentException("unknown memory pool name \"" + name + "\"."); - } - - MemoryUsage usage = mxBean.getUsage(); - return usage.getMax(); - } - - /** - * Get current size a memory pool. - * - * @param name the name of a memory pool. - * @return the current size. - */ - public long getMemoryPoolSize(String name) { - - MemoryPoolMXBean mxBean = findMemoryPoolMXBeen(name); - if (mxBean == null) { - throw new IllegalArgumentException("unknown memory pool name \"" + name + "\"."); - } - - MemoryUsage usage = mxBean.getUsage(); - return usage.getCommitted(); - } - - /** - * Get used size a memory pool. - * - * @param name the name of a memory pool. - * @return the used size. - */ - public long getMemoryPoolUsed(String name) { - - MemoryPoolMXBean mxBean = findMemoryPoolMXBeen(name); - if (mxBean == null) { - throw new IllegalArgumentException("unknown memory pool name \"" + name + "\"."); - } - - MemoryUsage usage = mxBean.getUsage(); - return usage.getUsed(); - } - - @Override - public String toString() { - - MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage(); - - StringBuilder builder = new StringBuilder(); - builder - .append("HeapMaxSize: ") - .append(getHeapMaxSize(memoryUsage) / 1024 / 1024) - .append(" MiB.\n"); - builder - .append("HeapSize: ") - .append(getHeapSize(memoryUsage) / 1024 / 1024) - .append(" MiB.\n"); - builder - .append("HeapUsedSize: ") - .append(getHeapUsedSize(memoryUsage) / 1024 / 1024) - .append(" MiB.\n"); - builder - .append("HeapUsagePercent: ") - .append(getHeapUsagePercent(memoryUsage)) - .append("%."); - - if (!memoryPoolMXBeans.isEmpty()) { - builder - .append('\n') - .append("Memory Pools:"); - } - - for (MemoryPoolMXBean mxBeen : memoryPoolMXBeans) { - - MemoryUsage usage = mxBeen.getUsage(); - - builder - .append('\n') - .append(mxBeen.getName()) - .append(":\n"); - builder - .append(" ") - .append("MemoryType: ") - .append(mxBeen.getType()) - .append('\n'); - builder - .append(" ") - .append("MemoryMaxSize: ") - .append(usage.getMax() / 1024 / 1024) - .append(" MiB.\n"); - builder - .append(" ") - .append("MemorySize: ") - .append(usage.getCommitted() / 1024 / 1024) - .append(" MiB.\n"); - builder - .append(" ") - .append("MemoryUsed: ") - .append(usage.getUsed() / 1024 / 1024) - .append(" MiB."); - } - - return builder.toString(); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/monitoring/MonitoringManager.java b/rlib-common/src/main/java/javasabr/rlib/common/monitoring/MonitoringManager.java deleted file mode 100644 index c91e07d9..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/monitoring/MonitoringManager.java +++ /dev/null @@ -1,92 +0,0 @@ -package javasabr.rlib.common.monitoring; - -/** - * The class to monitor a state a Java process. - * - * @author JavaSaBr - */ -public final class MonitoringManager { - - private static final MonitoringManager INSTANCE = new MonitoringManager(); - - /** - * Gets instance. - * - * @return the instance - */ - public static MonitoringManager getInstance() { - return INSTANCE; - } - - /** - * The memory monitoring. - */ - private final MemoryMonitoring memoryMonitoring; - - /** - * The runtime monitoring. - */ - private final RuntimeMonitoring runtimeMonitoring; - - /** - * The threads monitoring. - */ - private final ThreadMonitoring threadMonitoring; - - private MonitoringManager() { - this.memoryMonitoring = new MemoryMonitoring(); - this.runtimeMonitoring = new RuntimeMonitoring(); - this.threadMonitoring = new ThreadMonitoring(); - } - - /** - * Gets memory monitoring. - * - * @return the memory monitoring. - */ - public MemoryMonitoring getMemoryMonitoring() { - return memoryMonitoring; - } - - /** - * Gets runtime monitoring. - * - * @return the runtime monitoring. - */ - public RuntimeMonitoring getRuntimeMonitoring() { - return runtimeMonitoring; - } - - /** - * Gets thread monitoring. - * - * @return the threads monitoring. - */ - public ThreadMonitoring getThreadMonitoring() { - return threadMonitoring; - } - - @Override - public String toString() { - - StringBuilder builder = new StringBuilder("\n"); - builder - .append("#==========Java Process Info==========#") - .append('\n'); - builder.append("#=============Memory Info=============#"); - builder - .append('\n') - .append(getMemoryMonitoring()) - .append('\n'); - builder.append("#============Runtime Info=============#"); - builder - .append('\n') - .append(getRuntimeMonitoring()) - .append('\n'); - // builder.append("#============Current state============#"); - // builder.append('\n').append(getThreadMonitoring()).append('\n'); - builder.append("#=====================================#"); - - return builder.toString(); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/monitoring/RuntimeMonitoring.java b/rlib-common/src/main/java/javasabr/rlib/common/monitoring/RuntimeMonitoring.java deleted file mode 100644 index 0797a668..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/monitoring/RuntimeMonitoring.java +++ /dev/null @@ -1,112 +0,0 @@ -package javasabr.rlib.common.monitoring; - -import static java.lang.ThreadLocal.withInitial; - -import java.lang.management.ManagementFactory; -import java.lang.management.OperatingSystemMXBean; -import java.lang.management.RuntimeMXBean; -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * The class to monitor a runtime state of a java process. - * - * @author JavaSaBr - */ -public class RuntimeMonitoring { - - private static final ThreadLocal LOCAL_DATE_FORMAT = withInitial(SimpleDateFormat::new); - - private static final ThreadLocal LOCAL_DATE = withInitial(Date::new); - - /** - * The OS manager. - */ - private final OperatingSystemMXBean operatingSystemMXBean; - - /** - * The runtime manager. - */ - private final RuntimeMXBean runtimeMXBean; - - /** - * Instantiates a new Runtime monitoring. - */ - public RuntimeMonitoring() { - this.operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean(); - this.runtimeMXBean = ManagementFactory.getRuntimeMXBean(); - } - - @Override - public String toString() { - - Date date = LOCAL_DATE.get(); - date.setTime(runtimeMXBean.getStartTime()); - - SimpleDateFormat format = LOCAL_DATE_FORMAT.get(); - StringBuilder builder = new StringBuilder(); - builder - .append("Operating System:") - .append('\n'); - builder - .append(" ") - .append("OS Name: ") - .append(operatingSystemMXBean.getName()) - .append('\n'); - builder - .append(" ") - .append("OS Arch: ") - .append(operatingSystemMXBean.getArch()) - .append('\n'); - builder - .append(" ") - .append("OS Version: ") - .append(operatingSystemMXBean.getVersion()) - .append('\n'); - builder - .append(" ") - .append("OS System Load: ") - .append(operatingSystemMXBean.getSystemLoadAverage()) - .append('\n'); - builder - .append(" ") - .append("OS Available Processors: ") - .append(operatingSystemMXBean.getAvailableProcessors()) - .append('\n'); - builder - .append("Runtime:") - .append('\n'); - builder - .append(" ") - .append("JVM StartTime: ") - .append(format.format(date)) - .append('\n'); - builder - .append(" ") - .append("JVM UpTime: ") - .append(runtimeMXBean.getUptime() / 1000 / 60) - .append(" minuts") - .append('\n'); - builder - .append(" ") - .append("JVM Name: ") - .append(runtimeMXBean.getVmName()) - .append('\n'); - builder - .append(" ") - .append("JVM Vendor: ") - .append(runtimeMXBean.getVmVendor()) - .append('\n'); - builder - .append(" ") - .append("JVM Version: ") - .append(runtimeMXBean.getVmVersion()) - .append('\n'); - builder - .append(" ") - .append("JVM Java Version: ") - .append(runtimeMXBean.getSpecVersion()); - - return builder.toString(); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/monitoring/ThreadMonitoring.java b/rlib-common/src/main/java/javasabr/rlib/common/monitoring/ThreadMonitoring.java deleted file mode 100644 index b62e28c2..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/monitoring/ThreadMonitoring.java +++ /dev/null @@ -1,8 +0,0 @@ -package javasabr.rlib.common.monitoring; - -/** - * The type Thread monitoring. - */ -public class ThreadMonitoring { - -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/monitoring/package-info.java b/rlib-common/src/main/java/javasabr/rlib/common/monitoring/package-info.java deleted file mode 100644 index 12d6d08d..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/monitoring/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -@NullMarked -package javasabr.rlib.common.monitoring; - -import org.jspecify.annotations.NullMarked; \ No newline at end of file diff --git a/rlib-common/src/main/java/javasabr/rlib/common/tuple/Tuple.java b/rlib-common/src/main/java/javasabr/rlib/common/tuple/Tuple.java new file mode 100644 index 00000000..2b9d76bf --- /dev/null +++ b/rlib-common/src/main/java/javasabr/rlib/common/tuple/Tuple.java @@ -0,0 +1,3 @@ +package javasabr.rlib.common.tuple; + +public record Tuple(L left, R right) {} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/ArrayUtils.java b/rlib-common/src/main/java/javasabr/rlib/common/util/ArrayUtils.java index 177d6c38..6ccef6d4 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/ArrayUtils.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/ArrayUtils.java @@ -18,7 +18,6 @@ import javasabr.rlib.common.function.TripleConsumer; import javasabr.rlib.common.function.TripleFunction; import javasabr.rlib.common.function.TriplePredicate; -import javasabr.rlib.common.util.array.Array; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @@ -622,16 +621,6 @@ public static void sort( java.util.Arrays.sort(array, fromIndex, toIndex, comparator); } - /** - * Convert the array to a string presentation. - * - * @param array the array. - * @return the string presentation. - */ - public static String toString(Array array) { - return toString(array, Object::toString); - } - public static String toString(T[] array, int size, Function toString) { if (array.length < 1) { @@ -654,43 +643,6 @@ public static String toString(T[] array, int size, Function toStr return builder.toString(); } - /** - * Convert the array to a string presentation. - * - * @param the element's type. - * @param array the array. - * @param toString the to string function. - * @return the string presentation. - */ - public static String toString(Array array, Function toString) { - - if (array.isEmpty()) { - return "[]"; - } - - var className = array - .array() - .getClass() - .getSimpleName(); - - var builder = new StringBuilder(className.substring(0, className.length() - 1)); - - for (int i = 0, length = array.size() - 1; i <= length; i++) { - - builder.append(toString.apply(array.get(i))); - - if (i == length) { - break; - } - - builder.append(", "); - } - - builder.append("]"); - - return builder.toString(); - } - /** * Convert the array to a string presentation. * @@ -853,70 +805,6 @@ public static String toString( return builder.toString(); } - /** - * Move all elements from the source array to the destination array. - * - * @param the type parameter - * @param the type parameter - * @param source the source array. - * @param destination the destination array. - * @param clearSource need clears the source array after moving. - */ - public static void move(Array source, Array destination, boolean clearSource) { - - if (source.isEmpty()) { - return; - } - - destination.addAll(source); - - if (clearSource) { - source.clear(); - } - } - - /** - * Move all elements from the source array to the destination array. - * - * @param the type parameter - * @param the type parameter - * @param source the source array. - * @param destination the destination array. - */ - public static void move(Array source, Array destination) { - move(source, destination, true); - } - - /** - * Add the object to the array in a synchronize block. - * - * @param the type parameter - * @param the type parameter - * @param array the array. - * @param object the object. - */ - public static void addInSynchronizeTo(Array array, V object) { - synchronized (array) { - array.add(object); - } - } - - /** - * Fast remove the object from the array in a synchronize block. - * - * @param the type parameter - * @param the type parameter - * @param array the array. - * @param object the object. - */ - public static void fastRemoveInSynchronizeTo( - Array array, - V object) { - synchronized (array) { - array.fastRemove(object); - } - } - /** * Apply the function to each element of the array. * diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/Copyable.java b/rlib-common/src/main/java/javasabr/rlib/common/util/Copyable.java deleted file mode 100644 index e60fef60..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/Copyable.java +++ /dev/null @@ -1,17 +0,0 @@ -package javasabr.rlib.common.util; - -/** - * The interface for implementing the copy method of this object. - * - * @param the type parameter - * @author JavaSaBr - */ -public interface Copyable { - - /** - * Create a new copy of this object. - * - * @return the new copy of this object. - */ - T copy(); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/HasName.java b/rlib-common/src/main/java/javasabr/rlib/common/util/HasName.java deleted file mode 100644 index c54884a2..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/HasName.java +++ /dev/null @@ -1,19 +0,0 @@ -package javasabr.rlib.common.util; - -import org.jspecify.annotations.NullMarked; - -/** - * The interface to mark an object that it has a name. - * - * @author JavaSaBr - */ -@NullMarked -public interface HasName { - - /** - * Gets name. - * - * @return the name of this object. - */ - String getName(); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/PropertyLoader.java b/rlib-common/src/main/java/javasabr/rlib/common/util/PropertyLoader.java index 3d00a653..f7f9608a 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/PropertyLoader.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/PropertyLoader.java @@ -9,24 +9,15 @@ import java.util.Locale; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; -import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; /** - * The property loader using UTF-8 encoding. - * * @author JavaSaBr */ -@NullMarked -public class PropertyLoader extends ResourceBundle.Control { +public final class PropertyLoader extends ResourceBundle.Control { private static final PropertyLoader INSTANCE = new PropertyLoader(); - /** - * Gets instance. - * - * @return the instance - */ public static PropertyLoader getInstance() { return INSTANCE; } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/Reloadable.java b/rlib-common/src/main/java/javasabr/rlib/common/util/Reloadable.java deleted file mode 100644 index 70083aad..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/Reloadable.java +++ /dev/null @@ -1,20 +0,0 @@ -package javasabr.rlib.common.util; - -import org.jspecify.annotations.NullMarked; - -/** - * The interface for implementing the method for reloading the object to new version of the object. - * - * @param the type parameter - * @author JavaSaBr - */ -@NullMarked -public interface Reloadable { - - /** - * Reload this object to version of the object. - * - * @param updated the updated object. - */ - void reload(E updated); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/Reusable.java b/rlib-common/src/main/java/javasabr/rlib/common/util/Reusable.java deleted file mode 100644 index c5675c61..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/Reusable.java +++ /dev/null @@ -1,17 +0,0 @@ -package javasabr.rlib.common.util; - -/** - * @author JavaSaBr - */ -public interface Reusable extends AutoCloseable { - - /** - * Cleanup this object - */ - default void cleanup() {} - - @Override - default void close() { - cleanup(); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/Utils.java b/rlib-common/src/main/java/javasabr/rlib/common/util/Utils.java index 5d520118..09474c2e 100644 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/Utils.java +++ b/rlib-common/src/main/java/javasabr/rlib/common/util/Utils.java @@ -16,23 +16,15 @@ import javasabr.rlib.common.function.NotNullSafeTriFunction; import javasabr.rlib.common.function.SafeRunnable; import javasabr.rlib.logger.api.LoggerManager; -import org.jspecify.annotations.NullMarked; +import lombok.experimental.UtilityClass; import org.jspecify.annotations.Nullable; /** - * The utility class. - * * @author JavaSaBr */ -@NullMarked +@UtilityClass public final class Utils { - /** - * Get a folder of a class. - * - * @param cs the class. - * @return the path to the folder. - */ public static Path getRootFolderFromClass(Class cs) { var className = cs.getName(); @@ -111,11 +103,6 @@ public static String getUserName() { return System.getProperty("user.name"); } - /** - * Execute the function with auto-converting a checked exception to an unchecked. - * - * @param function the function. - */ public static void unchecked(SafeRunnable function) { try { function.run(); @@ -126,14 +113,6 @@ public static void unchecked(SafeRunnable function) { } } - /** - * Try to execute a function with some result. - * - * @param function the function. - * @param the result's type. - * @return the result or null. - * @since 9.5.0 - */ public static @Nullable R tryGet(NotNullSafeSupplier function) { try { return function.get(); @@ -143,13 +122,6 @@ public static void unchecked(SafeRunnable function) { } } - /** - * Execute the function with auto-converting a checked exception to an unchecked. - * - * @param first the argument. - * @param function the function. - * @param the argument's type. - */ public static void unchecked(F first, NotNullSafeConsumer function) { try { function.accept(first); @@ -160,15 +132,6 @@ public static void unchecked(F first, NotNullSafeConsumer function) { } } - /** - * Execute the function with auto-converting a checked exception to an unchecked. - * - * @param first the first argument. - * @param second the second argument. - * @param consumer the function. - * @param the first argument's type. - * @param the second argument's type. - */ public static void unchecked( F first, S second, @@ -182,13 +145,6 @@ public static void unchecked( } } - /** - * Execute the function with auto-converting a checked exception to an unchecked. - * - * @param function the function. - * @param the result type. - * @return the result. - */ public static R uncheckedGet(NotNullSafeFactory function) { try { return function.get(); @@ -199,15 +155,6 @@ public static R uncheckedGet(NotNullSafeFactory function) { } } - /** - * Execute the function with auto-converting a checked exception to an unchecked. - * - * @param argument the argument. - * @param function the function. - * @param the argument's type. - * @param the result's type. - * @return the result. - */ public static R uncheckedGet(F argument, NotNullSafeFunction function) { try { return function.apply(argument); @@ -218,16 +165,6 @@ public static R uncheckedGet(F argument, NotNullSafeFunction functi } } - /** - * Execute the function with returning default value if got an exception. - * - * @param argument the argument. - * @param function the function. - * @param def the default value. - * @param the argument's type. - * @param the result's type. - * @return the result. - */ public static R uncheckedGet( F argument, NotNullSafeFunction function, @@ -239,18 +176,6 @@ public static R uncheckedGet( } } - /** - * Execute the function with auto-converting a checked exception to an unchecked. - * - * @param first the first argument. - * @param second the second argument. - * @param function the function. - * @param the first's type. - * @param the second's type. - * @param the result's type. - * @return the result. - * @since 9.2.1 - */ public static R uncheckedGet( F first, S second, @@ -263,20 +188,6 @@ public static R uncheckedGet( throw new RuntimeException(e); } } - - /** - * Execute the function with auto-converting a checked exception to an unchecked. - * - * @param first the first argument. - * @param second the second argument. - * @param function the function. - * @param the first's type. - * @param the second's type. - * @param the third's type. - * @param the result's type. - * @return the result. - * @since 9.9.0 - */ public static R uncheckedGet( F first, S second, @@ -291,16 +202,6 @@ public static R uncheckedGet( } } - /** - * Try to execute a function with some result. - * - * @param argument the argument. - * @param function the function. - * @param the argument's type. - * @param the result's type. - * @return the result or null. - * @since 9.3.0 - */ public static @Nullable R tryGet(F argument, NotNullSafeFunction function) { try { return function.apply(argument); @@ -310,17 +211,6 @@ public static R uncheckedGet( } } - /** - * Try to execute a function with some result. - * - * @param argument the argument. - * @param function the function. - * @param def the default value. - * @param the argument's type. - * @param the result's type. - * @return the result or null. - * @since 9.3.0 - */ public static R tryGet( F argument, NotNullSafeFunction function, @@ -333,18 +223,6 @@ public static R tryGet( } } - /** - * Try to execute a function with some result and convert this result to another. - * - * @param argument the argument. - * @param function the function. - * @param resultConverter the result converter. - * @param the argument's type. - * @param the function result's type. - * @param the converter result's type. - * @return the final result or null. - * @since 9.3.0 - */ public static @Nullable FR tryGetAndConvert( F argument, NotNullSafeFunction function, @@ -357,31 +235,15 @@ public static R tryGet( } } - /** - * Print an exception to log. - * - * @param exception the exception. - * @since 9.8.0 - */ public static void print(Exception exception) { LoggerManager .getDefaultLogger() .warning(exception); } - /** - * Print a message to log. - * - * @param message the message. - * @since 9.8.0 - */ public static void print(String message) { LoggerManager .getDefaultLogger() .warning(message); } - - private Utils() { - throw new RuntimeException(); - } } diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/VarTable.java b/rlib-common/src/main/java/javasabr/rlib/common/util/VarTable.java deleted file mode 100644 index 2a950028..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/VarTable.java +++ /dev/null @@ -1,1252 +0,0 @@ -package javasabr.rlib.common.util; - -import static javasabr.rlib.common.util.ObjectUtils.notNull; - -import javasabr.rlib.common.util.dictionary.DictionaryFactory; -import javasabr.rlib.common.util.dictionary.ObjectDictionary; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -/** - * The utility class to contain properties of different types. - * - * @author JavaSaBr - */ -@NullMarked -public class VarTable { - - /** - * The table with values. - */ - private final ObjectDictionary values; - - /** - * @since 8.1.0 - */ - public VarTable() { - this.values = DictionaryFactory.newObjectDictionary(); - } - - /** - * Clear this table. - */ - public void clear() { - values.clear(); - } - - /** - * Get a value by the key. - * - * @param key the key. - * @param the value's type. - * @return the value. - * @throws IllegalArgumentException if the value is null. - */ - public T get(String key) { - - T result = ClassUtils.unsafeCast(values.get(key)); - - if (result != null) { - return result; - } - - throw new IllegalArgumentException("Not found value for the key: " + key); - } - - /** - * Get a value by a key. - * - * @param the value's type. - * @param key the key. - * @param type the type. - * @return the value. - * @throws IllegalArgumentException if the value is null or has wrong type. - */ - public T get(String key, Class type) { - - var object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found value for the key: " + key); - } else if (type.isInstance(object)) { - return type.cast(object); - } - - throw new IllegalArgumentException( - "Value: " + object + " has another type than requested: " + type + " by the key: " + key); - } - - /** - * Get a value by a key. - * - * @param the value's type. - * @param the default value's type. - * @param key the key. - * @param type the type. - * @param def the default value. - * @return the value or default if the value is null or has wrong type. - */ - public T get(String key, Class type, E def) { - - var object = values.get(key); - - if (object == null) { - return def; - } else if (type.isInstance(object)) { - return type.cast(object); - } - - return def; - } - - /** - * Get a value by a key. - * - * @param the value's type. - * @param the default value's type. - * @param key the key. - * @param type the type. - * @param def the default value. - * @return the value or default if the value not found. - * @throws IllegalArgumentException if the value has wrong type. - */ - public @Nullable T getNullable(String key, Class type, @Nullable E def) { - - var object = values.get(key); - - if (object == null) { - return def; - } else if (type.isInstance(object)) { - return type.cast(object); - } - - throw new IllegalArgumentException( - "Value: " + object + " has another type than requested: " + type + " by the key: " + key); - } - - /** - * Get a value by a key. - * - * @param the value's type. - * @param key the key. - * @param def the default value. - * @return the value or default if the value is null. - */ - public T get(String key, T def) { - - var object = values.get(key); - - if (object == null) { - return def; - } - - var type = def.getClass(); - - if (type.isInstance(object)) { - return notNull(ClassUtils.unsafeCast(object)); - } - - throw new IllegalArgumentException( - "Value: " + object + " has another type than requested: " + type + " by the key: " + key); - } - - /** - * Get a value by a key. - * - * @param the value's type. - * @param key the key. - * @param def the default value. - * @return the value or default if the value is not found. - */ - public @Nullable T getNullable(String key, @Nullable T def) { - - var object = values.get(key); - - if (object == null) { - return def; - } - - if (def != null) { - - var type = def.getClass(); - - if (type.isInstance(object)) { - return ClassUtils.unsafeCast(object); - } - - return def; - - } else { - return ClassUtils.unsafeCast(object); - } - } - - /** - * Get an array of a key. - * - * @param the array element's type. - * @param key the key. - * @param type the array's type. - * @param def the default array. - * @return the array. - */ - @SafeVarargs - public final T[] getArray(String key, Class type, T... def) { - - var object = values.get(key); - - if (object == null) { - return def; - } else if (type.isInstance(object)) { - return ClassUtils.unsafeNNCast(object); - } - - throw new IllegalArgumentException( - "Value: " + object + " has another type than requested: " + type + " by the key: " + key); - } - - /** - * Get a boolean value by a key. - * - * @param key the key. - * @return the value. - */ - public boolean getBoolean(String key) { - - var object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found value for the key: " + key); - } else if (object instanceof Boolean) { - return (Boolean) object; - } else if (object instanceof String) { - return Boolean.parseBoolean(object.toString()); - } - - throw new IllegalArgumentException("Value: " + object + " cannot be converted to boolean by the key: " + key); - } - - /** - * Get a boolean value by a key. - * - * @param key the key. - * @param def the default value. - * @return the value. - */ - public boolean getBoolean(String key, boolean def) { - - var object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof Boolean) { - return (Boolean) object; - } else if (object instanceof String) { - return Boolean.parseBoolean(object.toString()); - } - - throw new IllegalArgumentException("Value: " + object + " cannot be converted to boolean by the key: " + key); - } - - /** - * Get a boolean array by a key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @return the boolean array. - */ - public boolean[] getBooleanArray(String key, String regex) { - - var object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found value for the key: " + key); - } else if (object instanceof boolean[]) { - return (boolean[]) object; - } else if (object instanceof String) { - return parseBooleanArray(regex, object); - } - - throw new IllegalArgumentException("Value: " + object + " cannot be converted to boolean array by the key: " + key); - } - - private boolean[] parseBooleanArray(String regex, Object object) { - - var strings = object - .toString() - .split(regex); - var booleans = new boolean[strings.length]; - - for (int i = 0, length = strings.length; i < length; i++) { - booleans[i] = Boolean.parseBoolean(strings[i].trim()); - } - - return booleans; - } - - /** - * Get a boolean array by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @param def the default array. - * @return the boolean array. - */ - public boolean[] getBooleanArray( - final String key, - final String regex, - final boolean... def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof boolean[]) { - return (boolean[]) object; - } else if (object instanceof String) { - return parseBooleanArray(regex, object); - } - - return def; - } - - /** - * Get a byte value by the key. - * - * @param key the key. - * @return the byte. - */ - public byte getByte(final String key) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof Byte) { - return (Byte) object; - } else if (object instanceof String) { - return Byte.parseByte(object.toString()); - } - - throw new IllegalArgumentException("Not found " + key); - } - - /** - * Get a byte value by the key. - * - * @param key the key. - * @param def the default value. - * @return the byte. - */ - public byte getByte(final String key, final byte def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof Byte) { - return (Byte) object; - } else if (object instanceof String) { - return Byte.parseByte(object.toString()); - } - - return def; - } - - /** - * Get a byte array by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @return the byte array. - */ - public byte[] getByteArray(final String key, final String regex) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof byte[]) { - return (byte[]) object; - } else if (object instanceof String) { - return parseByteArray(regex, object); - } - - throw new IllegalArgumentException("Not found " + key); - } - - private byte[] parseByteArray(final String regex, final Object object) { - - final String[] strings = object - .toString() - .split(regex); - final byte[] result = new byte[strings.length]; - - for (int i = 0, length = strings.length; i < length; i++) { - result[i] = Byte.parseByte(strings[i]); - } - - return result; - } - - /** - * Get a byte array by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @param def the default byte array. - * @return the byte array. - */ - public byte[] getByteArray( - final String key, - final String regex, - final byte... def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof byte[]) { - return (byte[]) object; - } else if (object instanceof String) { - return parseByteArray(regex, object); - } - - throw new IllegalArgumentException("Not found " + key); - } - - /** - * Get a double value by the key. - * - * @param key the key. - * @return the value. - */ - public double getDouble(final String key) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof Double) { - return (Double) object; - } else if (object instanceof String) { - return Double.parseDouble(object.toString()); - } - - throw new IllegalArgumentException("Not found " + key); - } - - /** - * Get a double value by the key. - * - * @param key the key. - * @param def the default value. - * @return the value. - */ - public double getDouble(final String key, final double def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof Double) { - return (Double) object; - } else if (object instanceof String) { - return Double.parseDouble(object.toString()); - } - - return def; - } - - /** - * Get a double array by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @return the double array. - */ - public double[] getDoubleArray(final String key, final String regex) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof double[]) { - return (double[]) object; - } else if (object instanceof String) { - return parseDoubleArray(regex, object); - } - - throw new IllegalArgumentException("Not found " + key); - } - - private double[] parseDoubleArray(final String regex, final Object object) { - - final String[] strings = object - .toString() - .split(regex); - final double[] result = new double[strings.length]; - - for (int i = 0, length = strings.length; i < length; i++) { - result[i] = Double.parseDouble(strings[i]); - } - - return result; - } - - /** - * Get a double array by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @param def the default array. - * @return the double array. - */ - public double[] getDoubleArray( - final String key, - final String regex, - final double... def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof double[]) { - return (double[]) object; - } else if (object instanceof String) { - return parseDoubleArray(regex, object); - } - - throw new IllegalArgumentException("Not found " + key); - } - - /** - * Get an enum value by the key. - * - * @param the type parameter - * @param key the key. - * @param type the type of enum. - * @return the value. - */ - public > T getEnum(final String key, final Class type) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (type.isInstance(object)) { - return type.cast(object); - } else if (object instanceof String) { - return Enum.valueOf(type, object.toString()); - } - - throw new IllegalArgumentException("Not found " + key); - } - - /** - * Get an enum value by the key. - * - * @param the type parameter - * @param key the key. - * @param type the type of enum. - * @param def the default value. - * @return the value. - */ - public > T getEnum( - final String key, - final Class type, - final T def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (type.isInstance(object)) { - return type.cast(object); - } else if (object instanceof String) { - return Enum.valueOf(type, object.toString()); - } - - return def; - } - - /** - * Get an enum array by the key. - * - * @param the type parameter - * @param key the key. - * @param type the type of enum. - * @param regex the regex to split if a value is string. - * @return the enum array. - */ - public > T[] getEnumArray( - final String key, - final Class type, - final String regex) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof Enum[]) { - return notNull(ClassUtils.unsafeCast(object)); - } else if (object instanceof String) { - return parseEnumArray(type, regex, object); - } - - throw new IllegalArgumentException("Not found " + key); - } - - private > T[] parseEnumArray( - final Class type, - final String regex, - final Object object) { - - final String[] strings = object - .toString() - .split(regex); - final T[] result = notNull(ClassUtils.unsafeCast(ArrayUtils.create(type, strings.length))); - - for (int i = 0, length = strings.length; i < length; i++) { - result[i] = Enum.valueOf(type, strings[i]); - } - - return result; - } - - /** - * Get an enum array by the key. - * - * @param the type parameter - * @param key the key. - * @param type the type of enum. - * @param regex the regex to split if a value is string. - * @param def the default array. - * @return the enum array. - */ - - public > T[] getEnumArray( - final String key, - final Class type, - final String regex, - final T... def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof Enum[]) { - return notNull(ClassUtils.unsafeCast(object)); - } else if (object instanceof String) { - return parseEnumArray(type, regex, object); - } - - throw new IllegalArgumentException("Not found " + key); - } - - /** - * Get a float value by the key. - * - * @param key the key. - * @return the float value. - */ - public float getFloat(final String key) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof Float) { - return (Float) object; - } else if (object instanceof String) { - return Float.parseFloat(object.toString()); - } - - throw new IllegalArgumentException("Not found " + key); - } - - /** - * Get a float value by the key. - * - * @param key the key. - * @param def the default value. - * @return the float value. - */ - public float getFloat(final String key, final float def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof Float) { - return (Float) object; - } else if (object instanceof String) { - return Float.parseFloat(object.toString()); - } - - return def; - } - - /** - * Get a float array by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @return the float array. - */ - public float[] getFloatArray(final String key, final String regex) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException(); - } else if (object instanceof float[]) { - return (float[]) object; - } else if (object instanceof String) { - return parseFloatArray(regex, object); - } - - throw new IllegalArgumentException("Not found " + key); - } - - private float[] parseFloatArray(final String regex, final Object object) { - - final String[] strings = object - .toString() - .split(regex); - final float[] result = new float[strings.length]; - - for (int i = 0, length = strings.length; i < length; i++) { - result[i] = Float.parseFloat(strings[i]); - } - - return result; - } - - /** - * Get a float array by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @param def the default array. - * @return the float array. - */ - public float[] getFloatArray(String key, String regex, float... def) { - - var object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof float[]) { - return (float[]) object; - } else if (object instanceof String) { - return parseFloatArray(regex, object); - } - - throw new IllegalArgumentException("Not found " + key); - } - - /** - * Get an integer value by the key. - * - * @param key the key. - * @return the integer value. - * @throws IllegalArgumentException if the value isn't exist. - * @throws IllegalStateException if the value can't be presented as int. - * @since 8.1.0 - */ - public int getInt(String key) { - - var object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof Integer) { - return (Integer) object; - } else if (object instanceof String) { - return Integer.parseInt(object.toString()); - } - - throw new IllegalStateException("Value: " + object + " can't be presented as int, key: " + key); - } - - /** - * Get an integer value by the key. - * - * @param key the key. - * @param def the default value. - * @return the integer value or the default value if the value isn't exist. - * @throws IllegalStateException if the value can't be presented as int. - * @since 8.1.0 - */ - public int getInt(String key, int def) { - - var object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof Integer) { - return (Integer) object; - } else if (object instanceof String) { - return Integer.parseInt(object.toString()); - } - - throw new IllegalStateException("Value: " + object + " can't be presented as int, key: " + key); - } - - /** - * Get an int array value by the key. - * - * @param key the key. - * @return the int array value. - * @throws IllegalStateException if the value can't be presented as int array. - * @throws IllegalArgumentException if the value isn't exist. - * @since 9.2.1 - */ - public int[] getIntArray(String key) { - - var object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof int[]) { - return (int[]) object; - } else if (object instanceof Integer[]) { - return ArrayUtils.toIntArray((Integer[]) object); - } - - throw new IllegalStateException("Value: " + object + " can't be presented as int array, key: " + key); - } - - /** - * Get an int array value by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @return the int array value. - * @throws IllegalArgumentException if the value isn't exist. - * @throws IllegalStateException if the value can't be presented as int array. - * @since 8.1.0 - */ - public int[] getIntArray(String key, String regex) { - - var object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof int[]) { - return (int[]) object; - } else if (object instanceof String) { - return ArrayUtils.toIntArray((String) object, regex); - } - - throw new IllegalStateException("Value: " + object + " can't be presented as int array, key: " + key); - } - - /** - * Get an int array value by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @param def the default value. - * @return the int array value or the default value if the value isn't exist. - * @throws IllegalStateException if the value can't be presented as int array. - * @since 8.1.0 - */ - public int[] getIntArray(String key, String regex, int... def) { - - var object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof int[]) { - return (int[]) object; - } else if (object instanceof String) { - return ArrayUtils.toIntArray((String) object, regex); - } - - throw new IllegalStateException("Value: " + object + " can't be presented as int array, key: " + key); - } - - /** - * Get a long value by the key. - * - * @param key the key. - * @return the long value. - */ - public long getLong(final String key) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof Long) { - return (Long) object; - } else if (object instanceof String) { - return Long.parseLong(object.toString()); - } - - throw new IllegalArgumentException("Not found " + key); - } - - /** - * Get a long value by the key. - * - * @param key the key. - * @param def the default value. - * @return the long value. - */ - public long getLong(final String key, final long def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof Long) { - return (Long) object; - } else if (object instanceof String) { - return Long.parseLong(object.toString()); - } - - return def; - } - - /** - * Get a long array by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @return the long array. - */ - public long[] getLongArray(final String key, final String regex) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof long[]) { - return (long[]) object; - } else if (object instanceof String) { - return parseLongArray(regex, object); - } - - throw new IllegalArgumentException("Not found " + key); - } - - private long[] parseLongArray(final String regex, final Object object) { - - final String[] strings = object - .toString() - .split(regex); - final long[] result = new long[strings.length]; - - for (int i = 0, length = strings.length; i < length; i++) { - result[i] = Long.parseLong(strings[i]); - } - - return result; - } - - /** - * Get a long array by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @param def the default array. - * @return the long array. - */ - public long[] getLongArray( - final String key, - final String regex, - final long... def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof long[]) { - return (long[]) object; - } else if (object instanceof String) { - return parseLongArray(regex, object); - } - - throw new IllegalArgumentException("Not found " + key); - } - - /** - * Get a short value by the key. - * - * @param key the key. - * @return the short value. - */ - public short getShort(final String key) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof Short) { - return (Short) object; - } else if (object instanceof String) { - return Short.parseShort(object.toString()); - } - - throw new IllegalArgumentException("Not found " + key); - } - - /** - * Get a short value by the key. - * - * @param key the key. - * @param def the default value. - * @return the short value. - */ - public short getShort(final String key, final short def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof Short) { - return (Short) object; - } else if (object instanceof String) { - return Short.parseShort(object.toString()); - } - - return def; - } - - /** - * Get a short array by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @return the short array. - */ - public short[] getShortArray(final String key, final String regex) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof short[]) { - return (short[]) object; - } else if (object instanceof String) { - return parseShortArray(regex, object); - } - - throw new IllegalArgumentException("Not found " + key); - } - - private short[] parseShortArray(final String regex, final Object object) { - - final String[] strings = object - .toString() - .split(regex); - final short[] result = new short[strings.length]; - - for (int i = 0, length = strings.length; i < length; i++) { - result[i] = Short.parseShort(strings[i]); - } - - return result; - } - - /** - * Get a short array by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @param def the default array. - * @return the short array. - */ - public short[] getShortArray( - final String key, - final String regex, - final short... def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof short[]) { - return (short[]) object; - } else if (object instanceof String) { - return parseShortArray(regex, object); - } - - throw new IllegalArgumentException("Not found " + key); - } - - /** - * Get a string by the key. - * - * @param key the key. - * @return the string value. - * @throws IllegalArgumentException if the value isn't exist. - */ - public String getString(String key) { - - var object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof String) { - return object.toString(); - } - - throw new IllegalArgumentException("Not found " + key); - } - - /** - * Get a string by the key. - * - * @param key the key. - * @param def the default string. - * @return the string. - */ - public String getString(final String key, final String def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof String) { - return object.toString(); - } - - return def; - } - - /** - * Get a string by the key. - * - * @param key the key. - * @param def the default string. - * @return the string. - */ - public @Nullable String getNullableString(final String key, @Nullable final String def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof String) { - return object.toString(); - } - - return def; - } - - /** - * Get a string array by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @return the string array. - */ - public String[] getStringArray(final String key, final String regex) { - - final Object object = values.get(key); - - if (object == null) { - throw new IllegalArgumentException("Not found " + key); - } else if (object instanceof String[]) { - return (String[]) object; - } else if (object instanceof String) { - return object - .toString() - .split(regex); - } - - throw new IllegalArgumentException("Not found " + key); - } - - /** - * Get a string array by the key. - * - * @param key the key. - * @param regex the regex to split if a value is string. - * @param def the default array. - * @return the string array. - */ - public String[] getStringArray( - final String key, - final String regex, - final String... def) { - - final Object object = values.get(key); - - if (object == null) { - return def; - } else if (object instanceof String[]) { - return (String[]) object; - } else if (object instanceof String) { - return ((String) object).split(regex); - } - - throw new IllegalArgumentException("no found " + key); - } - - /** - * Get the values table. - * - * @return the values table. - */ - public ObjectDictionary getValues() { - return values; - } - - /** - * Put the value by the key to this vars table. - * - * @param key the key. - * @param value the value. - * @since 8.1.0 - */ - public void put(String key, Object value) { - values.put(key, notNull(value)); - } - - /** - * Clear a value by the key. - * - * @param key the key. - */ - public void clear(String key) { - values.remove(key); - } - - /** - * Copy all values from the another vars table. - * - * @param vars the another vars table. - * @return this vars table. - * @throws IllegalArgumentException is the vars table is the same as this vars table. - * @since 8.1.0 - */ - public VarTable put(VarTable vars) { - - if (vars == this) { - throw new IllegalArgumentException("Can't set itself."); - } - - values.put(vars.getValues()); - return this; - } - - /** - * Return true if a value by the key is presented in this vars table. - * - * @param key the key. - * @return true if a value by the key is presented in this vars table. - */ - public boolean has(String key) { - return values.containsKey(key); - } - - @Override - public String toString() { - return "VarTable: " + ("values = " + values); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/Array.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/Array.java deleted file mode 100644 index 182423e6..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/Array.java +++ /dev/null @@ -1,1450 +0,0 @@ -package javasabr.rlib.common.util.array; - -import static javasabr.rlib.common.util.ClassUtils.unsafeCast; -import static javasabr.rlib.common.util.ClassUtils.unsafeNNCast; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.Collection; -import java.util.Objects; -import java.util.Optional; -import java.util.RandomAccess; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Stream; -import javasabr.rlib.common.function.BiIntPredicate; -import javasabr.rlib.common.function.NotNullBiConsumer; -import javasabr.rlib.common.function.NotNullBiPredicate; -import javasabr.rlib.common.function.NotNullConsumer; -import javasabr.rlib.common.function.NotNullFloatBiObjectConsumer; -import javasabr.rlib.common.function.NotNullFunction; -import javasabr.rlib.common.function.NotNullFunctionInt; -import javasabr.rlib.common.function.NotNullIntBiObjectConsumer; -import javasabr.rlib.common.function.NotNullIntObjectPredicate; -import javasabr.rlib.common.function.NotNullLongBiObjectConsumer; -import javasabr.rlib.common.function.NotNullLongObjectPredicate; -import javasabr.rlib.common.function.NotNullPredicate; -import javasabr.rlib.common.function.NotNullSupplier; -import javasabr.rlib.common.function.NotNullTripleConsumer; -import javasabr.rlib.common.function.NotNullTriplePredicate; -import javasabr.rlib.common.util.ArrayUtils; -import javasabr.rlib.common.util.ClassUtils; -import javasabr.rlib.common.util.array.impl.DefaultArrayIterator; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -/** - * Interface to implement dynamic arrays. - *

To create to use {@link ArrayFactory}. - * - * @param the element's type. - * @author JavaSaBr - */ -@NullMarked -@Deprecated -public interface Array extends Collection, Serializable, Cloneable, RandomAccess { - - /** - * Create an empty read only array. - * - * @param the result element's type. - * @return the empty array. - */ - static ReadOnlyArray empty() { - return unsafeNNCast(ArrayFactory.EMPTY_ARRAY); - } - - /** - * Create a new array for the element's type. - * - * @param type the element's type. - * @param the element's type. - * @return the new array. - */ - static Array ofType(Class type) { - return ArrayFactory.newArray(type); - } - - /** - * Create a new array for the element's type. - * - * @param type the element's type. - * @param capacity the start capacity of this array. - * @param the element's type. - * @return the new array. - */ - static Array ofType(Class type, int capacity) { - return ArrayFactory.newArray(type, capacity); - } - - /** - * Copy an array to a read only array. - * - * @param another the another array. - * @param the element's type. - * @return the new read only array. - */ - static ReadOnlyArray of(Array another) { - return ArrayFactory.newReadOnlyArray(ArrayUtils.copyOfRange(another.array(), 0, another.size())); - } - - /** - * Creates a single element read only array. - * - * @param element the element. - * @param the element's type. - * @return the read only array. - */ - static ReadOnlyArray of(T element) { - - T[] newArray = ArrayUtils.create(element.getClass(), 1); - newArray[0] = element; - - return ArrayFactory.newReadOnlyArray(newArray); - } - - @SafeVarargs - static ReadOnlyArray of(T... elements) { - return ArrayFactory.newReadOnlyArray(ArrayUtils.copyOf(elements)); - } - - @SafeVarargs - static ReadOnlyArray optionals(Class type, Optional... elements) { - return ArrayFactory.newReadOnlyArray(Arrays - .stream(elements) - .filter(Optional::isPresent) - .map(Optional::get) - .toArray(value -> ArrayUtils.create(type, value))); - } - - static > A append(A first, A second) { - first.addAll(second); - return first; - } - - static ReadOnlyArray combine(Array first, Array second) { - - var componentType = ClassUtils.>unsafeNNCast(first - .array() - .getClass() - .getComponentType()); - - var newArray = ArrayUtils.combine(first.toArray(componentType), second.toArray(componentType)); - - return ArrayFactory.newReadOnlyArray(newArray); - } - - /** - * Create a supplier which creates new arrays. - * - * @param type the element's type. - * @param the element's type. - * @return the supplier. - */ - static NotNullSupplier> supplier(Class type) { - return () -> ArrayFactory.newConcurrentStampedLockArray(type); - } - - /** - * Create a function which creates new arrays. - * - * @param type the element's type. - * @param the element's type. - * @return the supplier. - */ - static NotNullFunction, Array> function(Class type) { - return ArrayFactory::newConcurrentStampedLockArray; - } - - /** - * Copy all elements from this array to a target array. - * - * @param target the target array. - */ - default void copyTo(Array target) { - target.addAll(this); - } - - /** - * Adds all elements from the array to this array. - * - * @param array the array with new elements. - * @return true if this array was changed. - */ - boolean addAll(Array array); - - /** - * Adds all elements from the array to this array. - * - * @param array the array with new elements. - * @return true if this array was changed. - */ - boolean addAll(E[] array); - - /** - * Applies this function to each element of this array with replacing to result element from thia function. - * - * @param function the function. - */ - default void apply(Function function) { - - E[] array = array(); - - for (int i = 0, length = size(); i < length; i++) { - array[i] = function.apply(array[i]); - } - } - - /** - * Get the wrapped array. - * - * @return the wrapped array. - */ - E [] array(); - - @Override - default Stream stream() { - return Arrays.stream(array(), 0, size()); - } - - @Override - default Stream parallelStream() { - return stream().parallel(); - } - - @Override - default boolean contains(Object object) { - - for (E element : array()) { - if (element == null) { - break; - } else if (element.equals(object)) { - return true; - } - } - - return false; - } - - /** - * Returns true if this array contains all of the elements in the specified array. - * - * @param array the array to be checked for containment in this array - * @return true if this array contains all of the elements in the specified array. - */ - default boolean containsAll(Array array) { - - if (array.isEmpty()) { - return false; - } - - for (var element : array.array()) { - if (element == null) { - break; - } else if (!contains(element)) { - return false; - } - } - - return true; - } - - @Override - default boolean containsAll(Collection array) { - - if (array.isEmpty()) { - return false; - } - - for (var element : array) { - if (element == null) { - break; - } else if (!contains(element)) { - return false; - } - } - - return true; - } - - /** - * Returns true if this array contains all of the elements in the specified array. - * - * @param array the array to be checked for containment in this array - * @return true if this array contains all of the elements in the specified array. - */ - default boolean containsAll(Object[] array) { - - if (array.length < 1) { - return false; - } - - for (Object element : array) { - if (!contains(element)) { - return false; - } - } - - return true; - } - - /** - * Removes the element at index possible with reordering. - * - * @param index the index of removing the element. - * @return the removed element. - */ - E fastRemove(int index); - - /** - * Removes an element without saving original ordering of other elements. - * - * @param object the element to remove. - * @return true if the element was removed. - */ - default boolean fastRemove(Object object) { - - int index = indexOf(object); - - if (index >= 0) { - fastRemove(index); - } - - return index >= 0; - } - - /** - * Removes the each element from the array. - * - * @param array the array with elements to remove. - * @return count of removed elements. - */ - default int fastRemoveAll(E[] array) { - - int count = 0; - - for (var object : array) { - if (fastRemove(object)) { - count++; - } - } - - return count; - } - - /** - * Try to get the first element of this array. - * - * @return the first element or null. - */ - default @Nullable E first() { - return isEmpty() ? null : get(0); - } - - /** - * Get an element by an index. - * - * @param index the index of the element. - * @return the element. - */ - E get(int index); - - /** - * Find an index of the object in this array. - * - * @param object the object to find. - * @return the index of the object or -1. - */ - default int indexOf(Object object) { - - int index = 0; - - for (E element : array()) { - - if (element == null) { - break; - } else if (Objects.equals(object, element)) { - return index; - } - - index++; - } - - return -1; - } - - @Override - default ArrayIterator iterator() { - return new DefaultArrayIterator<>(this); - } - - /** - * Try to get the last element. - * - * @return the last element or null. - */ - default @Nullable E last() { - - int size = size(); - - if (size < 1) { - return null; - } - - return get(size - 1); - } - - /** - * Find the last index of the object in this array. - * - * @param object the object. - * @return the last index or -1. - */ - default int lastIndexOf(Object object) { - - E[] array = array(); - - int last = -1; - - for (int i = 0, length = size(); i < length; i++) { - - E element = array[i]; - - if (element.equals(object)) { - last = i; - } - } - - return last; - } - - /** - * Get and remove the first element from this array. - * - * @return the first element or null. - */ - default @Nullable E poll() { - return isEmpty() ? null : remove(0); - } - - /** - * Get and remove the last element of this array. - * - * @return the last element or null. - */ - default @Nullable E pop() { - return isEmpty() ? null : fastRemove(size() - 1); - } - - /** - * Removes all of this target's elements that are also contained in the specified array (optional operation). - * - * @param target array containing elements to be removed from this array. - * @return true if this array changed as a result of the call. - */ - default boolean removeAll(Array target) { - - if (target.isEmpty()) { - return false; - } - - int count = 0; - - for (var element : target.array()) { - if (element == null) { - break; - } else if (remove(element)) { - count++; - } - } - - return count > 0; - } - - /** - * Removes all of this target's elements that are also contained in the specified array (optional operation) with - * reordering. - * - * @param target array containing elements to be removed from this array. - * @return true if this array changed as a result of the call. - */ - default boolean fastRemoveAll(Array target) { - - if (target.isEmpty()) { - return false; - } - - var count = 0; - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - - var element = array[i]; - - if (!target.contains(element)) { - continue; - } - - fastRemove(i); - i--; - length--; - count++; - } - - return count > 0; - } - - @Override - default boolean removeAll(Collection target) { - - if (target.isEmpty()) { - return false; - } - - int count = 0; - - for (var element : target) { - if (remove(element)) { - count++; - } - } - - return count == target.size(); - } - - /** - * Retains only the elements in this array that are contained in the specified array (optional operation). In other - * words, removes from this array all of its elements that are not contained in the specified array. - * - * @param target array containing elements to be retained in this array. - * @return true if this array changed as a result of the call. - */ - default boolean retainAll(Array target) { - - E[] array = array(); - - for (int i = 0, length = size(); i < length; i++) { - if (!target.contains(array[i])) { - fastRemove(i--); - length--; - } - } - - return true; - } - - @Override - default boolean retainAll(Collection target) { - - E[] array = array(); - - for (int i = 0, length = size(); i < length; i++) { - if (!target.contains(array[i])) { - fastRemove(i--); - length--; - } - } - - return true; - } - - /** - * Replace an element by an index. - * - * @param index the element's index. - * @param element the new element. - */ - void replace(int index, E element); - - /** - * Removes the element at index. - * - * @param index the index of removing the element. - * @return the removed element. - */ - E remove(int index); - - @Override - default boolean remove(Object object) { - - var index = indexOf(object); - - if (index >= 0) { - remove(index); - } - - return index >= 0; - } - - /** - * Sort this array using the comparator. - * - * @param comparator the comparator. - * @return the array - */ - default Array sort(ArrayComparator comparator) { - ArrayUtils.sort(array(), 0, size(), comparator); - return this; - } - - @Override - default T[] toArray(T[] newArray) { - - E[] array = array(); - - if (newArray.length >= size()) { - - for (int i = 0, j = 0, length = array.length, newLength = newArray.length; i < length && j < newLength; i++) { - if (array[i] == null) { - continue; - } - newArray[j++] = unsafeCast(array[i]); - } - - return newArray; - } - - Class arrayClass = unsafeCast(newArray.getClass()); - Class componentType = unsafeCast(arrayClass.getComponentType()); - - return toArray(componentType); - } - - /** - * Copy this array to the new array. - * - * @param the type parameter - * @param componentType the type of the new array. - * @return the copied array. - */ - default T[] toArray(Class componentType) { - - T[] newArray = ArrayUtils.create(componentType, size()); - E[] array = array(); - - System.arraycopy(array, 0, newArray, 0, size()); - - return newArray; - } - - /** - * Get the unsafe interface of this array. - * - * @return the unsafe interface of this array. - */ - default UnsafeArray asUnsafe() { - if (this instanceof UnsafeArray) { - return (UnsafeArray) this; - } else { - throw new UnsupportedOperationException(); - } - } - - @Override - default boolean isEmpty() { - return size() < 1; - } - - @Override - default E[] toArray() { - var array = array(); - return Arrays.copyOf(array, size(), (Class) array.getClass()); - } - - String toString(Function toString); - - @Override - default boolean removeIf(Predicate filter) { - - var array = array(); - var removed = 0; - - for (int i = 0, length = size(); i < length; i++) { - - var element = array[i]; - - if (filter.test(element)) { - remove(i); - i--; - length--; - removed++; - } - } - - return removed > 0; - } - - /** - * Removes all of the elements of this collection that satisfy the given predicate. - * - * @param argument the additional argument. - * @param filter the predicate which returns {@code true} for elements to be removed. - * @param the argument's type. - * @return {@code true} if any elements were removed. - */ - default boolean removeIf(A argument, NotNullBiPredicate filter) { - - var array = array(); - var removed = 0; - - for (int i = 0, length = size(); i < length; i++) { - - var element = array[i]; - - if (filter.test(argument, element)) { - remove(i); - i--; - length--; - removed++; - } - } - - return removed > 0; - } - - /** - * Removes all of the elements of this collection that satisfy the given predicate. - * - * @param argument the additional argument. - * @param converter the converter of the argument. - * @param filter the predicate which returns {@code true} for elements to be removed. - * @param the argument's type. - * @param the argument converted type. - * @return {@code true} if any elements were removed. - */ - default boolean removeIf( - A argument, - NotNullFunction converter, - NotNullBiPredicate filter) { - - var array = array(); - var removed = 0; - - for (int i = 0, length = size(); i < length; i++) { - - var element = array[i]; - - if (filter.test(converter.apply(argument), element)) { - remove(i); - i--; - length--; - removed++; - } - } - - return removed > 0; - } - - /** - * Removes all of the elements of this collection that satisfy the given predicate. - * - * @param argument the additional argument. - * @param converter the converter of the elements. - * @param filter the predicate which returns {@code true} for elements to be removed. - * @param the argument's type. - * @param the element converted type. - * @return {@code true} if any elements were removed. - * @since 9.6.0 - */ - default boolean removeIfConverted( - A argument, - NotNullFunction converter, - NotNullBiPredicate filter) { - - var array = array(); - var removed = 0; - - for (int i = 0, length = size(); i < length; i++) { - - var element = array[i]; - - if (filter.test(argument, converter.apply(element))) { - remove(i); - i--; - length--; - removed++; - } - } - - return removed > 0; - } - - /** - * Return true if there is at least an element for the condition. - * - * @param argument the argument. - * @param filter the condition. - * @param the argument's type. - * @return true if there is at least an element for the condition. - */ - default boolean anyMatch(T argument, NotNullBiPredicate filter) { - return findAny(argument, filter) != null; - } - - /** - * Return true if there is at least a converted element for the condition. - * - * @param argument the argument. - * @param converter the converter element to another type. - * @param filter the condition. - * @param the argument's type. - * @param the converted element's type. - * @return true if there is at least an element for the condition. - * @since 9.7.0 - */ - default boolean anyMatchConverted( - T argument, - NotNullFunction converter, - NotNullBiPredicate filter) { - return findAnyConverted(argument, converter, filter) != null; - } - - /** - * Return true if there is at least an element for the condition. - * - * @param argument the argument. - * @param filter the condition. - * @return true if there is at least an element for the condition. - */ - default boolean anyMatch(int argument, NotNullIntObjectPredicate filter) { - return findAny(argument, filter) != null; - } - - /** - * Return true if there is at least an element for the condition. - * - * @param the argument's type. - * @param argument the argument. - * @param filter the condition. - * @return true if there is at least an element for the condition. - */ - default boolean anyMatchR(T argument, NotNullBiPredicate filter) { - return findAnyR(argument, filter) != null; - } - - /** - * Find an element using the condition. - * - * @param filter the condition. - * @return the found element or null. - */ - default @Nullable E findAny(NotNullPredicate filter) { - - if (isEmpty()) { - return null; - } - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - - var element = array[i]; - - if (filter.test(element)) { - return element; - } - } - - return null; - } - - /** - * Search an element using the condition. - * - * @param argument the argument. - * @param filter the condition. - * @param the argument's type. - * @return the found element or null. - */ - default @Nullable E findAny(T argument, NotNullBiPredicate filter) { - - if (isEmpty()) { - return null; - } - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - - var element = array[i]; - - if (filter.test(argument, element)) { - return element; - } - } - - return null; - } - - /** - * Search an element using the condition by converted value. - * - * @param argument the argument. - * @param converter the converted an element to another type. - * @param filter the condition. - * @param the argument's type. - * @param the converted element's type. - * @return the found element or null. - * @since 9.7.0 - */ - default @Nullable E findAnyConverted( - T argument, - NotNullFunction converter, - NotNullBiPredicate filter) { - - if (isEmpty()) { - return null; - } - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - - var element = array[i]; - - if (filter.test(argument, converter.apply(element))) { - return element; - } - } - - return null; - } - - /** - * Find an element for the condition. - * - * @param the argument's type. - * @param argument the argument. - * @param filter the condition. - * @return the found element or null. - */ - default @Nullable E findAnyR(T argument, NotNullBiPredicate filter) { - - if (isEmpty()) { - return null; - } - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - - var element = array[i]; - - if (filter.test(element, argument)) { - return element; - } - } - - return null; - } - - /** - * Search an element using the condition. - * - * @param argument the argument. - * @param filter the condition. - * @return the found element or null. - */ - default @Nullable E findAny(int argument, NotNullIntObjectPredicate filter) { - - if (isEmpty()) { - return null; - } - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - - var element = array[i]; - - if (filter.test(argument, element)) { - return element; - } - } - - return null; - } - - /** - * Search an element using the condition. - * - * @param argument the argument. - * @param filter the condition. - * @return the found element or null. - */ - default @Nullable E findAnyL(long argument, NotNullLongObjectPredicate filter) { - - if (isEmpty()) { - return null; - } - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - - var element = array[i]; - - if (filter.test(argument, element)) { - return element; - } - } - - return null; - } - - /** - * Search an element using the condition. - * - * @param first the first argument. - * @param second the second argument. - * @param filter the condition. - * @param the first argument's type. - * @param the second argument's type. - * @return the found element or null. - */ - default @Nullable E findAny( - F first, - S second, - NotNullTriplePredicate filter) { - - if (isEmpty()) { - return null; - } - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - - var element = array[i]; - - if (filter.test(first, second, element)) { - return element; - } - } - - return null; - } - - /** - * Search a converted element to int using the condition. - * - * @param argument the argument. - * @param converter the converter element to int. - * @param filter the condition. - * @return the found element or null. - * @since 9.6.0 - */ - default @Nullable E findAnyConvertedToInt( - int argument, - NotNullFunctionInt converter, - BiIntPredicate filter) { - - if (isEmpty()) { - return null; - } - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - - var element = array[i]; - - if (filter.test(argument, converter.apply(element))) { - return element; - } - } - - return null; - } - - /** - * Search a converted element to int using the condition. - * - * @param argument the argument. - * @param firstConverter the converter element to T. - * @param secondConverter the converter element to int. - * @param filter the condition. - * @param the first converted type. - * @return the found element or null. - * @since 9.7.0 - */ - default @Nullable E findAnyConvertedToInt( - int argument, - NotNullFunction firstConverter, - NotNullFunctionInt secondConverter, - BiIntPredicate filter) { - - if (isEmpty()) { - return null; - } - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - - var element = array[i]; - - if (filter.test(argument, secondConverter.apply(firstConverter.apply(element)))) { - return element; - } - } - - return null; - } - - /** - * Calculate a count of matched elements. - * - * @param filter the condition. - * @return the count of matched elements. - * @since 9.5.0 - */ - default int count(NotNullPredicate filter) { - - var array = array(); - var count = 0; - - for (int i = 0, length = size(); i < length; i++) { - - var element = array[i]; - - if (filter.test(element)) { - count++; - } - } - - return count; - } - - /** - * Calculate a count of matched elements. - * - * @param arg the argument. - * @param filter the condition. - * @param the argument's type. - * @return the count of matched elements. - */ - default int count(F arg, NotNullBiPredicate filter) { - - var array = array(); - var count = 0; - - for (int i = 0, length = size(); i < length; i++) { - - var element = array[i]; - - if (filter.test(arg, element)) { - count++; - } - } - - return count; - } - - /** - * Calculate a count of matched elements with reversed ordering of arguments. - * - * @param the argument's type. - * @param arg the argument. - * @param filter the condition. - * @return the count of matched elements. - */ - default int countR(F arg, NotNullBiPredicate filter) { - - var array = array(); - var count = 0; - - for (int i = 0, length = size(); i < length; i++) { - - var element = array[i]; - - if (filter.test(element, arg)) { - count++; - } - } - - return count; - } - - @Override - default void forEach(Consumer consumer) { - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - consumer.accept(array[i]); - } - } - - /** - * Apply a function to each filtered element. - * - * @param filter the condition. - * @param consumer the function. - */ - default void forEachFiltered(NotNullPredicate filter, NotNullConsumer consumer) { - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - - E element = array[i]; - - if (filter.test(element)) { - consumer.accept(element); - } - } - } - - /** - * Apply a function to each element. - * - * @param argument the argument. - * @param consumer the function. - * @param the type of an argument. - */ - default void forEach(T argument, NotNullBiConsumer consumer) { - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - consumer.accept(argument, array[i]); - } - } - - /** - * Apply a function to each element. - * - * @param argument the argument. - * @param consumer the function. - * @param the argument's type. - */ - default void forEachR(T argument, NotNullBiConsumer consumer) { - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - consumer.accept(array[i], argument); - } - } - - /** - * Apply a function to each converted element. - * - * @param argument the argument. - * @param converter the converter from E to C. - * @param consumer the function. - * @param the argument's type. - * @param the converted type. - */ - default void forEachConverted( - T argument, - NotNullFunction converter, - NotNullBiConsumer consumer) { - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - consumer.accept(argument, converter.apply(array[i])); - } - } - - /** - * Apply a function to each converted element. - * - * @param first the first argument. - * @param second the second argument. - * @param converter the converter from E to C. - * @param consumer the function. - * @param the first argument's type. - * @param the second argument's type. - * @param the converted type. - */ - default void forEachConverted( - F first, - S second, - NotNullFunction converter, - NotNullTripleConsumer consumer) { - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - consumer.accept(first, second, converter.apply(array[i])); - } - } - - /** - * Apply a function to each element and converted argument. - * - * @param argument the argument. - * @param converter the converter from T to C. - * @param consumer the function. - * @param the argument's type. - * @param the converted type. - * @since 9.8.0 - */ - default void forEach( - T argument, - NotNullFunction converter, - NotNullBiConsumer consumer) { - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - consumer.accept(converter.apply(argument), array[i]); - } - } - - /** - * Apply a function to each filtered element. - * - * @param the type of an argument. - * @param argument the argument. - * @param filter the condition. - * @param consumer the function. - */ - default void forEachFiltered( - T argument, - NotNullBiPredicate filter, - NotNullBiConsumer consumer) { - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - - E element = array[i]; - - if (filter.test(argument, element)) { - consumer.accept(argument, element); - } - } - } - - /** - * Apply a function to each element. - * - * @param first the first argument. - * @param second the second argument. - * @param consumer the function. - * @param the firs argument's type. - * @param the second argument's type. - */ - default void forEach( - F first, - S second, - NotNullTripleConsumer consumer) { - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - consumer.accept(first, second, array[i]); - } - } - - /** - * Apply a function to each element. - * - * @param first the first argument. - * @param second the second argument. - * @param consumer the function. - * @param the second argument's type. - */ - default void forEach(int first, A second, NotNullIntBiObjectConsumer consumer) { - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - consumer.accept(first, second, array[i]); - } - } - - /** - * Apply the function to each element. - * - * @param first the first argument. - * @param second the second argument. - * @param consumer the function. - * @param the first argument type. - * @param the second argument type. - */ - default void forEachR( - F first, - S second, - NotNullTripleConsumer consumer) { - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - consumer.accept(array[i], first, second); - } - } - - /** - * Apply a function to each filtered element. - * - * @param first the first argument. - * @param second the second argument. - * @param filter the condition. - * @param consumer the function. - * @param the firs argument's type. - * @param the second argument's type. - */ - default void forEachFiltered( - F first, - S second, - NotNullTriplePredicate filter, - NotNullTripleConsumer consumer) { - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - - E element = array[i]; - - if (filter.test(first, second, element)) { - consumer.accept(first, second, element); - } - } - } - - /** - * Apply a function to each element. - * - * @param first the first argument. - * @param second the second argument. - * @param consumer the function. - * @param the second argument's type. - */ - default void forEachL( - long first, - F second, - NotNullLongBiObjectConsumer consumer) { - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - consumer.accept(first, second, array[i]); - } - } - - /** - * Apply a function to each element. - * - * @param the type parameter - * @param first the first argument. - * @param second the second argument. - * @param consumer the function. - */ - default void forEachF( - float first, - F second, - NotNullFloatBiObjectConsumer consumer) { - - var array = array(); - - for (int i = 0, length = size(); i < length; i++) { - consumer.accept(first, second, array[i]); - } - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayCollectors.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayCollectors.java deleted file mode 100644 index 98ef7a87..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayCollectors.java +++ /dev/null @@ -1,144 +0,0 @@ -package javasabr.rlib.common.util.array; - -import static java.util.Collections.unmodifiableSet; - -import java.util.Collection; -import java.util.EnumSet; -import java.util.Set; -import java.util.function.BiConsumer; -import java.util.function.BinaryOperator; -import java.util.function.Function; -import java.util.function.Supplier; -import java.util.stream.Collector; -import org.jspecify.annotations.NullMarked; - -/** - * The array collectors factory. - * - * @author JavaSaBr - */ -@NullMarked -public class ArrayCollectors { - - private static Set CH_ID = - unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH)); - - private static Set CH_ID_CONC = unmodifiableSet(EnumSet.of( - Collector.Characteristics.IDENTITY_FINISH, - Collector.Characteristics.CONCURRENT)); - - /** - * Get a collector to collect elements into an array. - * - * @param type the type of elements. - * @param arrayFactory the array factory. - * @param the array element's type. - * @param the array's type. - * @return the collector. - */ - public static > Collector collector( - Class type, - Function, A> arrayFactory) { - return new Collector<>() { - - private final Supplier supplier = () -> arrayFactory.apply(type); - - @Override - public Supplier supplier() { - return supplier; - } - - @Override - public BiConsumer accumulator() { - return Collection::add; - } - - @Override - public BinaryOperator combiner() { - return (source, toAdd) -> { - source.addAll(toAdd); - return source; - }; - } - - @Override - public Function finisher() { - return array -> array; - } - - @Override - public Set characteristics() { - return CH_ID; - } - }; - } - - /** - * Get a collector to collect elements in a thread safe array. - * - * @param type the type of elements. - * @param arrayFactory the array factory. - * @param the array element's type. - * @param the array's type. - * @return the collector. - */ - public static > Collector concurrentCollector( - Class type, - Function, A> arrayFactory) { - return new Collector<>() { - - private final Supplier supplier = () -> arrayFactory.apply(type); - - @Override - public Supplier supplier() { - return supplier; - } - - @Override - public BiConsumer accumulator() { - return Collection::add; - } - - @Override - public BinaryOperator combiner() { - return (source, toAdd) -> { - source.runInWriteLock(toAdd, Array::addAll); - return source; - }; - } - - @Override - public Function finisher() { - return array -> array; - } - - @Override - public Set characteristics() { - return CH_ID_CONC; - } - }; - } - - /** - * Get a collector to collect elements into an array. - * - * @param type the type of elements. - * @param the array element's type. - * @return the collector. - */ - public static Collector, Array> toArray(Class type) { - return collector(type, ArrayFactory::newArray); - } - - /** - * Get a collector to collect elements in a thread safe array. - * - * @param type the type of elements. - * @param the array element's type. - * @return the collector. - */ - public static Collector, ConcurrentArray> toConcurrentArray( - Class type) { - return concurrentCollector(type, ArrayFactory::newConcurrentStampedLockArray); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayComparator.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayComparator.java deleted file mode 100644 index 48d3d760..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayComparator.java +++ /dev/null @@ -1,37 +0,0 @@ -package javasabr.rlib.common.util.array; - -import java.util.Comparator; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -/** - * The interface to implement a comparator for {@link Array}. - * - * @param the type parameter - * @author JavaSaBr - */ -@NullMarked -public interface ArrayComparator extends Comparator { - - @Override - default int compare(@Nullable T left, @Nullable T right) { - - if (left == null) { - return 1; - } else if (right == null) { - return -1; - } - - return compareImpl(left, right); - } - - /** - * Compare the two objects. - * - * @param first the first. - * @param second 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. - */ - int compareImpl(T first, T second); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayFactory.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayFactory.java deleted file mode 100644 index 3f6bd4e3..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayFactory.java +++ /dev/null @@ -1,87 +0,0 @@ -package javasabr.rlib.common.util.array; - -import static javasabr.rlib.common.util.ClassUtils.unsafeNNCast; - -import javasabr.rlib.common.util.ArrayUtils; -import javasabr.rlib.common.util.array.impl.ConcurrentStampedLockArray; -import javasabr.rlib.common.util.array.impl.CopyOnModifyArray; -import javasabr.rlib.common.util.array.impl.FastArray; -import javasabr.rlib.common.util.array.impl.ReadOnlyFastArray; -import org.jspecify.annotations.NullMarked; - -/** - * The factory to create different kinds of arrays. - * - * @author JavaSaBr - */ -@NullMarked -public class ArrayFactory { - - public static final Array EMPTY_ARRAY = newReadOnlyArray(ArrayUtils.EMPTY_OBJECT_ARRAY); - - @SafeVarargs - public static Array asArray(E... args) { - return new FastArray<>(args); - } - - public static Array newArray(Class type) { - return newUnsafeArray(type); - } - - public static Array newArray(Class type, int capacity) { - return newUnsafeArray(type, capacity); - } - - public static Array newCopyOnModifyArray(Class type) { - return new CopyOnModifyArray<>(type, 0); - } - - public static UnsafeArray newUnsafeArray(Class type) { - return new FastArray<>(type); - } - - public static UnsafeArray newUnsafeArray(Class type, int capacity) { - return new FastArray<>(type, capacity); - } - - public static ReadOnlyArray newReadOnlyArray(E[] elements) { - return new ReadOnlyFastArray<>(elements); - } - - public static ConcurrentArray newConcurrentStampedLockArray(Class type) { - return new ConcurrentStampedLockArray<>(type); - } - - public static ConcurrentArray newConcurrentStampedLockArray(E [] array) { - - Class type = unsafeNNCast(array - .getClass() - .getComponentType()); - - var result = new ConcurrentStampedLockArray(type, array.length); - result.addAll(array); - - return result; - } - - public static float[] toFloatArray(float... elements) { - return elements; - } - - public static int[] toIntArray(int... elements) { - return elements; - } - - public static long[] toLongArray(long... elements) { - return elements; - } - - public static boolean[] toBooleanArray(boolean... elements) { - return elements; - } - - @SafeVarargs - public static T[] toArray(K... elements) { - return elements; - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayIterator.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayIterator.java deleted file mode 100644 index d25c72a1..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ArrayIterator.java +++ /dev/null @@ -1,24 +0,0 @@ -package javasabr.rlib.common.util.array; - -import java.util.Iterator; - -/** - * The interface for implementing an iterator for {@link Array}. - * - * @param the type parameter - * @author JavaSaBr - */ -public interface ArrayIterator extends Iterator { - - /** - * Removes the current element using reordering. - */ - void fastRemove(); - - /** - * Index int. - * - * @return the current position of this {@link Array}. - */ - int index(); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ConcurrentArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ConcurrentArray.java deleted file mode 100644 index cfc18a82..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ConcurrentArray.java +++ /dev/null @@ -1,824 +0,0 @@ -package javasabr.rlib.common.util.array; - -import java.util.function.Function; -import javasabr.rlib.common.function.BiIntPredicate; -import javasabr.rlib.common.function.NotNullBiConsumer; -import javasabr.rlib.common.function.NotNullBiPredicate; -import javasabr.rlib.common.function.NotNullConsumer; -import javasabr.rlib.common.function.NotNullFunction; -import javasabr.rlib.common.function.NotNullFunctionInt; -import javasabr.rlib.common.function.NotNullIntBiObjectConsumer; -import javasabr.rlib.common.function.NotNullIntObjectPredicate; -import javasabr.rlib.common.function.NotNullNullableBiFunction; -import javasabr.rlib.common.function.NotNullNullableFunction; -import javasabr.rlib.common.function.NotNullNullableTripleFunction; -import javasabr.rlib.common.function.NotNullPredicate; -import javasabr.rlib.common.function.NotNullSupplier; -import javasabr.rlib.common.function.NotNullTripleConsumer; -import javasabr.rlib.common.util.ClassUtils; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -/** - * The interface with methods to manage thread-safe access with arrays. - * - * @param the element's type. - * @author JavaSaBr - */ -@NullMarked -public interface ConcurrentArray extends Array { - - @SafeVarargs - static ConcurrentArray of(T... elements) { - return ArrayFactory.newConcurrentStampedLockArray(elements); - } - - /** - * Create a new concurrent array for the element's type. - * - * @param type the element's type. - * @param the element's type. - * @return the new concurrent array. - */ - static ConcurrentArray ofType(Class type) { - return ArrayFactory.newConcurrentStampedLockArray(type); - } - - /** - * Create a supplier to create new arrays. - * - * @param type the element's type. - * @param the element's type. - * @return the supplier. - */ - static NotNullSupplier> supplier(Class type) { - return () -> ArrayFactory.newConcurrentStampedLockArray(type); - } - - /** - * Create a function to create new arrays. - * - * @param the element's type. - * @return the supplier. - */ - static Function, ConcurrentArray> function() { - return ArrayFactory::newConcurrentStampedLockArray; - } - - /** - * Create a function to create new arrays. - * - * @param type the element's type. - * @param the element's type. - * @return the supplier. - */ - static Function, ConcurrentArray> function(Class type) { - return aClass -> ArrayFactory.newConcurrentStampedLockArray(ClassUtils.>unsafeNNCast(type)); - } - - /** - * Lock this array for reading. - * - * @return the stamp of read lock or 0. - */ - default long readLock() { - throw new UnsupportedOperationException(); - } - - /** - * Unlock the read lock. - * - * @param stamp the stamp of read lock. - */ - default void readUnlock(long stamp) { - throw new UnsupportedOperationException(); - } - - /** - * Try to optimistic read. - * - * @return the stamp of optimistic read or 0 if it was failed. - */ - default long tryOptimisticRead() { - throw new UnsupportedOperationException(); - } - - /** - * Validate this stamp. - * - * @param stamp the stamp. - * @return true is this stamp is valid. - */ - default boolean validate(long stamp) { - throw new UnsupportedOperationException(); - } - - /** - * Lock this array for writing. - * - * @return the stamp of write lock or 0. - */ - default long writeLock() { - throw new UnsupportedOperationException(); - } - - /** - * Unlock the write lock. - * - * @param stamp the stamp of write lock. - */ - default void writeUnlock(long stamp) { - throw new UnsupportedOperationException(); - } - - /** - * Apply a function to each element under {@link #readLock()} block. - * - * @param consumer the consumer. - * @return this array. - */ - default ConcurrentArray forEachInReadLock(NotNullConsumer consumer) { - - var stamp = readLock(); - try { - forEach(consumer); - } finally { - readUnlock(stamp); - } - - return this; - } - - /** - * Apply a function to each element under {@link #readLock()} block. - * - * @param argument the argument. - * @param function the function. - * @param the argument's type. - * @return this array. - */ - default ConcurrentArray forEachInReadLock( - T argument, - NotNullBiConsumer function) { - - var stamp = readLock(); - try { - forEach(argument, function); - } finally { - readUnlock(stamp); - } - - return this; - } - - /** - * Apply a function to each element under {@link #readLock()} block. - * - * @param first the first argument. - * @param second the second argument. - * @param consumer the function. - * @param the second argument's type. - * @return this array. - */ - default ConcurrentArray forEachInReadLock( - int first, - A second, - NotNullIntBiObjectConsumer consumer) { - - var stamp = readLock(); - try { - forEach(first, second, consumer); - } finally { - readUnlock(stamp); - } - - return this; - } - - /** - * Apply a function to each element under {@link #readLock()} block. - * - * @param first the first argument. - * @param second the second argument. - * @param consumer the function. - * @param the firs argument's type. - * @param the second argument's type. - * @return this array. - */ - default ConcurrentArray forEachInReadLock( - F first, - S second, - NotNullTripleConsumer consumer) { - - var stamp = readLock(); - try { - forEach(first, second, consumer); - } finally { - readUnlock(stamp); - } - - return this; - } - - /** - * Apply a function to each element under {@link #readLock()} block. - * - * @param argument the argument. - * @param function the function. - * @param the argument's type. - * @return this array. - */ - default ConcurrentArray forEachInReadLockR( - T argument, - NotNullBiConsumer function) { - - var stamp = readLock(); - try { - forEachR(argument, function); - } finally { - readUnlock(stamp); - } - - return this; - } - - /** - * Apply a function to each converted element under {@link #readLock()} block. - * - * @param argument the argument. - * @param converter the converter from T to C. - * @param function the function. - * @param the argument's type. - * @param the converted type. - * @return this array. - */ - default ConcurrentArray forEachConvertedInReadLock( - T argument, - NotNullFunction converter, - NotNullBiConsumer function) { - - var stamp = readLock(); - try { - forEachConverted(argument, converter, function); - } finally { - readUnlock(stamp); - } - - return this; - } - - /** - * Apply a function to each converted element under {@link #readLock()} block. - * - * @param first the first argument. - * @param second the second argument. - * @param converter the converter from E to C. - * @param function the function. - * @param the first argument's type. - * @param the second argument's type. - * @param the converted type. - * @return this array. - * @since 9.8.0 - */ - default ConcurrentArray forEachConvertedInReadLock( - F first, - S second, - NotNullFunction converter, - NotNullTripleConsumer function) { - - var stamp = readLock(); - try { - forEachConverted(first, second, converter, function); - } finally { - readUnlock(stamp); - } - - return this; - } - - /** - * Apply a function to each element and converted argument under {@link #readLock()} block. - * - * @param argument the argument. - * @param converter the converter from T to C. - * @param function the function. - * @param the argument's type. - * @param the converted type. - * @return this array. - */ - default ConcurrentArray forEachInReadLock( - T argument, - NotNullFunction converter, - NotNullBiConsumer function) { - - var stamp = readLock(); - try { - forEach(argument, converter, function); - } finally { - readUnlock(stamp); - } - - return this; - } - - /** - * Execute a function to get some result under {@link #readLock()} block. - * - * @param function the function. - * @param the result's type. - * @return the result from the function. - */ - default @Nullable R getInReadLock(NotNullNullableFunction, R> function) { - var stamp = readLock(); - try { - return function.apply(this); - } finally { - readUnlock(stamp); - } - } - - /** - * Execute a function to get some result under {@link #readLock()} block. - * - * @param arg the argument for the function. - * @param function the function. - * @param the argument's type. - * @param the result's type. - * @return the result from the function. - * @since 9.5.0 - */ - default @Nullable R getInReadLock( - A arg, - NotNullNullableBiFunction, A, R> function) { - var stamp = readLock(); - try { - return function.apply(this, arg); - } finally { - readUnlock(stamp); - } - } - - /** - * Execute a function to get some result under {@link #readLock()} block. - * - * @param first the first argument for the function. - * @param second the second argument for the function. - * @param function the function. - * @param the first argument's type. - * @param the second argument's type. - * @param the result's type. - * @return the result from the function. - * @since 9.9.0 - */ - default @Nullable R getInReadLock( - A first, - T second, - NotNullNullableTripleFunction, A, T, R> function) { - var stamp = readLock(); - try { - return function.apply(this, first, second); - } finally { - readUnlock(stamp); - } - } - - /** - * Execute a function to get some result under {@link #writeLock()} block. - * - * @param function the function. - * @param the result's type. - * @return the result from the function. - */ - default @Nullable R getInWriteLock(NotNullNullableFunction, R> function) { - var stamp = writeLock(); - try { - return function.apply(this); - } finally { - writeUnlock(stamp); - } - } - - /** - * Execute a function to get some result under {@link #writeLock()} block. - * - * @param argument the argument for the function. - * @param function the function. - * @param the argument's type. - * @param the result's type. - * @return the result from the function. - * @since 9.5.0 - */ - default @Nullable R getInWriteLock( - A argument, - NotNullNullableBiFunction, A, R> function) { - var stamp = writeLock(); - try { - return function.apply(this, argument); - } finally { - writeUnlock(stamp); - } - } - - /** - * Execute a function to get some result under {@link #writeLock()} block. - * - * @param first the first argument for the function. - * @param second the second argument for the function. - * @param function the function. - * @param the first argument's type. - * @param the second argument's type. - * @param the result's type. - * @return the result from the function. - * @since 9.9.0 - */ - default @Nullable R getInWriteLock( - A first, - T second, - NotNullNullableTripleFunction, A, T, R> function) { - var stamp = writeLock(); - try { - return function.apply(this, first, second); - } finally { - writeUnlock(stamp); - } - } - - /** - * Execute a function under {@link #readLock()} block. - * - * @param function the function. - * @return this array. - */ - default ConcurrentArray runInReadLock(NotNullConsumer> function) { - - var stamp = readLock(); - try { - function.accept(this); - } finally { - readUnlock(stamp); - } - - return this; - } - - /** - * Execute a function under {@link #readLock()} block. - * - * @param the argument's type. - * @param argument the argument. - * @param function the function. - * @return this array. - */ - default ConcurrentArray runInReadLock( - F argument, - NotNullBiConsumer, F> function) { - - var stamp = readLock(); - try { - function.accept(this, argument); - } finally { - readUnlock(stamp); - } - - return this; - } - - /** - * Execute a function under {@link #readLock()} block. - * - * @param the first argument's type. - * @param the second argument's type. - * @param first the first argument. - * @param second the second argument. - * @param function the function. - * @return this array. - * @since 9.9.0 - */ - default ConcurrentArray runInReadLock( - A first, - T second, - NotNullTripleConsumer, A, T> function) { - - var stamp = readLock(); - try { - function.accept(this, first, second); - } finally { - readUnlock(stamp); - } - - return this; - } - - /** - * Execute a function under {@link #writeLock()} block. - * - * @param function the function. - * @return this array. - */ - default ConcurrentArray runInWriteLock(NotNullConsumer> function) { - - var stamp = writeLock(); - try { - function.accept(this); - } finally { - writeUnlock(stamp); - } - - return this; - } - - /** - * Execute a function under {@link #writeLock()} block. - * - * @param the argument's type. - * @param argument the argument. - * @param function the function. - * @return this array. - */ - default ConcurrentArray runInWriteLock( - F argument, - NotNullBiConsumer, F> function) { - - var stamp = writeLock(); - try { - function.accept(this, argument); - } finally { - writeUnlock(stamp); - } - - return this; - } - - /** - * Execute a function under {@link #writeLock()} block. - * - * @param first the first argument for the function. - * @param second the second argument for the function. - * @param function the function. - * @param the first argument's type. - * @param the second argument's type. - * @return this array. - * @since 9.9.0 - */ - default ConcurrentArray runInWriteLock( - A first, - T second, - NotNullTripleConsumer, A, T> function) { - var stamp = writeLock(); - try { - function.accept(this, first, second); - } finally { - writeUnlock(stamp); - } - return this; - } - - /** - * Search an element using the condition under {@link #readLock()} block. - * - * @param argument the argument. - * @param filter the condition. - * @return the found element or null. - * @since 9.5.0 - */ - default @Nullable E findAnyInReadLock(int argument, NotNullIntObjectPredicate filter) { - - if (isEmpty()) { - return null; - } - - var stamp = readLock(); - try { - return findAny(argument, filter); - } finally { - readUnlock(stamp); - } - } - - /** - * Search an element using the condition by converted value under {@link #readLock()} block. - * - * @param argument the argument. - * @param converter the converted an element to another type. - * @param filter the condition. - * @param the argument's type. - * @param the converted element's type. - * @return the found element or null. - * @since 9.7.0 - */ - default @Nullable E findAnyConvertedInReadLock( - T argument, - NotNullFunction converter, - NotNullBiPredicate filter) { - if (isEmpty()) { - return null; - } - - var stamp = readLock(); - try { - return findAnyConverted(argument, converter, filter); - } finally { - readUnlock(stamp); - } - } - - /** - * Search a converted element to int using the condition under {@link #readLock()} block. - * - * @param argument the argument. - * @param converter the converter element to int. - * @param filter the condition. - * @return the found element or null. - * @since 9.6.0 - */ - default @Nullable E findAnyConvertedToIntInReadLock( - int argument, - NotNullFunctionInt converter, - BiIntPredicate filter) { - if (isEmpty()) { - return null; - } - - var stamp = readLock(); - try { - return findAnyConvertedToInt(argument, converter, filter); - } finally { - readUnlock(stamp); - } - } - - /** - * Search a converted element to int using the condition under {@link #readLock()} block. - * - * @param argument the argument. - * @param firstConverter the converter element to T. - * @param secondConverter the converter element to int. - * @param filter the condition. - * @param the first converted type. - * @return the found element or null. - * @since 9.7.0 - */ - default @Nullable E findAnyConvertedToIntInReadLock( - int argument, - NotNullFunction firstConverter, - NotNullFunctionInt secondConverter, - BiIntPredicate filter) { - if (isEmpty()) { - return null; - } - - var stamp = readLock(); - try { - return findAnyConvertedToInt(argument, firstConverter, secondConverter, filter); - } finally { - readUnlock(stamp); - } - } - - /** - * Search an element by condition under {@link #readLock()} block. - * - * @param the argument's type. - * @param argument the argument. - * @param filter the condition. - * @return true if there is at least an element for the condition. - */ - default boolean anyMatchInReadLock(T argument, NotNullBiPredicate filter) { - - if (isEmpty()) { - return false; - } - - var stamp = readLock(); - try { - return anyMatch(argument, filter); - } finally { - readUnlock(stamp); - } - } - - /** - * Search an element by condition under {@link #readLock()} block. - * - * @param argument the argument. - * @param filter the condition. - * @return true if there is at least an element for the condition. - */ - default boolean anyMatchInReadLock(int argument, NotNullIntObjectPredicate filter) { - - if (isEmpty()) { - return false; - } - - var stamp = readLock(); - try { - return anyMatch(argument, filter); - } finally { - readUnlock(stamp); - } - } - - /** - * Return true if there is at least a converted element for the condition under {@link #readLock()} block. - * - * @param argument the argument. - * @param converter the converter element to another type. - * @param filter the condition. - * @param the argument's type. - * @param the converted element's type. - * @return true if there is at least an element for the condition. - * @since 9.7.0 - */ - default boolean anyMatchConvertedInReadLock( - T argument, - NotNullFunction converter, - NotNullBiPredicate filter) { - if (isEmpty()) { - return false; - } - - var stamp = readLock(); - try { - return anyMatchConverted(argument, converter, filter); - } finally { - readUnlock(stamp); - } - } - - /** - * Removes all of the elements of this collection that satisfy the given predicate under {@link #writeLock()} block. - * - * @param filter the predicate which returns {@code true} for elements to be removed. - * @return {@code true} if any elements were removed. - */ - default boolean removeIfInWriteLock(NotNullPredicate filter) { - var stamp = writeLock(); - try { - return removeIf(filter); - } finally { - writeUnlock(stamp); - } - } - - /** - * Removes all of the elements of this collection that satisfy the given predicate under {@link #writeLock()} block. - * - * @param argument the additional argument. - * @param filter the predicate which returns {@code true} for elements to be removed. - * @param the argument's type. - * @return {@code true} if any elements were removed. - */ - default boolean removeIfInWriteLock(A argument, NotNullBiPredicate filter) { - var stamp = writeLock(); - try { - return removeIf(argument, filter); - } finally { - writeUnlock(stamp); - } - } - - /** - * Removes all of the elements of this collection that satisfy the given predicate under {@link #writeLock()} block. - * - * @param argument the additional argument. - * @param converter the converter of the argument. - * @param filter the predicate which returns {@code true} for elements to be removed. - * @param the argument's type. - * @param the argument converted type. - * @return {@code true} if any elements were removed. - */ - default boolean removeIfInWriteLock( - A argument, - NotNullFunction converter, - NotNullBiPredicate filter) { - var stamp = writeLock(); - try { - return removeIf(argument, converter, filter); - } finally { - writeUnlock(stamp); - } - } - - /** - * Removes all of the elements of this collection that satisfy the given predicate. - * - * @param argument the additional argument. - * @param converter the converter of the elements. - * @param filter the predicate which returns {@code true} for elements to be removed. - * @param the argument's type. - * @param the element converted type. - * @return {@code true} if any elements were removed. - * @since 9.6.0 - */ - default boolean removeIfConvertedInWriteLock( - A argument, - NotNullFunction converter, - NotNullBiPredicate filter) { - var stamp = writeLock(); - try { - return removeIfConverted(argument, converter, filter); - } finally { - writeUnlock(stamp); - } - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ReadOnlyArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/ReadOnlyArray.java deleted file mode 100644 index 26c7d7ed..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/ReadOnlyArray.java +++ /dev/null @@ -1,81 +0,0 @@ -package javasabr.rlib.common.util.array; - -import java.util.Collection; -import java.util.function.Function; -import java.util.function.Predicate; -import javasabr.rlib.common.util.array.impl.ReadOnlyFastArray; -import org.jspecify.annotations.NullMarked; - -/** - * The interface to mark an array as read only array. - * - * @param the element's type. - * @author JavaSaBr - */ -@NullMarked -public interface ReadOnlyArray extends Array { - - static ReadOnlyArray wrap(Array array) { - return new ReadOnlyFastArray<>(array.toArray()); - } - - @Override - @Deprecated - void apply(Function function); - - @Override - @Deprecated - boolean add(E e); - - @Override - @Deprecated - boolean addAll(E[] array); - - @Override - @Deprecated - boolean addAll(Array array); - - @Override - @Deprecated - boolean addAll(Collection c); - - @Override - @Deprecated - boolean fastRemove(Object object); - - @Override - @Deprecated - E remove(int index); - - @Override - @Deprecated - boolean removeIf(Predicate filter); - - @Override - @Deprecated - boolean retainAll(Collection target); - - @Override - @Deprecated - boolean retainAll(Array target); - - @Override - @Deprecated - boolean removeAll(Collection target); - - @Override - @Deprecated - boolean removeAll(Array target); - - @Override - @Deprecated - boolean remove(Object object); - - @Override - @Deprecated - void clear(); - - @Override - @Deprecated - Array sort(ArrayComparator comparator); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/UnsafeArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/UnsafeArray.java deleted file mode 100644 index b98870b1..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/UnsafeArray.java +++ /dev/null @@ -1,60 +0,0 @@ -package javasabr.rlib.common.util.array; - -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -/** - * The interface with unsafe methods for the Array. - * - * @param the element's type. - * @author JavaSaBr - */ -@NullMarked -public interface UnsafeArray extends Array { - - /** - * Prepare this array for the target size. - * - * @param size the size. - */ - default void prepareForSize(int size) { - throw new UnsupportedOperationException(); - } - - /** - * Add the new element without any checks. - * - * @param object the new element. - * @return true if this array was changed. - */ - default boolean unsafeAdd(E object) { - throw new UnsupportedOperationException(); - } - - /** - * Get the element for the index without any checks. - * - * @param index the index. - * @return the element or null. - */ - default @Nullable E unsafeGet(int index) { - throw new UnsupportedOperationException(); - } - - /** - * Set the element for the index without any checks. - * - * @param index the index. - * @param element the element. - */ - default void unsafeSet(int index, E element) { - throw new UnsupportedOperationException(); - } - - /** - * Reduce wrapped array to size of this array. - * - * @return the array - */ - Array trimToSize(); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/AbstractArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/AbstractArray.java deleted file mode 100644 index d27541ba..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/AbstractArray.java +++ /dev/null @@ -1,96 +0,0 @@ -package javasabr.rlib.common.util.array.impl; - -import java.io.Serial; -import java.util.Arrays; -import java.util.Objects; -import java.util.function.Function; -import javasabr.rlib.common.util.ArrayUtils; -import javasabr.rlib.common.util.ClassUtils; -import javasabr.rlib.common.util.array.Array; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -/** - * The base implementation of dynamic arrays. - * - * @param the array's element type. - * @author JavaSaBr - */ -@NullMarked -public abstract class AbstractArray implements Array { - - @Serial - private static final long serialVersionUID = 2113052245369887690L; - - /** - * The default size of new backend array. - */ - protected static final int DEFAULT_CAPACITY = 10; - - public AbstractArray(Class type) { - this(type, DEFAULT_CAPACITY); - } - - public AbstractArray(Class type, int capacity) { - super(); - - if (capacity < 0) { - throw new IllegalArgumentException("Negative capacity"); - } - - setArray(ArrayUtils.create(type, capacity)); - } - - public AbstractArray(E[] array) { - super(); - setArray(array); - setSize(array.length); - } - - @Override - public void clear() { - if (!isEmpty()) { - ArrayUtils.clear(array()); - setSize(0); - } - } - - @Override - public AbstractArray clone() throws CloneNotSupportedException { - return ClassUtils.unsafeNNCast(super.clone()); - } - - protected abstract void setArray(E [] array); - - protected abstract void setSize(int size); - - @Override - public String toString() { - return ArrayUtils.toString(this); - } - - @Override - public String toString(Function toString) { - return ArrayUtils.toString(this, toString); - } - - @Override - public boolean equals(@Nullable Object another) { - - if (this == another) { - return true; - } else if (!(another instanceof Array)) { - return false; - } - - var array = (Array) another; - return size() == array.size() && Arrays.equals(array(), 0, size(), array.array(), 0, array.size()); - } - - @Override - public int hashCode() { - int result = Objects.hash(size()); - result = 31 * result + Arrays.hashCode(array()); - return result; - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/AbstractConcurrentArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/AbstractConcurrentArray.java deleted file mode 100644 index ae988569..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/AbstractConcurrentArray.java +++ /dev/null @@ -1,285 +0,0 @@ -package javasabr.rlib.common.util.array.impl; - -import static java.lang.Math.max; - -import java.io.Serial; -import java.util.Collection; -import java.util.NoSuchElementException; -import java.util.concurrent.atomic.AtomicInteger; -import javasabr.rlib.common.util.ArrayUtils; -import javasabr.rlib.common.util.array.Array; -import javasabr.rlib.common.util.array.ArrayIterator; -import javasabr.rlib.common.util.array.ConcurrentArray; -import javasabr.rlib.common.util.array.UnsafeArray; -import org.jspecify.annotations.NullMarked; - -/** - * The base concurrent implementation of dynamic arrays. - * - * @param the array's element type. - * @author JavaSaBr - */ -@NullMarked -@SuppressWarnings("NonAtomicOperationOnVolatileField") -public abstract class AbstractConcurrentArray extends AbstractArray implements ConcurrentArray, - UnsafeArray { - - @Serial - private static final long serialVersionUID = -6291504312637658721L; - - /** - * The count of elements in this array. - */ - private final AtomicInteger size; - - /** - * The unsafe array. - */ - @SuppressWarnings("NullableProblems") - private volatile E [] array; - - public AbstractConcurrentArray(Class type) { - this(type, 10); - } - - public AbstractConcurrentArray(Class type, int size) { - super(type, size); - this.size = new AtomicInteger(); - } - - @Override - public boolean add(E element) { - - if (size() == array.length) { - array = ArrayUtils.copyOfAndExtend(array, Math.max(array.length >> 1, 1)); - } - - array[size.getAndIncrement()] = element; - return true; - } - - @Override - public final boolean addAll(Array elements) { - - if (elements.isEmpty()) { - return false; - } - - var current = array.length; - var selfSize = size(); - var targetSize = elements.size(); - var diff = selfSize + targetSize - current; - - if (diff > 0) { - array = ArrayUtils.copyOfAndExtend(array, max(current >> 1, diff)); - } - - processAdd(elements, selfSize, targetSize); - return true; - } - - @Override - public boolean addAll(Collection collection) { - - if (collection.isEmpty()) { - return false; - } - - var current = array.length; - var diff = size() + collection.size() - current; - - if (diff > 0) { - array = ArrayUtils.copyOfAndExtend(array, Math.max(current >> 1, diff)); - } - - for (var element : collection) { - unsafeAdd(element); - } - - return true; - } - - @Override - public final boolean addAll(E[] elements) { - - if (elements.length < 1) { - return false; - } - - var current = array.length; - var selfSize = size(); - var targetSize = elements.length; - var diff = selfSize + targetSize - current; - - if (diff > 0) { - array = ArrayUtils.copyOfAndExtend(array, max(current >> 1, diff)); - } - - processAdd(elements, selfSize, targetSize); - return true; - } - - @Override - public final E[] array() { - return array; - } - - @Override - public void prepareForSize(int size) { - - var current = array.length; - var selfSize = size(); - var diff = selfSize + size - current; - - if (diff > 0) { - array = ArrayUtils.copyOfAndExtend(array, Math.max(current >> 1, diff)); - } - } - - @Override - public final E fastRemove(int index) { - - if (index < 0 || index >= size()) { - throw new NoSuchElementException(); - } - - var newSize = size.decrementAndGet(); - var old = array[index]; - - array[index] = array[newSize]; - array[newSize] = null; - - return old; - } - - @Override - public final E get(int index) { - - if (index < 0 || index >= size()) { - throw new NoSuchElementException(); - } - - return array[index]; - } - - @Override - public final ArrayIterator iterator() { - return new DefaultArrayIterator<>(this); - } - - @Override - public void replace(int index, E element) { - - if (index < 0 || index >= size()) { - throw new ArrayIndexOutOfBoundsException(); - } - - array[index] = element; - } - - @Override - protected final void setArray(E [] array) { - this.array = array; - } - - @Override - protected final void setSize(final int size) { - this.size.getAndSet(size); - } - - @Override - public final int size() { - return size.get(); - } - - @Override - public E remove(int index) { - - if (index < 0 || index >= size()) { - throw new ArrayIndexOutOfBoundsException(); - } - - var length = size(); - var numMoved = length - index - 1; - - var old = array[index]; - - if (numMoved > 0) { - System.arraycopy(array, index + 1, array, index, numMoved); - } - - array[size.decrementAndGet()] = null; - return old; - } - - @Override - public final AbstractConcurrentArray trimToSize() { - - var size = size(); - - if (size == array.length) { - return this; - } - - array = ArrayUtils.copyOfRange(array, 0, size); - return this; - } - - @Override - public boolean unsafeAdd(E object) { - array[size.getAndIncrement()] = object; - return true; - } - - @Override - public E unsafeGet(int index) { - return array[index]; - } - - @Override - public void unsafeSet(final int index, final E element) { - - if (array[index] != null) { - size.decrementAndGet(); - } - - array[index] = element; - size.incrementAndGet(); - } - - /** - * Process of adding the elements. - * - * @param elements the elements - * @param selfSize the self size - * @param targetSize the target size - */ - protected void processAdd(Array elements, int selfSize, int targetSize) { - System.arraycopy(elements.array(), 0, array, selfSize, targetSize); - size.set(selfSize + targetSize); - } - - /** - * Process of adding the elements. - * - * @param elements the elements - * @param selfSize the self size - * @param targetSize the target size - */ - protected void processAdd(E[] elements, int selfSize, int targetSize) { - System.arraycopy(elements, 0, array, selfSize, targetSize); - size.set(selfSize + targetSize); - } - - @Override - public UnsafeArray asUnsafe() { - return this; - } - - @Override - public AbstractConcurrentArray clone() throws CloneNotSupportedException { - var clone = (AbstractConcurrentArray) super.clone(); - clone.array = ArrayUtils.copyOfAndExtend(array, size()); - return clone; - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentStampedLockArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentStampedLockArray.java deleted file mode 100644 index 7b0edcb1..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentStampedLockArray.java +++ /dev/null @@ -1,59 +0,0 @@ -package javasabr.rlib.common.util.array.impl; - -import java.util.concurrent.locks.StampedLock; -import javasabr.rlib.common.util.array.ConcurrentArray; -import org.jspecify.annotations.NullMarked; - -/** - * The concurrent implementation of array using {@link StampedLock} for {@link ConcurrentArray#readLock()} and - * {@link ConcurrentArray#writeLock()}. - * - * @param the element's type. - * @author JavaSaBr - */ -@NullMarked -public class ConcurrentStampedLockArray extends AbstractConcurrentArray { - - private static final long serialVersionUID = -6291504312637658721L; - - private final StampedLock lock; - - public ConcurrentStampedLockArray(Class type) { - this(type, 10); - } - - public ConcurrentStampedLockArray(Class type, int size) { - super(type, size); - this.lock = new StampedLock(); - } - - @Override - public final long readLock() { - return lock.readLock(); - } - - @Override - public final long tryOptimisticRead() { - return lock.tryOptimisticRead(); - } - - @Override - public final boolean validate(long stamp) { - return lock.validate(stamp); - } - - @Override - public final void readUnlock(long stamp) { - lock.unlockRead(stamp); - } - - @Override - public final long writeLock() { - return lock.writeLock(); - } - - @Override - public final void writeUnlock(long stamp) { - lock.unlockWrite(stamp); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentStampedLockArraySet.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentStampedLockArraySet.java deleted file mode 100644 index ef36b96a..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ConcurrentStampedLockArraySet.java +++ /dev/null @@ -1,52 +0,0 @@ -package javasabr.rlib.common.util.array.impl; - -import java.util.concurrent.locks.StampedLock; -import javasabr.rlib.common.util.array.Array; -import javasabr.rlib.common.util.array.ConcurrentArray; -import org.jspecify.annotations.NullMarked; - -/** - * The concurrent implementation of the array without duplications using {@link StampedLock} for - * {@link ConcurrentArray#readLock()}* and {@link ConcurrentArray#writeLock()}. - * - * @param the array's element type. - * @author JavaSaBr - */ -@NullMarked -public class ConcurrentStampedLockArraySet extends ConcurrentStampedLockArray { - - private static final long serialVersionUID = -6291504312637658721L; - - public ConcurrentStampedLockArraySet(Class type) { - this(type, 10); - } - - public ConcurrentStampedLockArraySet(Class type, int size) { - super(type, size); - } - - @Override - public boolean add(E element) { - return !contains(element) && super.add(element); - } - - @Override - protected void processAdd(Array elements, int selfSize, int targetSize) { - var array = elements.array(); - for (int i = 0, length = elements.size(); i < length; i++) { - E element = array[i]; - if (!contains(element)) { - unsafeAdd(element); - } - } - } - - @Override - protected void processAdd(E[] elements, int selfSize, int targetSize) { - for (E element : elements) { - if (!contains(element)) { - unsafeAdd(element); - } - } - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/CopyOnModifyArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/CopyOnModifyArray.java deleted file mode 100644 index c6f16cdc..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/CopyOnModifyArray.java +++ /dev/null @@ -1,275 +0,0 @@ -package javasabr.rlib.common.util.array.impl; - -import java.util.Collection; -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.concurrent.atomic.AtomicReference; -import javasabr.rlib.common.util.ArrayUtils; -import javasabr.rlib.common.util.array.Array; -import javasabr.rlib.common.util.array.ArrayComparator; -import javasabr.rlib.common.util.array.ArrayFactory; -import org.jspecify.annotations.NullMarked; - -/** - * The implementation of the array which create a new back-end array for each modification. Thread-safe. - * - * @param the array's element type. - * @author JavaSaBr - */ -@NullMarked -public class CopyOnModifyArray extends AbstractArray { - - private static final long serialVersionUID = -8477384427415127978L; - - @SuppressWarnings("NullableProblems") - protected volatile AtomicReference array; - - public CopyOnModifyArray(Class type, int size) { - super(type, size); - } - - @Override - public boolean add(E object) { - - var current = array.get(); - var newArray = ArrayUtils.copyOfAndExtend(current, 1); - newArray[current.length] = object; - - if (!array.compareAndSet(current, newArray)) { - return add(object); - } - - return true; - } - - @Override - public boolean addAll(Array elements) { - - if (elements.isEmpty()) { - return false; - } - - var current = array.get(); - var newArray = ArrayUtils.copyOfAndExtend(current, elements.size()); - - for (int i = current.length, g = 0; i < newArray.length; i++, g++) { - newArray[i] = elements.get(g); - } - - if (!array.compareAndSet(current, newArray)) { - return addAll(elements); - } - - return true; - } - - @Override - public boolean addAll(Collection collection) { - - if (collection.isEmpty()) { - return false; - } - - var current = array.get(); - var newArray = ArrayUtils.copyOfAndExtend(current, collection.size()); - - Iterator iterator = collection.iterator(); - - for (int i = current.length; i < newArray.length; i++) { - newArray[i] = iterator.next(); - } - - if (!array.compareAndSet(current, newArray)) { - return addAll(collection); - } - - return true; - } - - @Override - public boolean addAll(E[] elements) { - - if (elements.length < 1) { - return false; - } - - var current = array.get(); - var newArray = ArrayUtils.combine(current, elements); - - if (!array.compareAndSet(current, newArray)) { - return addAll(elements); - } - - return true; - } - - @Override - public final E[] array() { - return array.get(); - } - - @Override - public E remove(int index) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean removeAll(Array target) { - - if (target.isEmpty()) { - return false; - } - - var current = array(); - var modifiable = ArrayFactory.asArray(current); - - if (!modifiable.removeAll(target)) { - return false; - } - - var newArray = modifiable.toArray(); - - if (!array.compareAndSet(current, newArray)) { - return removeAll(target); - } - - return true; - } - - @Override - public boolean removeAll(Collection target) { - - if (target.isEmpty()) { - return false; - } - - var current = array(); - var modifiable = ArrayFactory.asArray(current); - - if (!modifiable.removeAll(target)) { - return false; - } - - var newArray = modifiable.toArray(); - - if (!array.compareAndSet(current, newArray)) { - return removeAll(target); - } - - return true; - } - - @Override - public boolean remove(Object object) { - - var current = array.get(); - var index = ArrayUtils.indexOf(current, object); - - if (index == -1) { - return false; - } - - var newArray = ArrayUtils.create(current, current.length - 1); - - for (int i = 0, j = 0; i < current.length; i++, j++) { - - if (i == index) { - i++; - if (i >= current.length) { - break; - } - } - - newArray[j] = current[i]; - } - - if (!array.compareAndSet(current, newArray)) { - return fastRemove(object); - } - - return true; - } - - @Override - public boolean fastRemove(Object object) { - return remove(object); - } - - @Override - public E fastRemove(int index) { - throw new UnsupportedOperationException(); - } - - @Override - public void clear() { - - var current = array.get(); - - if (current.length < 1) { - return; - } - - var newArray = ArrayUtils.create(current, 0); - - if (!array.compareAndSet(current, newArray)) { - clear(); - } - } - - @Override - public final E get(int index) { - - if (index < 0 || index >= size()) { - throw new NoSuchElementException(); - } - - return array.get()[index]; - } - - @Override - public void replace(int index, E element) { - throw new UnsupportedOperationException(); - } - - @Override - protected final void setArray(E [] array) { - - //noinspection ConstantConditions - if (this.array == null) { - this.array = new AtomicReference<>(); - } - - this.array.set(array); - } - - @Override - protected final void setSize(int size) { - } - - @Override - public final int size() { - return array().length; - } - - @Override - public Array sort(ArrayComparator comparator) { - - var current = array(); - var newArray = ArrayUtils.copyOfAndExtend(current, 0); - - ArrayUtils.sort(newArray, 0, newArray.length, comparator); - - if (!array.compareAndSet(current, newArray)) { - return sort(comparator); - } - - return this; - } - - @Override - public CopyOnModifyArray clone() throws CloneNotSupportedException { - var clone = (CopyOnModifyArray) super.clone(); - clone.array = new AtomicReference<>(ArrayUtils.copyOf(array())); - return clone; - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/DefaultArrayIterator.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/DefaultArrayIterator.java deleted file mode 100644 index 6f5d5768..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/DefaultArrayIterator.java +++ /dev/null @@ -1,65 +0,0 @@ -package javasabr.rlib.common.util.array.impl; - -import javasabr.rlib.common.util.array.Array; -import javasabr.rlib.common.util.array.ArrayIterator; -import org.jspecify.annotations.NullMarked; - -/** - * The implementation of the unsafeArray iterator. - * - * @param the element's type. - * @author JavaSaBr - */ -@NullMarked -public class DefaultArrayIterator implements ArrayIterator { - - /** - * The array for iteration. - */ - private final Array array; - - /** - * The unsafe array for directly access. - */ - private final E[] unsafeArray; - - /** - * The current position in the array. - */ - private int ordinal; - - public DefaultArrayIterator(Array array) { - this.array = array; - this.unsafeArray = array.array(); - } - - @Override - public void fastRemove() { - array.fastRemove(--ordinal); - } - - @Override - public boolean hasNext() { - return ordinal < array.size(); - } - - @Override - public int index() { - return ordinal - 1; - } - - @Override - public E next() { - return ordinal >= unsafeArray.length ? null : unsafeArray[ordinal++]; - } - - @Override - public void remove() { - array.remove(--ordinal); - } - - @Override - public String toString() { - return "ArrayIteratorImpl{" + "array=" + array + ", ordinal=" + ordinal + '}'; - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastArray.java deleted file mode 100644 index 07920070..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastArray.java +++ /dev/null @@ -1,281 +0,0 @@ -package javasabr.rlib.common.util.array.impl; - -import static java.lang.Math.max; - -import java.util.Collection; -import java.util.NoSuchElementException; -import javasabr.rlib.common.util.ArrayUtils; -import javasabr.rlib.common.util.array.Array; -import javasabr.rlib.common.util.array.ArrayIterator; -import javasabr.rlib.common.util.array.UnsafeArray; -import org.jspecify.annotations.NullMarked; - -/** - * The fast implementation of the array. This array is not threadsafe. - * - * @param the array's element type. - * @author JavaSaBr - */ -@NullMarked -public class FastArray extends AbstractArray implements UnsafeArray { - - private static final long serialVersionUID = -8477384427415127978L; - - /** - * The unsafe array. - */ - @SuppressWarnings("NullableProblems") - protected E [] array; - - /** - * The current size of this array. - */ - protected int size; - - public FastArray(Class type) { - super(type); - } - - public FastArray(Class type, final int size) { - super(type, size); - } - - public FastArray(E[] array) { - super(array); - } - - @Override - public boolean add(E object) { - - if (size == array.length) { - array = ArrayUtils.copyOfAndExtend(array, max(array.length >> 1, 1)); - } - - return unsafeAdd(object); - } - - @Override - public boolean addAll(Array elements) { - - if (elements.isEmpty()) { - return false; - } - - int current = array.length; - int selfSize = size(); - int targetSize = elements.size(); - int diff = selfSize + targetSize - current; - - if (diff > 0) { - array = ArrayUtils.copyOfAndExtend(array, max(current >> 1, diff)); - } - - processAdd(elements, selfSize, targetSize); - return true; - } - - @Override - public boolean addAll(Collection collection) { - - if (collection.isEmpty()) { - return false; - } - - int current = array.length; - int selfSize = size(); - int targetSize = collection.size(); - int diff = selfSize + targetSize - current; - - if (diff > 0) { - array = ArrayUtils.copyOfAndExtend(array, max(current >> 1, diff)); - } - - for (E element : collection) { - unsafeAdd(element); - } - - return true; - } - - @Override - public boolean addAll(E[] elements) { - - if (elements.length < 1) { - return false; - } - - int current = array.length; - int selfSize = size(); - int targetSize = elements.length; - int diff = selfSize + targetSize - current; - - if (diff > 0) { - array = ArrayUtils.copyOfAndExtend(array, max(current >> 1, diff)); - } - - processAdd(elements, selfSize, targetSize); - return true; - } - - @Override - public final E[] array() { - return array; - } - - @Override - public void prepareForSize(int size) { - - int current = array.length; - int selfSize = size(); - int diff = selfSize + size - current; - - if (diff > 0) { - array = ArrayUtils.copyOfAndExtend(array, max(current >> 1, diff)); - } - } - - @Override - public E fastRemove(int index) { - - if (index < 0 || index >= size) { - throw new NoSuchElementException(); - } - - size -= 1; - - E old = array[index]; - - array[index] = array[size]; - array[size] = null; - - return old; - } - - @Override - public final E get(int index) { - - if (index < 0 || index >= size()) { - throw new IndexOutOfBoundsException(); - } - - return array[index]; - } - - @Override - public final ArrayIterator iterator() { - return new DefaultArrayIterator<>(this); - } - - /** - * The process of adding the array. - * - * @param elements the elements. - * @param selfSize the self size. - * @param targetSize the target size. - */ - protected void processAdd(Array elements, int selfSize, int targetSize) { - System.arraycopy(elements.array(), 0, array, selfSize, targetSize); - size = selfSize + targetSize; - } - - /** - * The process of adding the array. - * - * @param elements the elements. - * @param selfSize the self size. - * @param targetSize the target size. - */ - protected void processAdd(E[] elements, int selfSize, int targetSize) { - System.arraycopy(elements, 0, array, selfSize, targetSize); - size = selfSize + targetSize; - } - - @Override - public void replace(int index, E element) { - - if (index < 0 || index >= size) { - throw new ArrayIndexOutOfBoundsException(); - } - - array[index] = element; - } - - @Override - protected final void setArray(E [] array) { - this.array = array; - } - - @Override - protected final void setSize(int size) { - this.size = size; - } - - @Override - public final int size() { - return size; - } - - @Override - public E remove(int index) { - - if (index < 0 || index >= size) { - throw new NoSuchElementException(); - } - - int numMoved = size - index - 1; - E old = array[index]; - - if (numMoved > 0) { - System.arraycopy(array, index + 1, array, index, numMoved); - } - - size -= 1; - array[size] = null; - - return old; - } - - @Override - public FastArray trimToSize() { - - if (size == array.length) { - return this; - } - - array = ArrayUtils.copyOfRange(array, 0, size); - - return this; - } - - @Override - public boolean unsafeAdd(E object) { - array[size++] = object; - return true; - } - - @Override - public void unsafeSet(int index, E element) { - if (array[index] != null) { - size -= 1; - } - array[index] = element; - size += 1; - } - - @Override - public E unsafeGet(int index) { - return array[index]; - } - - @Override - public UnsafeArray asUnsafe() { - return this; - } - - @Override - public FastArray clone() throws CloneNotSupportedException { - var clone = (FastArray) super.clone(); - clone.array = ArrayUtils.copyOfAndExtend(array, size()); - return clone; - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastArraySet.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastArraySet.java deleted file mode 100644 index f0f4ae87..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/FastArraySet.java +++ /dev/null @@ -1,49 +0,0 @@ -package javasabr.rlib.common.util.array.impl; - -import javasabr.rlib.common.util.array.Array; -import org.jspecify.annotations.NullMarked; - -/** - * The fast implementation of the array with checking on duplicates. This array is not threadsafe. - * - * @param the type parameter - * @author JavaSaBr - */ -@NullMarked -public class FastArraySet extends FastArray { - - private static final long serialVersionUID = 1L; - - public FastArraySet(Class type) { - super(type); - } - - public FastArraySet(Class type, int size) { - super(type, size); - } - - @Override - public boolean add(E element) { - return !contains(element) && super.add(element); - } - - @Override - protected void processAdd(Array elements, int selfSize, int targetSize) { - var array = elements.array(); - for (int i = 0, length = elements.size(); i < length; i++) { - E element = array[i]; - if (!contains(element)) { - unsafeAdd(element); - } - } - } - - @Override - protected void processAdd(E[] elements, int selfSize, int targetSize) { - for (E element : elements) { - if (!contains(element)) { - unsafeAdd(element); - } - } - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ReadOnlyFastArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ReadOnlyFastArray.java deleted file mode 100644 index e60bc3c9..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/ReadOnlyFastArray.java +++ /dev/null @@ -1,124 +0,0 @@ -package javasabr.rlib.common.util.array.impl; - -import java.util.Collection; -import java.util.function.Function; -import java.util.function.Predicate; -import javasabr.rlib.common.util.array.Array; -import javasabr.rlib.common.util.array.ArrayComparator; -import javasabr.rlib.common.util.array.ReadOnlyArray; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -/** - * The read only version of the {@link FastArray}. - * - * @param the element's type. - * @author JavaSaBr - */ -@NullMarked -public final class ReadOnlyFastArray extends FastArray implements ReadOnlyArray { - - public ReadOnlyFastArray(E[] array) { - super(array); - } - - @Override - public void apply(Function function) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public boolean add(E object) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public boolean addAll(Collection collection) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public boolean fastRemove(Object object) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public E remove(int index) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public boolean addAll(Array elements) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public boolean addAll(E[] elements) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public E fastRemove(int index) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public boolean unsafeAdd(E object) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public E unsafeGet(int index) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public void unsafeSet(int index, E element) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public void replace(int index, E element) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public void clear() { - throw new IllegalStateException("This array is read only."); - } - - @Override - public Array sort(ArrayComparator comparator) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public boolean remove(@Nullable Object object) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public boolean removeAll(Array target) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public boolean removeAll(Collection target) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public boolean retainAll(Array target) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public boolean retainAll(Collection target) { - throw new IllegalStateException("This array is read only."); - } - - @Override - public boolean removeIf(Predicate filter) { - throw new IllegalStateException("This array is read only."); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/SortedFastArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/SortedFastArray.java deleted file mode 100644 index 352d4534..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/SortedFastArray.java +++ /dev/null @@ -1,86 +0,0 @@ -package javasabr.rlib.common.util.array.impl; - -import javasabr.rlib.common.util.ArrayUtils; -import javasabr.rlib.common.util.array.Array; -import org.jspecify.annotations.NullMarked; - -/** - * The sorted implementation of the {@link FastArray}. - * - * @param the array's element type. - * @author JavaSaBr - */ -@NullMarked -public class SortedFastArray> extends FastArray { - - private static final long serialVersionUID = 1L; - - public SortedFastArray(Class type) { - super(type); - } - - public SortedFastArray(Class type, int size) { - super(type, size); - } - - @Override - public boolean add(E element) { - - if (size == array.length) { - array = ArrayUtils.copyOfAndExtend(array, array.length * 3 / 2 + 1); - } - - return unsafeAdd(element); - } - - @Override - protected void processAdd(Array elements, int selfSize, int targetSize) { - var array = elements.array(); - for (int i = 0, length = elements.size(); i < length; i++) { - E element = array[i]; - if (!contains(element)) { - unsafeAdd(element); - } - } - } - - @Override - protected void processAdd(E[] elements, int selfSize, int targetSize) { - for (E element : elements) { - if (!contains(element)) { - unsafeAdd(element); - } - } - } - - @Override - public boolean unsafeAdd(E element) { - - E[] array = array(); - - for (int i = 0, length = array.length; i < length; i++) { - - E old = array[i]; - - if (old == null) { - array[i] = element; - size++; - return true; - } - - if (element.compareTo(old) < 0) { - - size++; - - int numMoved = size - i - 1; - - System.arraycopy(array, i, array, i + 1, numMoved); - - array[i] = element; - return true; - } - } - - return true; - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/SynchronizedArray.java b/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/SynchronizedArray.java deleted file mode 100644 index 115d483c..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/array/impl/SynchronizedArray.java +++ /dev/null @@ -1,212 +0,0 @@ -package javasabr.rlib.common.util.array.impl; - -import static java.lang.Math.max; - -import java.util.Collection; -import java.util.NoSuchElementException; -import java.util.concurrent.atomic.AtomicInteger; -import javasabr.rlib.common.util.ArrayUtils; -import javasabr.rlib.common.util.array.Array; -import javasabr.rlib.common.util.array.ArrayIterator; -import javasabr.rlib.common.util.array.UnsafeArray; -import org.jspecify.annotations.NullMarked; - -/** - * The implementation of the array with synchronization all methods. - * - * @param the array's element type. - * @author JavaSaBr - */ -@NullMarked -public class SynchronizedArray extends AbstractArray implements UnsafeArray { - - private static final long serialVersionUID = -7288153859732883548L; - - /** - * The count of elements in this array. - */ - private final AtomicInteger size; - - /** - * The unsafe array. - */ - private volatile E[] array; - - public SynchronizedArray(Class type) { - this(type, 10); - } - - public SynchronizedArray(Class type, int size) { - super(type, size); - this.size = new AtomicInteger(); - } - - @Override - public synchronized boolean add(E element) { - - if (size() == array.length) { - array = ArrayUtils.copyOfAndExtend(array, array.length >> 1); - } - - array[size.getAndIncrement()] = element; - return true; - } - - @Override - public synchronized final boolean addAll(Array elements) { - - if (elements.isEmpty()) { - return true; - } - - final int current = array.length; - final int selfSize = size(); - final int targetSize = elements.size(); - final int diff = selfSize + targetSize - current; - - if (diff > 0) { - array = ArrayUtils.copyOfAndExtend(array, max(current >> 1, diff)); - } - - processAdd(elements, selfSize, targetSize); - return true; - } - - @Override - public synchronized boolean addAll(final Collection collection) { - if (collection.isEmpty()) { - return true; - } - - final int current = array.length; - final int diff = size() + collection.size() - current; - - if (diff > 0) { - array = ArrayUtils.copyOfAndExtend(array, Math.max(current >> 1, diff)); - } - - for (final E element : collection) - unsafeAdd(element); - return true; - } - - @Override - public synchronized final boolean addAll(final E[] elements) { - - final int current = array.length; - final int selfSize = size(); - final int targetSize = elements.length; - final int diff = selfSize + targetSize - current; - - if (diff > 0) { - array = ArrayUtils.copyOfAndExtend(array, max(current >> 1, diff)); - } - - processAdd(elements, selfSize, targetSize); - return true; - } - - @Override - public final E[] array() { - return array; - } - - @Override - public synchronized final E fastRemove(final int index) { - - if (index < 0 || index >= size()) { - throw new NoSuchElementException(); - } - - final int newSize = size.decrementAndGet(); - final E old = array[index]; - - array[index] = array[newSize]; - array[newSize] = null; - - return old; - } - - @Override - public synchronized final E get(final int index) { - - if (index < 0 || index >= size()) { - throw new NoSuchElementException(); - } - - return array[index]; - } - - @Override - public synchronized ArrayIterator iterator() { - return new DefaultArrayIterator<>(this); - } - - @Override - public void replace(int index, E element) { - - if (index < 0 || index >= size()) { - throw new ArrayIndexOutOfBoundsException(); - } - - array[index] = element; - } - - @Override - protected final void setArray(final E[] array) { - this.array = array; - } - - @Override - protected final void setSize(final int size) { - this.size.getAndSet(size); - } - - @Override - public final int size() { - return size.get(); - } - - @Override - public synchronized E remove(int index) { - - if (index < 0 || index >= size()) { - throw new NoSuchElementException(); - } - - var length = size(); - var numMoved = length - index - 1; - - var old = array[index]; - - if (numMoved > 0) { - System.arraycopy(array, index + 1, array, index, numMoved); - } - - array[size.decrementAndGet()] = null; - return old; - } - - @Override - public synchronized SynchronizedArray trimToSize() { - - var size = size(); - - if (size == array.length) { - return this; - } - - array = ArrayUtils.copyOfRange(array, 0, size); - return this; - } - - protected void processAdd(final Array elements, final int selfSize, final int targetSize) { - System.arraycopy(elements.array(), 0, array, selfSize, targetSize); - size.set(selfSize + targetSize); - } - - protected void processAdd(final E[] elements, final int selfSize, final int targetSize) { - System.arraycopy(elements, 0, array, selfSize, targetSize); - size.set(selfSize + targetSize); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentIntegerDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentIntegerDictionary.java deleted file mode 100644 index 96a5a185..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentIntegerDictionary.java +++ /dev/null @@ -1,80 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import java.util.concurrent.atomic.AtomicInteger; -import javasabr.rlib.common.util.ArrayUtils; -import org.jspecify.annotations.NullMarked; - -/** - * The base implementation of the {@link ConcurrentIntegerDictionary}. - * - * @param the type parameter - * @author JavaSaBr - */ -@NullMarked -public abstract class AbstractConcurrentIntegerDictionary extends AbstractIntegerDictionary implements - ConcurrentIntegerDictionary { - - private final AtomicInteger size; - - private volatile IntegerEntry[] entries; - - private volatile int threshold; - - protected AbstractConcurrentIntegerDictionary() { - this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); - } - - protected AbstractConcurrentIntegerDictionary(float loadFactor) { - this(loadFactor, DEFAULT_INITIAL_CAPACITY); - } - - protected AbstractConcurrentIntegerDictionary(int initCapacity) { - this(DEFAULT_LOAD_FACTOR, initCapacity); - } - - protected AbstractConcurrentIntegerDictionary(float loadFactor, int initCapacity) { - super(loadFactor, initCapacity); - this.entries = ArrayUtils.create(getEntryType(), initCapacity); - this.size = new AtomicInteger(0); - } - - @Override - public void setEntries(IntegerEntry[] entries) { - this.entries = entries; - } - - @Override - public IntegerEntry [] entries() { - return entries; - } - - @Override - public int getThreshold() { - return threshold; - } - - @Override - protected void setSize(int size) { - this.size.set(size); - } - - @Override - public void setThreshold(int threshold) { - this.threshold = threshold; - } - - @Override - protected int decrementSizeAndGet() { - return size.decrementAndGet(); - } - - @Override - protected int incrementSizeAndGet() { - return size.incrementAndGet(); - } - - @Override - public final int size() { - return size.get(); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentLongDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentLongDictionary.java deleted file mode 100644 index 5ded013f..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentLongDictionary.java +++ /dev/null @@ -1,80 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import java.util.concurrent.atomic.AtomicInteger; -import javasabr.rlib.common.util.ArrayUtils; -import org.jspecify.annotations.NullMarked; - -/** - * The base implementation of the {@link ConcurrentLongDictionary}. - * - * @param the type parameter - * @author JavaSaBr - */ -@NullMarked -public abstract class AbstractConcurrentLongDictionary extends AbstractLongDictionary implements - ConcurrentLongDictionary { - - private final AtomicInteger size; - - private volatile LongEntry[] entries; - - private volatile int threshold; - - protected AbstractConcurrentLongDictionary() { - this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); - } - - protected AbstractConcurrentLongDictionary(float loadFactor) { - this(loadFactor, DEFAULT_INITIAL_CAPACITY); - } - - protected AbstractConcurrentLongDictionary(int initCapacity) { - this(DEFAULT_LOAD_FACTOR, initCapacity); - } - - protected AbstractConcurrentLongDictionary(float loadFactor, int initCapacity) { - super(loadFactor, initCapacity); - this.entries = ArrayUtils.create(getEntryType(), initCapacity); - this.size = new AtomicInteger(0); - } - - @Override - protected void setEntries(LongEntry[] entries) { - this.entries = entries; - } - - @Override - public LongEntry [] entries() { - return entries; - } - - @Override - public int getThreshold() { - return threshold; - } - - @Override - protected void setSize(int size) { - this.size.set(size); - } - - @Override - public void setThreshold(int threshold) { - this.threshold = threshold; - } - - @Override - protected int decrementSizeAndGet() { - return size.decrementAndGet(); - } - - @Override - protected int incrementSizeAndGet() { - return size.incrementAndGet(); - } - - @Override - public final int size() { - return size.get(); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentObjectDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentObjectDictionary.java deleted file mode 100644 index 1056d0ac..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractConcurrentObjectDictionary.java +++ /dev/null @@ -1,81 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import java.util.concurrent.atomic.AtomicInteger; -import javasabr.rlib.common.util.ArrayUtils; -import org.jspecify.annotations.NullMarked; - -/** - * The base implementation of the {@link ConcurrentObjectDictionary}. - * - * @param the key's type. - * @param the value's type. - * @author JavaSaBr - */ -@NullMarked -public abstract class AbstractConcurrentObjectDictionary extends AbstractObjectDictionary implements - ConcurrentObjectDictionary { - - private final AtomicInteger size; - - private volatile ObjectEntry[] entries; - - private volatile int threshold; - - protected AbstractConcurrentObjectDictionary() { - this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); - } - - protected AbstractConcurrentObjectDictionary(float loadFactor) { - this(loadFactor, DEFAULT_INITIAL_CAPACITY); - } - - protected AbstractConcurrentObjectDictionary(int initCapacity) { - this(DEFAULT_LOAD_FACTOR, initCapacity); - } - - protected AbstractConcurrentObjectDictionary(float loadFactor, int initCapacity) { - super(loadFactor, initCapacity); - this.entries = ArrayUtils.create(getEntryType(), initCapacity); - this.size = new AtomicInteger(0); - } - - @Override - public void setEntries(ObjectEntry[] entries) { - this.entries = entries; - } - - @Override - public ObjectEntry [] entries() { - return entries; - } - - @Override - public int getThreshold() { - return threshold; - } - - @Override - protected void setSize(int size) { - this.size.set(size); - } - - @Override - public void setThreshold(int threshold) { - this.threshold = threshold; - } - - @Override - protected int decrementSizeAndGet() { - return size.decrementAndGet(); - } - - @Override - protected int incrementSizeAndGet() { - return size.incrementAndGet(); - } - - @Override - public final int size() { - return size.get(); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractDictionary.java deleted file mode 100644 index 1c3cc200..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractDictionary.java +++ /dev/null @@ -1,257 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import java.util.Objects; -import java.util.function.Consumer; -import javasabr.rlib.common.function.NotNullFunction; -import javasabr.rlib.common.util.ArrayUtils; -import javasabr.rlib.common.util.array.Array; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -/** - * The base implementation of the {@link Dictionary}. - * - * @param the key's type. - * @param the value's type. - * @author JavaSaBr - */ -@NullMarked -public abstract class AbstractDictionary> implements Dictionary { - - /** - * The default size of table in the {@link Dictionary}. - */ - protected static final int DEFAULT_INITIAL_CAPACITY = 16; - - /** - * The max size of the {@link Dictionary}. - */ - protected static final int DEFAULT_MAXIMUM_CAPACITY = 1 << 30; - - /** - * The load factor of the {@link Dictionary}. - */ - protected static final float DEFAULT_LOAD_FACTOR = 0.75f; - - /** - * Calculate a hash of the hashcode. - * - * @param hashcode the hashcode. - * @return the hash. - */ - protected static int hash(int hashcode) { - hashcode ^= hashcode >>> 20 ^ hashcode >>> 12; - return hashcode ^ hashcode >>> 7 ^ hashcode >>> 4; - } - - /** - * Calculate a hash of the long key. - * - * @param key the long key. - * @return the hash. - */ - protected static int hash(long key) { - int hash = (int) (key ^ key >>> 32); - hash ^= hash >>> 20 ^ hash >>> 12; - return hash ^ hash >>> 7 ^ hash >>> 4; - } - - /** - * Get an index of table in the {@link Dictionary}. - * - * @param hash the hash of a key. - * @param length the length of a table in the {@link Dictionary}. - * @return the index in the table. - */ - protected static int indexFor(int hash, int length) { - return hash & length - 1; - } - - - /** - * The load factor. - */ - protected final float loadFactor; - - protected AbstractDictionary(float loadFactor, int initCapacity) { - this.loadFactor = loadFactor; - setThreshold((int) (initCapacity * loadFactor)); - } - - @Override - public final void apply(NotNullFunction function) { - for (var entry : entries()) { - while (entry != null) { - entry.setValue(function.apply(entry.getValue())); - entry = entry.getNext(); - } - } - } - - @Override - public void clear() { - - var entries = entries(); - - E next; - - for (E entry : entries) { - while (entry != null) { - next = entry.getNext(); - //entryPool.put(entry); - entry = next; - } - } - - ArrayUtils.clear(entries); - - setSize(0); - } - - @Override - public final boolean containsValue(@Nullable V value) { - - for (var entry : entries()) { - for (var nextEntry = entry; nextEntry != null; nextEntry = nextEntry.getNext()) { - if (Objects.equals(value, nextEntry.getValue())) { - return true; - } - } - } - - return false; - } - - @Override - public final void forEach(Consumer consumer) { - for (var entry : entries()) { - while (entry != null) { - consumer.accept(entry.getValue()); - entry = entry.getNext(); - } - } - } - - /** - * Resize the array of buckets of this dictionary. - * - * @param newLength the new size. - */ - protected final void resize(int newLength) { - - var prevEntries = entries(); - var oldLength = prevEntries.length; - - if (oldLength >= DEFAULT_MAXIMUM_CAPACITY) { - setThreshold(Integer.MAX_VALUE); - return; - } - - var newEntries = ArrayUtils.create(getEntryType(), newLength); - - transfer(newEntries); - setEntries(newEntries); - setThreshold((int) (newLength * loadFactor)); - } - - /** - * Transfer current entries to new entries. - * - * @param newEntries the new array of entries. - */ - private void transfer(E[] newEntries) { - - var entries = entries(); - var newCapacity = newEntries.length; - - for (var entry : entries) { - - if (entry == null) { - continue; - } - - do { - - var nextEntry = entry.getNext(); - var i = indexFor(entry.getHash(), newCapacity); - - entry.setNext(newEntries[i]); - newEntries[i] = entry; - entry = nextEntry; - - } while (entry != null); - } - } - - @Override - public final Array values(Array container) { - - var unsafeArray = container.asUnsafe(); - unsafeArray.prepareForSize(container.size() + size()); - - for (var entry : entries()) { - while (entry != null) { - unsafeArray.unsafeAdd(entry.getValue()); - entry = entry.getNext(); - } - } - - return container; - } - - /** - * Get the entries type. - * - * @return the entries type. - */ - protected abstract Class getEntryType(); - - /** - * Set new array of entries of this {@link Dictionary}. - * - * @param entries the new array of entries. - */ - protected abstract void setEntries(E[] entries); - - /** - * Get an array of all entries in this dictionary.. - * - * @return the array of entries. - */ - protected abstract E [] entries(); - - /** - * Set the next size value at which to resize (capacity * load factor). - * - * @param threshold the next size. - */ - protected abstract void setThreshold(int threshold); - - /** - * Get the threshold. - * - * @return the current next size. - */ - protected abstract int getThreshold(); - - /** - * Set the new size of this {@link Dictionary}. - * - * @param size the new size. - */ - protected abstract void setSize(int size); - - /** - * Decrement and get the size of this {@link Dictionary}. - * - * @return the new size of this {@link Dictionary}. - */ - protected abstract int decrementSizeAndGet(); - - /** - * Increment and get the size of this {@link Dictionary}. - * - * @return the new size of this {@link Dictionary}. - */ - protected abstract int incrementSizeAndGet(); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractIntegerDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractIntegerDictionary.java deleted file mode 100644 index ececceff..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractIntegerDictionary.java +++ /dev/null @@ -1,276 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import java.util.Iterator; -import java.util.function.Function; -import java.util.function.IntFunction; -import java.util.function.Supplier; -import javasabr.rlib.common.function.IntBiObjectConsumer; -import javasabr.rlib.common.util.ClassUtils; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -/** - * The base implementation of {@link IntegerDictionary}. - * - * @param the type parameter - * @author JavaSaBr - */ -@NullMarked -public abstract class AbstractIntegerDictionary extends AbstractDictionary> implements - UnsafeIntegerDictionary { - - protected AbstractIntegerDictionary() { - this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); - } - - protected AbstractIntegerDictionary(float loadFactor, int initCapacity) { - super(loadFactor, initCapacity); - } - - @Override - protected Class> getEntryType() { - return IntegerEntry.class; - } - - /** - * Add a new entry to this dictionary. - * - * @param hash the hash of the key. - * @param key the key. - * @param value the value of the key. - * @param index the index of bucket. - */ - protected final void addEntry(int hash, int key, V value, int index) { - - var entries = entries(); - var entry = entries[index]; - - var newEntry = new IntegerEntry(); - newEntry.set(hash, key, value, entry); - - entries[index] = newEntry; - - if (incrementSizeAndGet() >= getThreshold()) { - resize(2 * entries.length); - } - } - - @Override - public final boolean containsKey(int key) { - return getEntry(key) != null; - } - - @Override - public void forEach( - T argument, - IntBiObjectConsumer consumer) { - for (var entry : entries()) { - while (entry != null) { - consumer.accept(entry.getKey(), entry.getValue(), argument); - entry = entry.getNext(); - } - } - } - - @Override - public final @Nullable V get(int key) { - var entry = getEntry(key); - return entry == null ? null : entry.getValue(); - } - - @Override - public V getOrCompute(int key, Supplier factory) { - - var entry = getEntry(key); - - if (entry == null) { - put(key, factory.get()); - entry = getEntry(key); - } - - if (entry == null) { - throw new IllegalStateException("The factory " + factory + " returned a null value."); - } - - return entry.getValue(); - } - - @Override - public V getOrCompute(int key, IntFunction factory) { - - var entry = getEntry(key); - - if (entry == null) { - put(key, factory.apply(key)); - entry = getEntry(key); - } - - if (entry == null) { - throw new IllegalStateException("The factory " + factory + " returned a null value."); - } - - return entry.getValue(); - } - - @Override - public @Nullable V getOrCompute(int key, T argument, Function factory) { - - var entry = getEntry(key); - - if (entry == null) { - put(key, factory.apply(argument)); - entry = getEntry(key); - } - - if (entry == null) { - throw new IllegalStateException("The factory " + factory + " returned a null value."); - } - - return entry.getValue(); - } - - /** - * Get the entry with value for the key. - * - * @param key the key. - * @return the entry or null. - */ - - private @Nullable IntegerEntry getEntry(int key) { - - var entries = entries(); - var index = indexFor(hash(key), entries.length); - - for (IntegerEntry entry = entries[index]; entry != null; entry = entry.getNext()) { - if (key == entry.getKey()) { - return entry; - } - } - - return null; - } - - @Override - public final Iterator iterator() { - return new IntegerDictionaryIterator<>(this); - } - - @Override - public void copyTo(Dictionary dictionary) { - - if (isEmpty() || !(dictionary instanceof IntegerDictionary)) { - return; - } - - IntegerDictionary target = ClassUtils.unsafeNNCast(dictionary); - - for (IntegerEntry entry : entries()) { - while (entry != null) { - target.put(entry.getKey(), entry.getValue()); - entry = entry.getNext(); - } - } - } - - @Override - public final @Nullable V put(int key, V value) { - - var entries = entries(); - - var hash = hash(key); - var entryIndex = indexFor(hash, entries.length); - - for (var entry = entries[entryIndex]; entry != null; entry = entry.getNext()) { - if (entry.getHash() == hash && key == entry.getKey()) { - return entry.setValue(value); - } - } - - addEntry(hash, key, value, entryIndex); - return null; - } - - @Override - public @Nullable V remove(int key) { - - var old = removeEntryForKey(key); - - if (old == null) { - return null; - } - - var value = old.getValue(); - - return value; - } - - /** - * Remove the entry for the key. - * - * @param key the key of the entry. - * @return removed entry or null. - */ - @Override - public final @Nullable IntegerEntry removeEntryForKey(int key) { - - var entries = entries(); - - int i = indexFor(hash(key), entries.length); - - var prev = entries[i]; - var entry = prev; - - while (entry != null) { - - var next = entry.getNext(); - - if (key == entry.getKey()) { - decrementSizeAndGet(); - - if (prev == entry) { - entries[i] = next; - } else { - prev.setNext(next); - } - - return entry; - } - - prev = entry; - entry = next; - } - - return null; - } - - @Override - public final String toString() { - - var size = size(); - - var builder = new StringBuilder(getClass().getSimpleName()); - builder - .append(" size = ") - .append(size) - .append(" : "); - - for (var entry : entries()) { - while (entry != null) { - builder - .append("[") - .append(entry.getKey()) - .append(" - ") - .append(entry.getValue()) - .append("]") - .append("\n"); - entry = entry.getNext(); - } - } - - if (size > 0) { - builder.replace(builder.length() - 1, builder.length(), "."); - } - - return builder.toString(); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractLongDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractLongDictionary.java deleted file mode 100644 index 99e0f3a1..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractLongDictionary.java +++ /dev/null @@ -1,286 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import java.util.Iterator; -import java.util.function.Function; -import java.util.function.LongFunction; -import java.util.function.Supplier; -import javasabr.rlib.common.function.LongBiObjectConsumer; -import javasabr.rlib.common.function.LongObjectConsumer; -import javasabr.rlib.common.util.ClassUtils; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -/** - * The base implementation of the {@link LongDictionary}. - * - * @param the value's type. - * @author JavaSaBr - */ -@NullMarked -public abstract class AbstractLongDictionary extends AbstractDictionary> implements - UnsafeLongDictionary { - - protected AbstractLongDictionary() { - this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); - } - - protected AbstractLongDictionary(float loadFactor) { - this(loadFactor, DEFAULT_INITIAL_CAPACITY); - } - - protected AbstractLongDictionary(int initCapacity) { - this(DEFAULT_LOAD_FACTOR, initCapacity); - } - - protected AbstractLongDictionary(float loadFactor, int initCapacity) { - super(loadFactor, initCapacity); - } - - @Override - protected Class> getEntryType() { - return LongEntry.class; - } - - /** - * Add new entry to this dictionary. - * - * @param hash the hash of the key. - * @param key the key. - * @param value the value of the key. - * @param index the index of bucket. - */ - private void addEntry(int hash, long key, V value, int index) { - - var entries = entries(); - var entry = entries[index]; - - var newEntry = new LongEntry(); - newEntry.set(hash, key, value, entry); - - entries[index] = newEntry; - - if (incrementSizeAndGet() >= getThreshold()) { - resize(2 * entries.length); - } - } - - @Override - public final boolean containsKey(long key) { - return getEntry(key) != null; - } - - @Override - public final @Nullable V get(long key) { - var entry = getEntry(key); - return entry == null ? null : entry.getValue(); - } - - @Override - public V getOrCompute(long key, Supplier factory) { - - var entry = getEntry(key); - - if (entry == null) { - put(key, factory.get()); - entry = getEntry(key); - } - - if (entry == null) { - throw new IllegalStateException("The factory " + factory + " returned a null value."); - } - - return entry.getValue(); - } - - @Override - public V getOrCompute(long key, LongFunction factory) { - - var entry = getEntry(key); - - if (entry == null) { - put(key, factory.apply(key)); - entry = getEntry(key); - } - - if (entry == null) { - throw new IllegalStateException("The factory " + factory + " returned a null value."); - } - - return entry.getValue(); - } - - @Override - public @Nullable V getOrCompute( - long key, - T argument, - Function factory) { - - var entry = getEntry(key); - - if (entry == null) { - put(key, factory.apply(argument)); - entry = getEntry(key); - } - - if (entry == null) { - throw new IllegalStateException("The factory " + factory + " returned a null value."); - } - - return entry.getValue(); - } - - /** - * Get the entry with value for the key. - * - * @param key the key. - * @return the entry or null. - */ - private @Nullable LongEntry getEntry(long key) { - - var entries = entries(); - - int hash = hash(key); - int index = indexFor(hash, entries.length); - - for (var entry = entries[index]; entry != null; entry = entry.getNext()) { - if (entry.getHash() == hash && key == entry.getKey()) { - return entry; - } - } - - return null; - } - - @Override - public final Iterator iterator() { - return new LongDictionaryIterator<>(this); - } - - @Override - public void copyTo(Dictionary dictionary) { - - if (isEmpty() || !(dictionary instanceof LongDictionary)) { - return; - } - - var targetDictionary = ClassUtils.>unsafeNNCast(dictionary); - - for (var entry : entries()) { - while (entry != null) { - targetDictionary.put(entry.getKey(), entry.getValue()); - entry = entry.getNext(); - } - } - } - - @Override - public V put(long key, V value) { - - var entries = entries(); - var hash = hash(key); - var i = indexFor(hash, entries.length); - - for (var entry = entries[i]; entry != null; entry = entry.getNext()) { - if (entry.getHash() == hash && key == entry.getKey()) { - return entry.setValue(value); - } - } - - addEntry(hash, key, value, i); - - return null; - } - - @Override - public @Nullable V remove(long key) { - var oldEntry = removeEntryForKey(key); - V value = oldEntry == null ? null : oldEntry.getValue(); - return value; - } - - @Override - public @Nullable LongEntry removeEntryForKey(long key) { - - var entries = entries(); - var hash = hash(key); - var i = indexFor(hash, entries.length); - - var prevEntry = entries[i]; - var entry = prevEntry; - - while (entry != null) { - - var nextEntry = entry.getNext(); - - if (entry.getHash() == hash && key == entry.getKey()) { - decrementSizeAndGet(); - - if (prevEntry == entry) { - entries[i] = nextEntry; - } else { - prevEntry.setNext(nextEntry); - } - - return entry; - } - - prevEntry = entry; - entry = nextEntry; - } - - return null; - } - - @Override - public final String toString() { - - var size = size(); - - var builder = new StringBuilder(getClass().getSimpleName()); - builder - .append(" size = ") - .append(size) - .append(" :\n"); - - var entries = entries(); - - for (var entry : entries) { - while (entry != null) { - builder - .append("[") - .append(entry.getKey()) - .append(" - ") - .append(entry.getValue()) - .append("]") - .append("\n"); - entry = entry.getNext(); - } - } - - if (size > 0) { - builder.delete(builder.length() - 1, builder.length()); - } - - return builder.toString(); - } - - @Override - public void forEach(T argument, LongBiObjectConsumer consumer) { - for (var entry : entries()) { - while (entry != null) { - consumer.accept(entry.getKey(), entry.getValue(), argument); - entry = entry.getNext(); - } - } - } - - @Override - public void forEach(LongObjectConsumer consumer) { - for (var entry : entries()) { - while (entry != null) { - consumer.accept(entry.getKey(), entry.getValue()); - entry = entry.getNext(); - } - } - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractObjectDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractObjectDictionary.java deleted file mode 100644 index 4ee4e274..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/AbstractObjectDictionary.java +++ /dev/null @@ -1,346 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import java.util.Iterator; -import javasabr.rlib.common.function.FourObjectConsumer; -import javasabr.rlib.common.function.NotNullBiConsumer; -import javasabr.rlib.common.function.NotNullBiFunction; -import javasabr.rlib.common.function.NotNullFunction; -import javasabr.rlib.common.function.NotNullSupplier; -import javasabr.rlib.common.function.NotNullTripleConsumer; -import javasabr.rlib.common.util.ClassUtils; -import javasabr.rlib.common.util.array.Array; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -/** - * The base implementation of the {@link ObjectDictionary}. - * - * @param the key's type. - * @param the value's type. - * @author JavaSaBr - */ -@NullMarked -public abstract class AbstractObjectDictionary extends AbstractDictionary> implements - UnsafeObjectDictionary { - - protected AbstractObjectDictionary() { - this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); - } - - protected AbstractObjectDictionary(float loadFactor) { - this(loadFactor, DEFAULT_INITIAL_CAPACITY); - } - - protected AbstractObjectDictionary(int initCapacity) { - this(DEFAULT_LOAD_FACTOR, initCapacity); - } - - protected AbstractObjectDictionary(float loadFactor, int initCapacity) { - super(loadFactor, initCapacity); - } - - @Override - protected Class> getEntryType() { - return ObjectEntry.class; - } - - /** - * Add new entry to this dictionary. - * - * @param hash the hash of the key. - * @param key the key. - * @param value the value of the key. - * @param index the index of bucket. - */ - private void addEntry(int hash, K key, V value, int index) { - - var entries = entries(); - var entry = entries[index]; - - var newEntry = new ObjectEntry(); - newEntry.set(hash, key, value, entry); - - entries[index] = newEntry; - - if (incrementSizeAndGet() >= getThreshold()) { - resize(2 * entries.length); - } - } - - @Override - public final boolean containsKey(K key) { - return getEntry(key) != null; - } - - @Override - public @Nullable V get(K key) { - var entry = getEntry(key); - return entry == null ? null : entry.getValue(); - } - - @Override - public V getOrCompute(K key, NotNullSupplier factory) { - - var entry = getEntry(key); - - if (entry == null) { - put(key, factory.get()); - entry = getEntry(key); - } - - if (entry == null) { - throw new IllegalStateException("Factory " + factory + " returned a null value."); - } - - //noinspection ConstantConditions - return entry.getValue(); - } - - @Override - public V getOrCompute(K key, NotNullFunction factory) { - - var entry = getEntry(key); - - if (entry == null) { - put(key, factory.apply(key)); - entry = getEntry(key); - } - - if (entry == null) { - throw new IllegalStateException("Factory " + factory + " returned a null value."); - } - - //noinspection ConstantConditions - return entry.getValue(); - } - - @Override - public V getOrCompute(K key, T argument, NotNullFunction factory) { - - var entry = getEntry(key); - - if (entry == null) { - put(key, factory.apply(argument)); - entry = getEntry(key); - } - - if (entry == null) { - throw new IllegalStateException("Factory " + factory + " returned a null value."); - } - - //noinspection ConstantConditions - return entry.getValue(); - } - - @Override - public V getOrCompute(K key, T argument, NotNullBiFunction factory) { - - var entry = getEntry(key); - - if (entry == null) { - put(key, factory.apply(key, argument)); - entry = getEntry(key); - } - - if (entry == null) { - throw new IllegalStateException("Factory " + factory + " returned a null value."); - } - - //noinspection ConstantConditions - return entry.getValue(); - } - - /** - * Get an entry for the key. - * - * @param key the key. - * @return the entry or null. - */ - private @Nullable ObjectEntry getEntry(K key) { - - var entries = entries(); - - var hash = hash(key.hashCode()); - var entryIndex = indexFor(hash, entries.length); - - for (var entry = entries[entryIndex]; entry != null; entry = entry.getNext()) { - if (entry.getHash() == hash && key.equals(entry.getKey())) { - return entry; - } - } - - return null; - } - - @Override - public final Iterator iterator() { - return new ObjectDictionaryIterator<>(this); - } - - @Override - public final Array keyArray(Array container) { - - var unsafeArray = container.asUnsafe(); - unsafeArray.prepareForSize(container.size() + size()); - - for (var entry : entries()) { - while (entry != null) { - //noinspection ConstantConditions - unsafeArray.unsafeAdd(entry.getKey()); - entry = entry.getNext(); - } - } - - return container; - } - - @Override - public void copyTo(Dictionary dictionary) { - - if (isEmpty() || !(dictionary instanceof ObjectDictionary)) { - return; - } - - var target = ClassUtils.>unsafeNNCast(dictionary); - - for (var entry : entries()) { - while (entry != null) { - //noinspection ConstantConditions - target.put(entry.getKey(), entry.getValue()); - entry = entry.getNext(); - } - } - } - - @Override - public @Nullable V put(K key, V value) { - - var entries = entries(); - - var hash = hash(key.hashCode()); - var entryIndex = indexFor(hash, entries.length); - - for (var entry = entries[entryIndex]; entry != null; entry = entry.getNext()) { - if (entry.getHash() == hash && key.equals(entry.getKey())) { - return entry.setValue(value); - } - } - - addEntry(hash, key, value, entryIndex); - return null; - } - - @Override - public @Nullable V remove(K key) { - - var old = removeEntryForKey(key); - - if (old == null) { - return null; - } - - var value = old.getValue(); - - return value; - } - - @Override - public @Nullable ObjectEntry removeEntryForKey(K key) { - - var entries = entries(); - - var hash = hash(key.hashCode()); - var entryIndex = indexFor(hash, entries.length); - - var prev = entries[entryIndex]; - var entry = prev; - - while (entry != null) { - - var next = entry.getNext(); - - if (entry.getHash() == hash && key.equals(entry.getKey())) { - decrementSizeAndGet(); - - if (prev == entry) { - entries[entryIndex] = next; - } else { - prev.setNext(next); - } - - return entry; - } - - prev = entry; - entry = next; - } - - return null; - } - - @Override - public final String toString() { - - int size = size(); - - var builder = new StringBuilder(getClass().getSimpleName()) - .append(" size = ") - .append(size) - .append(" : "); - - var entries = entries(); - - for (var entry : entries) { - while (entry != null) { - builder - .append("[") - .append(entry.getKey()) - .append(" - ") - .append(entry.getValue()) - .append("]\n"); - entry = entry.getNext(); - } - } - - if (size > 0) { - builder.replace(builder.length() - 1, builder.length(), "."); - } - - return builder.toString(); - } - - @Override - public void forEach(NotNullBiConsumer consumer) { - for (var entry : entries()) { - while (entry != null) { - consumer.accept(entry.getKey(), entry.getValue()); - entry = entry.getNext(); - } - } - } - - @Override - public void forEach( - T argument, - NotNullTripleConsumer consumer) { - for (var entry : entries()) { - while (entry != null) { - consumer.accept(argument, entry.getKey(), entry.getValue()); - entry = entry.getNext(); - } - } - } - - @Override - public void forEach( - F first, - S second, - FourObjectConsumer consumer) { - for (var entry : entries()) { - while (entry != null) { - consumer.accept(first, second, entry.getKey(), entry.getValue()); - entry = entry.getNext(); - } - } - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentDictionary.java deleted file mode 100644 index f6b09d0a..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentDictionary.java +++ /dev/null @@ -1,69 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import org.jspecify.annotations.NullMarked; - -/** - * The interface with methods for supporting threadsafe for the {@link Dictionary}. - * - * @param the key's type. - * @param the value's type. - * @author JavaSaBr - */ -@NullMarked -public interface ConcurrentDictionary extends Dictionary { - - /** - * Lock this dictionary for reading. - * - * @return the stamp of read lock or 0. - */ - default long readLock() { - throw new UnsupportedOperationException(); - } - - /** - * Unlock the read lock. - * - * @param stamp the stamp of read lock. - */ - default void readUnlock(long stamp) { - throw new UnsupportedOperationException(); - } - - /** - * Try to optimistic read. - * - * @return the stamp of optimistic read or 0 if it was failed. - */ - default long tryOptimisticRead() { - throw new UnsupportedOperationException(); - } - - /** - * Validate this stamp. - * - * @param stamp the stamp. - * @return true is this stamp is valid. - */ - default boolean validate(long stamp) { - throw new UnsupportedOperationException(); - } - - /** - * Lock this array for writing. - * - * @return the stamp of write lock or 0. - */ - default long writeLock() { - throw new UnsupportedOperationException(); - } - - /** - * Unlock the write lock. - * - * @param stamp the stamp of write lock. - */ - default void writeUnlock(long stamp) { - throw new UnsupportedOperationException(); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentIntegerDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentIntegerDictionary.java deleted file mode 100644 index 79750e1e..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentIntegerDictionary.java +++ /dev/null @@ -1,14 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import org.jspecify.annotations.NullMarked; - -/** - * The interface with methods for supporting threadsafe for the {@link IntegerDictionary}. - * - * @param the value's type. - * @author JavaSaBr - */ -@NullMarked -public interface ConcurrentIntegerDictionary extends IntegerDictionary, ConcurrentDictionary { - -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentLongDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentLongDictionary.java deleted file mode 100644 index 14462e34..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentLongDictionary.java +++ /dev/null @@ -1,14 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import org.jspecify.annotations.NullMarked; - -/** - * The interface with methods for supporting threadsafe for the {@link LongDictionary}. - * - * @param the value's type. - * @author JavaSaBr - */ -@NullMarked -public interface ConcurrentLongDictionary extends LongDictionary, ConcurrentDictionary { - -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentObjectDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentObjectDictionary.java deleted file mode 100644 index 96c0ea84..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentObjectDictionary.java +++ /dev/null @@ -1,227 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import java.util.function.BiFunction; -import javasabr.rlib.common.function.NotNullBiConsumer; -import javasabr.rlib.common.function.NotNullConsumer; -import javasabr.rlib.common.function.NotNullNullableBiFunction; -import javasabr.rlib.common.function.NotNullNullableTripleFunction; -import javasabr.rlib.common.function.NotNullTripleConsumer; -import org.jspecify.annotations.NonNull; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -/** - * The interface with methods for supporting thread-safe for the {@link ObjectDictionary}. - * - * @param the key's type. - * @param the value's type. - * @author JavaSaBr - */ -@NullMarked -public interface ConcurrentObjectDictionary extends ObjectDictionary, ConcurrentDictionary { - - /** - * Create a new concurrent object dictionary for the key's type and value's type. - * - * @param keyValueType the key's and value's type. - * @param the key's and value's type. - * @return the new concurrent object dictionary. - */ - static ObjectDictionary ofType(Class keyValueType) { - return DictionaryFactory.newConcurrentStampedLockObjectDictionary(); - } - - /** - * Create a new concurrent object dictionary for the key's type and value's type. - * - * @param keyType the key's type. - * @param valueType the value's type. - * @param the key's type. - * @param the value's type. - * @return the new concurrent object dictionary. - */ - static ConcurrentObjectDictionary ofType( - Class keyType, - Class valueType) { - return DictionaryFactory.newConcurrentStampedLockObjectDictionary(); - } - - /** - * Execute a function for this dictionary under block {@link ConcurrentObjectDictionary#readLock()}. - * - * @param argument the argument. - * @param consumer the function. - * @param the argument's type. - * @return this dictionary. - */ - default ConcurrentObjectDictionary runInReadLock( - A argument, - NotNullBiConsumer, A> consumer) { - - var stamp = readLock(); - try { - consumer.accept(this, argument); - } finally { - readUnlock(stamp); - } - - return this; - } - - /** - * Execute a function for this dictionary under block {@link ConcurrentObjectDictionary#writeLock()}. - * - * @param consumer the function. - * @return this dictionary. - */ - default ConcurrentObjectDictionary runInWriteLock( - NotNullConsumer> consumer) { - - var stamp = writeLock(); - try { - consumer.accept(this); - } finally { - writeUnlock(stamp); - } - - return this; - } - - /** - * Execute a function for this dictionary under block {@link ConcurrentObjectDictionary#writeLock()}. - * - * @param argument the argument. - * @param consumer the function. - * @param the argument's type. - * @return this dictionary. - */ - default ConcurrentObjectDictionary runInWriteLock( - A argument, - NotNullBiConsumer, A> consumer) { - - var stamp = writeLock(); - try { - consumer.accept(this, argument); - } finally { - writeUnlock(stamp); - } - - return this; - } - - /** - * Execute a function for this dictionary under block {@link ConcurrentObjectDictionary#writeLock()}. - * - * @param first the first argument. - * @param second the second argument. - * @param consumer the function. - * @param the first argument's type. - * @param the second argument's type. - * @return this dictionary. - */ - default ConcurrentObjectDictionary runInWriteLock( - F first, - S second, - NotNullTripleConsumer, F, S> consumer) { - - var stamp = writeLock(); - try { - consumer.accept(this, first, second); - } finally { - writeUnlock(stamp); - } - - return this; - } - - default @Nullable R getFromReadLock( - A arg1, - BiFunction<@NonNull ConcurrentObjectDictionary, A, R> function) { - var stamp = readLock(); - try { - return function.apply(this, arg1); - } finally { - readUnlock(stamp); - } - } - - /** - * Get the value from a function for this dictionary under block {@link ConcurrentObjectDictionary#readLock()}. - * - * @param first the first argument. - * @param second the second argument. - * @param function the function. - * @param the first argument's type. - * @param the second argument's type. - * @param the result's type. - * @return the result of the function. - */ - default @Nullable R getInReadLock( - F first, - S second, - NotNullNullableTripleFunction, F, S, R> function) { - var stamp = readLock(); - try { - return function.apply(this, first, second); - } finally { - readUnlock(stamp); - } - } - - /** - * Get the value from a function for this dictionary under block {@link ConcurrentObjectDictionary#writeLock()}. - * - * @param argument the argument. - * @param function the function. - * @param the argument's type. - * @param the result's type. - * @return the result of the function. - */ - default @Nullable R getInWriteLock( - A argument, - NotNullNullableBiFunction, A, R> function) { - var stamp = writeLock(); - try { - return function.apply(this, argument); - } finally { - writeUnlock(stamp); - } - } - - /** - * Get the value from a function for this dictionary under block {@link ConcurrentObjectDictionary#writeLock()}. - * - * @param first the first argument. - * @param second the second argument. - * @param function the function. - * @param the first argument's type. - * @param the second argument's type. - * @param the result's type. - * @return the result of the function. - */ - default @Nullable R getInWriteLock( - F first, - S second, - NotNullNullableTripleFunction, F, S, R> function) { - var stamp = writeLock(); - try { - return function.apply(this, first, second); - } finally { - writeUnlock(stamp); - } - } - - /** - * Performs the given action for each key-value pair of this dictionary. - * - * @param consumer the consumer. - */ - default void forEachInReadLock(NotNullBiConsumer consumer) { - var stamp = readLock(); - try { - forEach(consumer); - } finally { - readUnlock(stamp); - } - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentStampedLockObjectDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentStampedLockObjectDictionary.java deleted file mode 100644 index 4bef9755..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ConcurrentStampedLockObjectDictionary.java +++ /dev/null @@ -1,54 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import java.util.concurrent.locks.StampedLock; -import org.jspecify.annotations.NullMarked; - -/** - * The implementation of the {@link ConcurrentObjectDictionary} using {@link LockFactory#newAtomicARSWLock()}*. - * - * @param the key's type. - * @param the value's type. - * @author JavaSaBr - */ -@NullMarked -public class ConcurrentStampedLockObjectDictionary extends AbstractConcurrentObjectDictionary { - - private final StampedLock lock; - - public ConcurrentStampedLockObjectDictionary() { - this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); - } - - public ConcurrentStampedLockObjectDictionary(float loadFactor) { - this(loadFactor, DEFAULT_INITIAL_CAPACITY); - } - - public ConcurrentStampedLockObjectDictionary(int initCapacity) { - this(DEFAULT_LOAD_FACTOR, initCapacity); - } - - public ConcurrentStampedLockObjectDictionary(float loadFactor, int initCapacity) { - super(loadFactor, initCapacity); - this.lock = new StampedLock(); - } - - @Override - public long readLock() { - return lock.readLock(); - } - - @Override - public void readUnlock(long stamp) { - lock.unlockRead(stamp); - } - - @Override - public void writeUnlock(long stamp) { - lock.unlockWrite(stamp); - } - - @Override - public long writeLock() { - return lock.writeLock(); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/Dictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/Dictionary.java deleted file mode 100644 index 4f5ffec9..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/Dictionary.java +++ /dev/null @@ -1,98 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import javasabr.rlib.common.function.NotNullFunction; -import javasabr.rlib.common.util.array.Array; -import javasabr.rlib.common.util.array.ArrayFactory; -import org.jspecify.annotations.NullMarked; - -/** - * The interface for implementing a key-value dictionary. - * - * @param the key's type. - * @param the value's type. - * @author JavaSaBr - */ -@NullMarked -@Deprecated -public interface Dictionary extends Iterable { - - /** - * Replace the all values using the function. - * - * @param function the function. - */ - default void apply(NotNullFunction function) { - throw new UnsupportedOperationException(); - } - - /** - * Clear this dictionary. - */ - default void clear() { - throw new UnsupportedOperationException(); - } - - /** - * Return true if this dictionary contains the value. - * - * @param value the value. - * @return true if this dictionary contains the value. - */ - default boolean containsValue(V value) { - throw new UnsupportedOperationException(); - } - - /** - * Returns true if this dictionary contains no key-value mappings. - * - * @return true if this dictionary contains no key-value mappings - */ - default boolean isEmpty() { - return size() == 0; - } - - /** - * Put all data from this dictionary to the dictionary. - * - * @param dictionary the dictionary. - */ - void copyTo(Dictionary dictionary); - - /** - * Put all data from the dictionary to this dictionary. - * - * @param dictionary the dictionary with new data. - */ - default void put(Dictionary dictionary) { - dictionary.copyTo(this); - } - - /** - * Return the number of key-value mappings in this dictionary. - * - * @return the number of key-value mappings in this dictionary. - */ - default int size() { - throw new UnsupportedOperationException(); - } - - /** - * Collect all values from this dictionary. - * - * @param container the container to store the values. - * @return the container with all values from this dictionary. - */ - default Array values(Array container) { - throw new UnsupportedOperationException(); - } - - /** - * Collect all values from this dictionary. - * - * @param type the value's type. - * @return the array with all values from this dictionary. - */ - default Array values(Class type) { - return values(ArrayFactory.newArray(type, size())); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryCollectors.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryCollectors.java deleted file mode 100644 index 40e8aed1..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryCollectors.java +++ /dev/null @@ -1,172 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import static java.util.Collections.unmodifiableSet; -import static java.util.stream.Collector.Characteristics; - -import java.util.EnumSet; -import java.util.Set; -import java.util.function.BiConsumer; -import java.util.function.BinaryOperator; -import java.util.function.Function; -import java.util.function.Supplier; -import java.util.stream.Collector; -import javasabr.rlib.common.util.ObjectUtils; -import org.jspecify.annotations.NullMarked; - -/** - * The collectors to {@link Dictionary} - * - * @author JavaSaBr - */ -@NullMarked -public final class DictionaryCollectors { - - static final Set CH_ID = unmodifiableSet(EnumSet.of(Characteristics.IDENTITY_FINISH)); - - /** - * Simple implementation class for {@code Collector}. - * - * @param the type of elements to be collected - * @param the type of the result - */ - static class CollectorImpl implements Collector { - - private final Supplier supplier; - private final BiConsumer accumulator; - private final BinaryOperator combiner; - private final Function finisher; - private final Set characteristics; - - CollectorImpl( - Supplier supplier, - BiConsumer accumulator, - BinaryOperator combiner, - Function finisher, - Set characteristics) { - this.supplier = supplier; - this.accumulator = accumulator; - this.combiner = combiner; - this.finisher = finisher; - this.characteristics = characteristics; - } - - CollectorImpl( - Supplier supplier, - BiConsumer accumulator, - BinaryOperator combiner, - Set characteristics) { - this(supplier, accumulator, combiner, a -> (R) a, characteristics); - } - - @Override - public BiConsumer accumulator() { - return accumulator; - } - - @Override - public Supplier supplier() { - return supplier; - } - - @Override - public BinaryOperator combiner() { - return combiner; - } - - @Override - public Function finisher() { - return finisher; - } - - @Override - public Set characteristics() { - return characteristics; - } - } - - public static Collector> toObjectDictionary( - Function keyMapper, - Function valueMapper) { - return new CollectorImpl<>( - DictionaryFactory::newObjectDictionary, - uniqKeysAccumulator(keyMapper, valueMapper), - ObjectDictionary::append, - CH_ID); - } - - public static Collector> toLongDictionary( - Function keyMapper, - Function valueMapper) { - return new CollectorImpl<>( - DictionaryFactory::newLongDictionary, - uniqLongsAccumulator(keyMapper, valueMapper), - LongDictionary::append, - CH_ID); - } - - /** - * {@code BiConsumer} that accumulates (key, value) pairs extracted from elements into the - * dictionary, throwing {@code IllegalStateException} if duplicate keys are encountered. - * - * @param keyMapper a function that dictionaries an element into a key. - * @param valueMapper a function that dictionaries an element into a value. - * @param type of elements. - * @param type of dictionaries keys. - * @param type of dictionaries values. - * @return an accumulating consumer. - */ - private static BiConsumer, T> uniqKeysAccumulator( - Function keyMapper, - Function valueMapper) { - return (map, element) -> { - - K key = keyMapper.apply(element); - V value = ObjectUtils.notNull(valueMapper.apply(element)); - V prev = map.put(key, value); - - if (prev != null) { - throw duplicateKeyException(key, prev, value); - } - }; - } - - /** - * {@code BiConsumer} that accumulates (key, value) pairs extracted from elements into the - * dictionary, throwing {@code IllegalStateException} if duplicate keys are encountered. - * - * @param keyMapper a function that dictionaries an element into a key. - * @param valueMapper a function that dictionaries an element into a value. - * @param type of elements. - * @param type of dictionaries values. - * @return an accumulating consumer. - */ - private static BiConsumer, T> uniqLongsAccumulator( - Function keyMapper, - Function valueMapper) { - return (map, element) -> { - - var key = keyMapper.apply(element); - var value = ObjectUtils.notNull(valueMapper.apply(element)); - var prevValue = map.put(key.longValue(), value); - - if (prevValue != null) { - throw duplicateKeyException(key, prevValue, value); - } - }; - } - - /** - * Construct an {@code IllegalStateException} with appropriate message. - * - * @param k the duplicate key - * @param u 1st value to be accumulated/merged - * @param v 2nd value to be accumulated/merged - */ - private static IllegalStateException duplicateKeyException(Object k, Object u, Object v) { - return new IllegalStateException(String.format("Duplicate key %s (attempted merging values %s and %s)", k, u, v)); - } - - private DictionaryCollectors() { - throw new IllegalArgumentException(); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryFactory.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryFactory.java deleted file mode 100644 index 7f544bdb..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryFactory.java +++ /dev/null @@ -1,61 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import org.jspecify.annotations.NullMarked; - -/** - * The factory for creating new {@link Dictionary}. - * - * @author JavaSaBr - */ -@NullMarked -public final class DictionaryFactory { - - public static final ObjectDictionary EMPTY_OD = new ReadOnlyFastObjectDictionary<>(); - public static final LongDictionary EMPTY_LD = new ReadOnlyFastLongDictionary<>(); - - public static ConcurrentObjectDictionary newConcurrentStampedLockObjectDictionary() { - return new ConcurrentStampedLockObjectDictionary<>(); - } - - public static ConcurrentObjectDictionary newConcurrentStampedLockObjectDictionary( - float loadFactor, - int initCapacity) { - return new ConcurrentStampedLockObjectDictionary<>(loadFactor, initCapacity); - } - - public static IntegerDictionary newIntegerDictionary() { - return new FastIntegerDictionary<>(); - } - - public static IntegerDictionary newIntegerDictionary(float loadFactor, int initCapacity) { - return new FastIntegerDictionary<>(loadFactor, initCapacity); - } - - public static LongDictionary newLongDictionary() { - return new FastLongDictionary<>(); - } - - public static LongDictionary newLongDictionary(int initCapacity) { - return new FastLongDictionary<>(initCapacity); - } - - public static LongDictionary newLongDictionary(float loadFactor, int initCapacity) { - return new FastLongDictionary<>(loadFactor, initCapacity); - } - - public static ObjectDictionary newObjectDictionary() { - return new FastObjectDictionary<>(); - } - - public static ObjectDictionary newObjectDictionary(float loadFactor, int initCapacity) { - return new FastObjectDictionary<>(loadFactor, initCapacity); - } - - public static ObjectDictionary newReadOnlyObjectDictionary(Object... values) { - return new ReadOnlyFastObjectDictionary<>(values); - } - - private DictionaryFactory() { - throw new IllegalArgumentException(); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryUtils.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryUtils.java deleted file mode 100644 index e1bb15bc..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/DictionaryUtils.java +++ /dev/null @@ -1,6 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -/** - * @author JavaSaBr - */ -public class DictionaryUtils {} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/Entry.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/Entry.java deleted file mode 100644 index 3781d023..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/Entry.java +++ /dev/null @@ -1,46 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import javasabr.rlib.common.util.Reusable; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -@NullMarked -public interface Entry extends Reusable { - - /** - * Get the next entry. - * - * @return the next entry. - */ - @Nullable - T getNext(); - - /** - * Set the next entry. - * - * @param next the next entry. - */ - void setNext(@Nullable T next); - - /** - * Get the value. - * - * @return the value. - */ - V getValue(); - - /** - * Set the value. - * - * @param value the new value of this entry. - * @return the old value of null. - */ - V setValue(V value); - - /** - * Get the hash. - * - * @return the hash. - */ - int getHash(); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastIntegerDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastIntegerDictionary.java deleted file mode 100644 index 5cb313a7..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastIntegerDictionary.java +++ /dev/null @@ -1,76 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import javasabr.rlib.common.util.ArrayUtils; -import org.jspecify.annotations.NullMarked; - -/** - * The fast implementation of {@link IntegerDictionary} without threadsafe supporting. - * - * @param the type parameter - * @author JavaSaBr - */ -@NullMarked -public class FastIntegerDictionary extends AbstractIntegerDictionary implements UnsafeIntegerDictionary { - - private IntegerEntry[] entries; - - private int threshold; - private int size; - - protected FastIntegerDictionary() { - this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); - } - - protected FastIntegerDictionary(float loadFactor) { - this(loadFactor, DEFAULT_INITIAL_CAPACITY); - } - - protected FastIntegerDictionary(int initCapacity) { - this(DEFAULT_LOAD_FACTOR, initCapacity); - } - - protected FastIntegerDictionary(float loadFactor, int initCapacity) { - super(loadFactor, initCapacity); - this.entries = ArrayUtils.create(getEntryType(), initCapacity); - } - - @Override - public void setSize(int size) { - this.size = size; - } - - @Override - public void setEntries(IntegerEntry[] entries) { - this.entries = entries; - } - - @Override - public IntegerEntry [] entries() { - return entries; - } - - @Override - public void setThreshold(int threshold) { - this.threshold = threshold; - } - - @Override - public int getThreshold() { - return threshold; - } - - @Override - protected int decrementSizeAndGet() { - return --size; - } - - @Override - protected int incrementSizeAndGet() { - return ++size; - } - - @Override - public final int size() { - return size; - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastLongDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastLongDictionary.java deleted file mode 100644 index bdac1f9f..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastLongDictionary.java +++ /dev/null @@ -1,76 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import javasabr.rlib.common.util.ArrayUtils; -import org.jspecify.annotations.NullMarked; - -/** - * The fast implementation of {@link LongDictionary} without threadsafe supporting. - * - * @param the value's type. - * @author JavaSaBr - */ -@NullMarked -public class FastLongDictionary extends AbstractLongDictionary { - - private LongEntry[] entries; - - private int threshold; - private int size; - - protected FastLongDictionary() { - this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); - } - - protected FastLongDictionary(float loadFactor) { - this(loadFactor, DEFAULT_INITIAL_CAPACITY); - } - - protected FastLongDictionary(int initCapacity) { - this(DEFAULT_LOAD_FACTOR, initCapacity); - } - - protected FastLongDictionary(float loadFactor, int initCapacity) { - super(loadFactor, initCapacity); - this.entries = ArrayUtils.create(getEntryType(), initCapacity); - } - - @Override - public void setSize(int size) { - this.size = size; - } - - @Override - public void setEntries(LongEntry[] content) { - this.entries = content; - } - - @Override - public LongEntry [] entries() { - return entries; - } - - @Override - public void setThreshold(int threshold) { - this.threshold = threshold; - } - - @Override - public int getThreshold() { - return threshold; - } - - @Override - protected int decrementSizeAndGet() { - return --size; - } - - @Override - protected int incrementSizeAndGet() { - return ++size; - } - - @Override - public final int size() { - return size; - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastObjectDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastObjectDictionary.java deleted file mode 100644 index 86016e50..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/FastObjectDictionary.java +++ /dev/null @@ -1,77 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import javasabr.rlib.common.util.ArrayUtils; -import org.jspecify.annotations.NullMarked; - -/** - * The fast implementation of {@link ObjectDictionary} without threadsafe supporting. - * - * @param the key's type. - * @param the value's type. - * @author JavaSaBr - */ -@NullMarked -public class FastObjectDictionary extends AbstractObjectDictionary { - - private ObjectEntry[] entries; - - private int threshold; - private int size; - - protected FastObjectDictionary() { - this(DEFAULT_LOAD_FACTOR, DEFAULT_INITIAL_CAPACITY); - } - - protected FastObjectDictionary(float loadFactor) { - this(loadFactor, DEFAULT_INITIAL_CAPACITY); - } - - protected FastObjectDictionary(int initCapacity) { - this(DEFAULT_LOAD_FACTOR, initCapacity); - } - - protected FastObjectDictionary(float loadFactor, int initCapacity) { - super(loadFactor, initCapacity); - this.entries = ArrayUtils.create(getEntryType(), initCapacity); - } - - @Override - public void setSize(int size) { - this.size = size; - } - - @Override - public void setEntries(ObjectEntry[] entries) { - this.entries = entries; - } - - @Override - public ObjectEntry [] entries() { - return entries; - } - - @Override - public void setThreshold(int threshold) { - this.threshold = threshold; - } - - @Override - public int getThreshold() { - return threshold; - } - - @Override - protected int decrementSizeAndGet() { - return --size; - } - - @Override - protected int incrementSizeAndGet() { - return ++size; - } - - @Override - public int size() { - return size; - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntKey.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntKey.java deleted file mode 100644 index 295277b3..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntKey.java +++ /dev/null @@ -1,13 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -/** - * The type of the {@link Dictionary}. - * - * @author JavaSaBr - */ -public final class IntKey { - - private IntKey() { - throw new IllegalArgumentException(); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerDictionary.java deleted file mode 100644 index 807362a3..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerDictionary.java +++ /dev/null @@ -1,165 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import java.util.function.Function; -import java.util.function.IntFunction; -import java.util.function.Supplier; -import javasabr.rlib.common.function.IntBiObjectConsumer; -import javasabr.rlib.common.util.array.ArrayFactory; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -/** - * The interface to implement a dictionary which uses int as key. - * - * @param the value's type. - * @author JavaSaBr - */ -@NullMarked -public interface IntegerDictionary extends Dictionary { - - /** - * Create a new integer dictionary for the value's type. - * - * @param valueType the value's type. - * @param the value's type. - * @return the new integer dictionary. - */ - static IntegerDictionary ofType(Class valueType) { - return DictionaryFactory.newIntegerDictionary(); - } - - /** - * Create a new integer dictionary for the values. - * - * @param values the key-value values. - * @param the value's type. - * @return the new integer dictionary. - */ - static IntegerDictionary of(Object... values) { - - if (values.length < 2 || values.length % 2 != 0) { - throw new IllegalArgumentException("Incorrect argument's count."); - } - - IntegerDictionary dictionary = DictionaryFactory.newIntegerDictionary(); - - for (int i = 0, length = values.length - 2; i <= length; i += 2) { - dictionary.put((Integer) values[i], (V) values[i + 1]); - } - - return dictionary; - } - - /** - * Return true if this dictionary contains a mapping for the specified key. - * - * @param key key whose presence in this dictionary is to be tested. - * @return true if this dictionary contains a mapping for the specified key. - */ - default boolean containsKey(int key) { - throw new UnsupportedOperationException(); - } - - /** - * Return the value to which the specified key is mapped, or {@code null} if this dictionary contains no mapping for - * the key. - * - * @param key the key whose associated value is to be returned. - * @return the value to which the specified key is mapped, or {@code null} if this dictionary contains no mapping for - * the key. - */ - default @Nullable V get(final int key) { - throw new UnsupportedOperationException(); - } - - /** - * Get the value for the key. If the value doesn't exists, the factory will create new value, puts this value to this - * dictionary and return this value. - * - * @param key the key. - * @param factory the factory. - * @return the stored value by the key or the new value. - */ - default V getOrCompute(int key, Supplier factory) { - throw new UnsupportedOperationException(); - } - - /** - * Get the value for the key. If the value doesn't exists, the factory will create new value, puts this value to this - * dictionary and return this value. - * - * @param key the key. - * @param factory the factory. - * @return the stored value by the key or the new value. - */ - default V getOrCompute(int key, IntFunction factory) { - throw new UnsupportedOperationException(); - } - - /** - * Get the value for the key. If the value doesn't exists, the factory will create new value, puts this value to this - * dictionary and return this value. - * - * @param the argument's type. - * @param key the key. - * @param argument the additional argument. - * @param factory the factory. - * @return the stored value by the key or the new value. - * @see #getOrCompute(int, Object, Function) - */ - - default @Nullable V get(int key, @Nullable T argument, Function factory) { - return getOrCompute(key, argument, factory); - } - - /** - * Get the value for the key. If the value doesn't exists, the factory will create new value, puts this value to this - * dictionary and return this value. - * - * @param the argument's type. - * @param key the key. - * @param argument the additional argument. - * @param factory the factory. - * @return the stored value by the key or the new value. - */ - default @Nullable V getOrCompute( - int key, - T argument, - Function factory) { - throw new UnsupportedOperationException(); - } - - /** - * Put the value by the key. - * - * @param key the value's key. - * @param value the value. - * @return the previous value for the key or null. - */ - default @Nullable V put(int key, V value) { - throw new UnsupportedOperationException(); - } - - /** - * Remove a mapping of the key. - * - * @param key the key. - * @return the previous value for the key or null. - */ - default @Nullable V remove(int key) { - throw new UnsupportedOperationException(); - } - - /** - * Performs the given action for each key-value pair of this dictionary. - * - * @param argument the argument. - * @param consumer the consumer. - * @param the argument's type. - */ - default void forEach( - T argument, - IntBiObjectConsumer consumer) { - throw new UnsupportedOperationException(); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerDictionaryIterator.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerDictionaryIterator.java deleted file mode 100644 index e38d3541..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerDictionaryIterator.java +++ /dev/null @@ -1,92 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import java.util.Iterator; -import java.util.NoSuchElementException; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -/** - * The iterator to iterate {@link IntegerDictionary}. - * - * @param the value's type. - * @author JavaSaBr - */ -@NullMarked -public class IntegerDictionaryIterator implements Iterator { - - /** - * The dictionary. - */ - private final UnsafeIntegerDictionary dictionary; - - /** - * The next entry. - */ - private @Nullable IntegerEntry next; - - /** - * The current entry. - */ - private @Nullable IntegerEntry current; - - /** - * The current index. - */ - private int index; - - public IntegerDictionaryIterator(UnsafeIntegerDictionary dictionary) { - this.dictionary = dictionary; - - if (!dictionary.isEmpty()) { - IntegerEntry[] entries = dictionary.entries(); - while (index < entries.length && (next = entries[index++]) == null); - } - } - - @Override - public boolean hasNext() { - return next != null; - } - - @Override - public V next() { - return nextEntry().getValue(); - } - - /** - * Get the next entry. - * - * @return the next entry. - */ - private IntegerEntry nextEntry() { - - IntegerEntry[] content = dictionary.entries(); - IntegerEntry entry = next; - - if (entry == null) { - throw new NoSuchElementException(); - } - - if ((next = entry.getNext()) == null) { - while (index < content.length && (next = content[index++]) == null); - } - - current = entry; - - return entry; - } - - @Override - public void remove() { - - if (current == null) { - throw new IllegalStateException(); - } - - int key = current.getKey(); - - current = null; - - dictionary.removeEntryForKey(key); - } -} \ No newline at end of file diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerEntry.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerEntry.java deleted file mode 100644 index 927ee45d..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/IntegerEntry.java +++ /dev/null @@ -1,118 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import java.util.Objects; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -/** - * The entry of {@link IntegerDictionary}. - * - * @param the value's type. - * @author JavaSaBr - */ -@NullMarked -public class IntegerEntry implements Entry, V> { - - /** - * The next entry. - */ - private @Nullable IntegerEntry next; - - /** - * The value of this entry. - */ - private V value; - - /** - * The key of this entry. - */ - private int key; - - /** - * The hash of the key. - */ - private int hash; - - @Override - public boolean equals(@Nullable Object object) { - - if (object == null || object.getClass() != IntegerEntry.class) { - return false; - } - - IntegerEntry entry = (IntegerEntry) object; - - int firstKey = getKey(); - int secondKey = entry.getKey(); - - if (firstKey != secondKey) { - return false; - } - - Object firstValue = getValue(); - Object secondValue = entry.getValue(); - - return Objects.equals(firstValue, secondValue); - } - - @Override - public int getHash() { - return hash; - } - - /** - * Get the key. - * - * @return the key. - */ - public int getKey() { - return key; - } - - @Override - public @Nullable IntegerEntry getNext() { - return next; - } - - @Override - public void setNext(@Nullable IntegerEntry next) { - this.next = next; - } - - @Override - public V getValue() { - return value; - } - - @Override - public final int hashCode() { - return key ^ value.hashCode(); - } - - /** - * Set all fields of this entry. - * - * @param hash the hash. - * @param key the key. - * @param value the value. - * @param next the next. - */ - public void set(int hash, int key, V value, @Nullable IntegerEntry next) { - this.value = value; - this.next = next; - this.key = key; - this.hash = hash; - } - - @Override - public V setValue(V value) { - V old = getValue(); - this.value = value; - return old; - } - - @Override - public final String toString() { - return "Entry : " + key + " = " + value; - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongDictionary.java deleted file mode 100644 index c275f205..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongDictionary.java +++ /dev/null @@ -1,173 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import java.util.function.Function; -import java.util.function.LongFunction; -import java.util.function.Supplier; -import javasabr.rlib.common.function.LongBiObjectConsumer; -import javasabr.rlib.common.function.LongObjectConsumer; -import javasabr.rlib.common.util.ClassUtils; -import javasabr.rlib.common.util.array.ArrayFactory; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -/** - * The interface to implement a dictionary which uses long as key. - * - * @param the value's type. - * @author JavaSaBr - */ -@NullMarked -public interface LongDictionary extends Dictionary { - - /** - * Get an empty read-only long dictionary. - * - * @param the value's type. - * @return the read-only empty dictionary. - */ - static LongDictionary empty() { - return ClassUtils.unsafeNNCast(DictionaryFactory.EMPTY_LD); - } - - /** - * Create a new long dictionary for the value's type. - * - * @param valueType the value's type. - * @param the value's type. - * @return the new long dictionary. - */ - static LongDictionary ofType(Class valueType) { - return DictionaryFactory.newLongDictionary(); - } - - /** - * Create a new long dictionary for the values. - * - * @param values the key-value values. - * @param the value's type. - * @return the new long dictionary. - */ - static LongDictionary of(Object... values) { - - if (values.length < 2 || values.length % 2 != 0) { - throw new IllegalArgumentException("Incorrect argument's count."); - } - - var dictionary = DictionaryFactory.newLongDictionary(); - - for (int i = 0, length = values.length - 2; i <= length; i += 2) { - dictionary.put(((Number) values[i]).longValue(), (V) values[i + 1]); - } - - return dictionary; - } - - static > M append(M first, M second) { - second.copyTo(first); - return first; - } - - /** - * Return true if this dictionary contains a mapping for the specified key. - * - * @param key key whose presence in this dictionary is to be tested. - * @return true if this dictionary contains a mapping for the specified key. - */ - default boolean containsKey(long key) { - throw new UnsupportedOperationException(); - } - - /** - * Return the value to which the specified key is mapped, or {@code null} if this dictionary contains no mapping for - * the key. - * - * @param key the key whose associated value is to be returned. - * @return the value to which the specified key is mapped, or {@code null} if this dictionary contains no mapping for - * the key. - */ - default @Nullable V get(long key) { - throw new UnsupportedOperationException(); - } - - /** - * Get the value for the key. If the value doesn't exists, the factory will create new value, puts this value to this - * dictionary and return this value. - * - * @param key the key. - * @param factory the factory. - * @return the stored value by the key or the new value. - */ - default V getOrCompute(long key, Supplier factory) { - throw new UnsupportedOperationException(); - } - - /** - * Get the value for the key. If the value doesn't exists, the factory will create new value, puts this value to this - * dictionary and return this value. - * - * @param key the key. - * @param factory the factory. - * @return the stored value by the key or the new value. - */ - default V getOrCompute(long key, LongFunction factory) { - throw new UnsupportedOperationException(); - } - - /** - * Get the value for the key. If the value doesn't exists, the factory will create new value, puts this value to this - * dictionary and return this value. - * - * @param the argument's type. - * @param key the key. - * @param argument the additional argument. - * @param factory the factory. - * @return the stored value by the key or the new value. - */ - default @Nullable V getOrCompute( - long key, - T argument, - Function factory) { - throw new UnsupportedOperationException(); - } - - /** - * Put the value by the key. - * - * @param key the value's key. - * @param value the value. - * @return the previous value for the key or null. - */ - default @Nullable V put(long key, V value) { - throw new UnsupportedOperationException(); - } - - /** - * Remove a mapping of the key. - * - * @param key the key. - * @return the previous value for the key or null. - */ - default @Nullable V remove(long key) { - throw new UnsupportedOperationException(); - } - - /** - * Performs the given action for each key-value pair of this dictionary. - * - * @param consumer the consumer. - */ - default void forEach(LongObjectConsumer consumer) { - throw new UnsupportedOperationException(); - } - - /** - * Performs the given action for each key-value pair of this dictionary. - * - * @param argument the argument. - * @param consumer the consumer. - * @param the argument's type. - */ - default void forEach(T argument, LongBiObjectConsumer consumer) { - throw new UnsupportedOperationException(); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongDictionaryIterator.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongDictionaryIterator.java deleted file mode 100644 index 2e205753..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongDictionaryIterator.java +++ /dev/null @@ -1,92 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import java.util.Iterator; -import java.util.NoSuchElementException; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -/** - * The iterator to iterate {@link LongDictionary}. - * - * @param the value's type. - * @author JavaSaBr - */ -@NullMarked -public class LongDictionaryIterator implements Iterator { - - /** - * The dictionary. - */ - private final UnsafeLongDictionary dictionary; - - /** - * The next entry. - */ - private @Nullable LongEntry next; - - /** - * The current entry. - */ - private @Nullable LongEntry current; - - /** - * The current index. - */ - private int index; - - public LongDictionaryIterator(UnsafeLongDictionary dictionary) { - this.dictionary = dictionary; - - if (!dictionary.isEmpty()) { - LongEntry[] entries = dictionary.entries(); - while (index < entries.length && (next = entries[index++]) == null); - } - } - - @Override - public boolean hasNext() { - return next != null; - } - - @Override - public V next() { - return nextEntry().getValue(); - } - - /** - * Get the next entry. - * - * @return the next entry. - */ - private LongEntry nextEntry() { - - LongEntry[] entries = dictionary.entries(); - LongEntry entry = next; - - if (entry == null) { - throw new NoSuchElementException(); - } - - if ((next = entry.getNext()) == null) { - while (index < entries.length && (next = entries[index++]) == null); - } - - current = entry; - - return entry; - } - - @Override - public void remove() { - - if (current == null) { - throw new IllegalStateException(); - } - - long key = current.getKey(); - - current = null; - - dictionary.removeEntryForKey(key); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongEntry.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongEntry.java deleted file mode 100644 index bdfb7a98..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongEntry.java +++ /dev/null @@ -1,117 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import java.util.Objects; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -/** - * The entry of {@link LongDictionary}. - * - * @param the value's type. - * @author JavaSaBr - */ -@NullMarked -public final class LongEntry implements Entry, V> { - - /** - * The next entry. - */ - private @Nullable LongEntry next; - - /** - * The value of this entry. - */ - private V value; - - /** - * The key of this entry. - */ - private long key; - /** - * The hash of the key. - */ - private int hash; - - @Override - public boolean equals(@Nullable Object object) { - - if (object == null || object.getClass() != LongEntry.class) { - return false; - } - - LongEntry entry = (LongEntry) object; - - long firstKey = getKey(); - long secondKey = entry.getKey(); - - if (firstKey != secondKey) { - return false; - } - - Object firstValue = getValue(); - Object secondValue = entry.getValue(); - - return Objects.equals(firstValue, secondValue); - } - - @Override - public int getHash() { - return hash; - } - - /** - * Get the key. - * - * @return the key. - */ - public long getKey() { - return key; - } - - @Override - public @Nullable LongEntry getNext() { - return next; - } - - @Override - public void setNext(@Nullable LongEntry next) { - this.next = next; - } - - @Override - public V getValue() { - return value; - } - - @Override - public final int hashCode() { - return (int) (key ^ value.hashCode()); - } - - /** - * Set all fields of this entry. - * - * @param hash the hash. - * @param key the key. - * @param value the value. - * @param next the next. - */ - public void set(int hash, long key, V value, @Nullable LongEntry next) { - this.value = value; - this.next = next; - this.key = key; - this.hash = hash; - } - - @Override - public V setValue(V value) { - V old = getValue(); - this.value = value; - return old; - } - - @Override - public String toString() { - return "LongEntry{" + "next=" + next + ", value=" + value + ", key=" + key + ", hash=" + hash + '}'; - } -} \ No newline at end of file diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongKey.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongKey.java deleted file mode 100644 index 16fe3098..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/LongKey.java +++ /dev/null @@ -1,13 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -/** - * The type of the {@link Dictionary}. - * - * @author JavaSaBr - */ -public final class LongKey { - - private LongKey() { - throw new IllegalArgumentException(); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectDictionary.java deleted file mode 100644 index 252e26cf..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectDictionary.java +++ /dev/null @@ -1,298 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import java.util.Optional; -import javasabr.rlib.common.function.FourObjectConsumer; -import javasabr.rlib.common.function.NotNullBiConsumer; -import javasabr.rlib.common.function.NotNullBiFunction; -import javasabr.rlib.common.function.NotNullFunction; -import javasabr.rlib.common.function.NotNullSupplier; -import javasabr.rlib.common.function.NotNullTripleConsumer; -import javasabr.rlib.common.util.ClassUtils; -import javasabr.rlib.common.util.array.Array; -import javasabr.rlib.common.util.array.ArrayFactory; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -/** - * The interface for implementing a key-value dictionary which using an object key. - * - * @param the key's type. - * @param the value's type. - * @author JavaSaBr - */ -@NullMarked -public interface ObjectDictionary extends Dictionary { - - /** - * Create a new object dictionary for the key's type and value's type. - * - * @param keyValueType the key's and value's type. - * @param the key's and value's type. - * @return the new object dictionary. - */ - static ObjectDictionary ofType(Class keyValueType) { - return DictionaryFactory.newObjectDictionary(); - } - - /** - * Create a new object dictionary for the key's type and value's type. - * - * @param keyType the key's type. - * @param valueType the value's type. - * @param the key's type. - * @param the value's type. - * @return the new object dictionary. - */ - static ObjectDictionary ofType( - Class keyType, - Class valueType) { - return DictionaryFactory.newObjectDictionary(); - } - - /** - * Create a new object dictionary for the values. - * - * @param values the key-value values. - * @param the key's type. - * @param the value's type. - * @return the new object dictionary. - */ - static ObjectDictionary of(Object... values) { - return new ReadOnlyFastObjectDictionary<>(values); - } - - /** - * Get an empty read-only object dictionary. - * - * @param the key's type. - * @param the value's type. - * @return the read-only empty dictionary. - */ - static ObjectDictionary empty() { - return ClassUtils.unsafeNNCast(DictionaryFactory.EMPTY_OD); - } - - static > M append(M first, M second) { - second.copyTo(first); - return first; - } - - /** - * Return true if this dictionary contains a mapping for the specified key. - * - * @param key key whose presence in this dictionary is to be tested. - * @return true if this dictionary contains a mapping for the specified key. - */ - default boolean containsKey(K key) { - throw new UnsupportedOperationException(); - } - - /** - * Return the value to which the specified key is mapped, or {@code null} if this dictionary contains no mapping for - * the key. - * - * @param key the key whose associated value is to be returned. - * @return the value to which the specified key is mapped, or {@code null} if this dictionary contains no mapping for - * the key. - */ - default @Nullable V get(K key) { - throw new UnsupportedOperationException(); - } - - /** - * Return the value to which the specified key is mapped, or default if this dictionary contains no mapping for the - * key. - * - * @param key the key whose associated value is to be returned. - * @param def the default value if no value in this dictionary. - * @return the value to which the specified key is mapped, or default if this dictionary contains no mapping for the - * key. - */ - default @Nullable V getOrDefault(K key, V def) { - var value = get(key); - return value == null ? def : value; - } - - /** - * Return the optional value to which the specified key is mapped, or {@code null} if this dictionary contains no - * mapping for the key. - * - * @param key the key whose associated value is to be returned. - * @return the optional value to which the specified key is mapped. - */ - default Optional getOptional(K key) { - return Optional.ofNullable(get(key)); - } - - /** - * Get the value for the key. If the value doesn't exists, the factory will create new value, puts this value to this - * dictionary and return this value. - * - * @param key the key. - * @param factory the factory. - * @return the stored value by the key or the new value. - */ - default V getOrCompute(K key, NotNullSupplier factory) { - throw new UnsupportedOperationException(); - } - - /** - * Get the value for the key. If the value doesn't exists, the factory will create new value, puts this value to this - * dictionary and return this value. - * - * @param key the key. - * @param factory the factory. - * @return the stored value by the key or the new value. - */ - default V getOrCompute(K key, NotNullFunction factory) { - throw new UnsupportedOperationException(); - } - - /** - * Get the value for the key. If the value doesn't exists, the factory will create new value, puts this value to this - * dictionary and return this value. - * - * @param the argument's type. - * @param key the key. - * @param argument the additional argument. - * @param factory the factory. - * @return the stored value by the key or the new value. - */ - default V getOrCompute(K key, T argument, NotNullFunction factory) { - throw new UnsupportedOperationException(); - } - - /** - * Get the value for the key. If the value doesn't exists, the factory will create new value, puts this value to this - * dictionary and return this value. - * - * @param the argument's type. - * @param key the key. - * @param argument the additional argument. - * @param factory the factory. - * @return the stored value by the key or the new value. - * @see #getOrCompute(Object, Object, NotNullBiFunction) - */ - default V get(K key, T argument, NotNullBiFunction factory) { - return getOrCompute(key, argument, factory); - } - - /** - * Get the value for the key. If the value doesn't exists, the factory will create new value, puts this value to this - * dictionary and return this value. - * - * @param the argument's type. - * @param key the key. - * @param argument the additional argument. - * @param factory the factory. - * @return the stored value by the key or the new value. - */ - default V getOrCompute( - K key, - T argument, - NotNullBiFunction factory) { - throw new UnsupportedOperationException(); - } - - /** - * Put to the array all keys of this dictionary. - * - * @param container the container. - * @return the array with all keys. - */ - default Array keyArray(Array container) { - throw new UnsupportedOperationException(); - } - - /** - * Create an array with all keys of this dictionary. - * - * @param type the key's type. - * @return the array with all keys of this dictionary. - */ - default Array keyArray(Class type) { - return keyArray(ArrayFactory.newArray(type, size())); - } - - /** - * Put the value by the key. - * - * @param key the value's key. - * @param value the value. - * @return the previous value for the key or null. - */ - default @Nullable V put(K key, V value) { - throw new UnsupportedOperationException(); - } - - /** - * Put the value by the key. - * - * @param key the value's key. - * @param value the value. - * @return the optional value of the previous value for the key. - */ - default Optional putOptional(K key, V value) { - return Optional.ofNullable(put(key, value)); - } - - /** - * Remove a mapping by the key. - * - * @param key the key. - * @return the previous value for the key or null. - */ - default @Nullable V remove(K key) { - throw new UnsupportedOperationException(); - } - - /** - * Remove a mapping by the key. - * - * @param key the key. - * @return the optional value of the previous value for the key. - */ - default Optional removeOptional(K key) { - return Optional.ofNullable(remove(key)); - } - - /** - * Performs the given action for each key-value pair of this dictionary. - * - * @param consumer the consumer. - */ - default void forEach(NotNullBiConsumer consumer) { - throw new UnsupportedOperationException(); - } - - /** - * Performs the given action for each key-value pair of this dictionary. - * - * @param argument the argument. - * @param consumer the consumer. - * @param the argument's type. - */ - default void forEach( - T argument, - NotNullTripleConsumer consumer) { - throw new UnsupportedOperationException(); - } - - /** - * Performs the given action for each key-value pair of this dictionary. - * - * @param first the first argument. - * @param second the second argument. - * @param consumer the consumer. - * @param the first argument's type. - * @param the second argument's type. - */ - default void forEach( - F first, - S second, - FourObjectConsumer consumer) { - throw new UnsupportedOperationException(); - } -} - - diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectDictionaryIterator.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectDictionaryIterator.java deleted file mode 100644 index 18c53805..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectDictionaryIterator.java +++ /dev/null @@ -1,95 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import java.util.Iterator; -import java.util.NoSuchElementException; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -/** - * The iterator to iterate {@link ObjectDictionary}. - * - * @param the key's type. - * @param the value's type. - * @author JavaSaBr - */ -@NullMarked -public class ObjectDictionaryIterator implements Iterator { - - /** - * The dictionary. - */ - private final UnsafeObjectDictionary dictionary; - - /** - * The next entry. - */ - private @Nullable ObjectEntry next; - - /** - * The current entry. - */ - private @Nullable ObjectEntry current; - - /** - * The current index. - */ - private int index; - - public ObjectDictionaryIterator(UnsafeObjectDictionary dictionary) { - this.dictionary = dictionary; - - if (!dictionary.isEmpty()) { - var entries = dictionary.entries(); - while (index < entries.length && (next = entries[index++]) == null); - } - } - - @Override - public boolean hasNext() { - return next != null; - } - - @Override - public V next() { - //noinspection ConstantConditions - return nextEntry().getValue(); - } - - /** - * Get the next entry. - * - * @return the next entry. - */ - private ObjectEntry nextEntry() { - - var entries = dictionary.entries(); - var entry = next; - - if (entry == null) { - throw new NoSuchElementException(); - } - - if ((next = entry.getNext()) == null) { - while (index < entries.length && (next = entries[index++]) == null); - } - - current = entry; - - return entry; - } - - @Override - public void remove() { - - if (current == null) { - throw new IllegalStateException(); - } - - K key = current.getKey(); - - current = null; - - //noinspection ConstantConditions - dictionary.removeEntryForKey(key); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectEntry.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectEntry.java deleted file mode 100644 index 9f6a8a02..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ObjectEntry.java +++ /dev/null @@ -1,97 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import java.util.Objects; -import lombok.Getter; -import lombok.Setter; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -/** - * The entry of {@link ObjectDictionary}. - * - * @param the key's type. - * @param the value's type. - * @author JavaSaBr - */ -@NullMarked -public class ObjectEntry implements Entry, V> { - - /** - * The next entry. - */ - @Setter - @Getter - private @Nullable ObjectEntry next; - - /** - * The key of this entry. - */ - @Getter - private @Nullable K key; - - /** - * The value of this entry. - */ - @Getter - private @Nullable V value; - - /** - * The hash of the key. - */ - @Getter - private int hash; - - @Override - public boolean equals(@Nullable Object object) { - - if (object == null || object.getClass() != ObjectEntry.class) { - return false; - } - - var entry = (ObjectEntry) object; - var firstKey = getKey(); - var secondKey = entry.getKey(); - - if (!Objects.equals(firstKey, secondKey)) { - return false; - } - - var firstValue = getValue(); - var secondValue = entry.getValue(); - - return Objects.equals(firstValue, secondValue); - } - - @Override - public final int hashCode() { - return Objects.hashCode(key) ^ Objects.hashCode(value); - } - - /** - * Set all fields of this entry. - * - * @param hash the hash. - * @param key the key. - * @param value the value. - * @param next the next entry. - */ - public void set(int hash, K key, V value, @Nullable ObjectEntry next) { - this.value = value; - this.next = next; - this.key = key; - this.hash = hash; - } - - @Override - @SuppressWarnings("ConstantConditions") - public V setValue(V value) { - var old = getValue(); - this.value = value; - return old; - } - - @Override - public final String toString() { - return "Entry : " + key + " = " + value; - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ReadOnlyFastLongDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ReadOnlyFastLongDictionary.java deleted file mode 100644 index 544d49f3..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ReadOnlyFastLongDictionary.java +++ /dev/null @@ -1,41 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import lombok.NoArgsConstructor; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -/** - * The fast read-only implementation of {@link LongDictionary} without threadsafe supporting. - * - * @param the value's type. - * @author JavaSaBr - */ -@NullMarked -@NoArgsConstructor -public class ReadOnlyFastLongDictionary extends FastLongDictionary { - - @Override - public void put(Dictionary dictionary) { - throw new IllegalStateException("Dictionary is only read."); - } - - @Override - public @Nullable V put(long key, @Nullable V value) { - throw new IllegalStateException("Dictionary is only read."); - } - - @Override - public @Nullable V remove(long key) { - throw new IllegalStateException("Dictionary is only read."); - } - - @Override - public @Nullable LongEntry removeEntryForKey(long key) { - throw new IllegalStateException("Dictionary is only read."); - } - - @Override - public void clear() { - throw new IllegalStateException("Dictionary is only read."); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ReadOnlyFastObjectDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ReadOnlyFastObjectDictionary.java deleted file mode 100644 index 23c41a8d..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/ReadOnlyFastObjectDictionary.java +++ /dev/null @@ -1,54 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import lombok.NoArgsConstructor; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -/** - * The fast read-only implementation of {@link ObjectDictionary} without threadsafe supporting. - * - * @param the key's type. - * @param the value's type. - * @author JavaSaBr - */ -@NullMarked -@NoArgsConstructor -public class ReadOnlyFastObjectDictionary extends FastObjectDictionary { - - public ReadOnlyFastObjectDictionary(Object... values) { - - if (values.length < 2 || values.length % 2 != 0) { - throw new IllegalArgumentException("Incorrect argument's count."); - } - - for (int i = 0, length = values.length - 2; i <= length; i += 2) { - //noinspection unchecked - super.put((K) values[i], (V) values[i + 1]); - } - } - - @Override - public void put(Dictionary dictionary) { - throw new IllegalStateException("Dictionary is readonly."); - } - - @Override - public @Nullable V put(K key, @Nullable V value) { - throw new IllegalStateException("Dictionary is readonly."); - } - - @Override - public @Nullable V remove(K key) { - throw new IllegalStateException("Dictionary is readonly."); - } - - @Override - public @Nullable ObjectEntry removeEntryForKey(K key) { - throw new IllegalStateException("Dictionary is readonly."); - } - - @Override - public void clear() { - throw new IllegalStateException("Dictionary is readonly."); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeIntegerDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeIntegerDictionary.java deleted file mode 100644 index 786efeb6..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeIntegerDictionary.java +++ /dev/null @@ -1,30 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -/** - * The interface for implementing Unsafe part of {@link IntegerDictionary} API. - * - * @param the type parameter - * @author JavaSaBr - */ -@NullMarked -public interface UnsafeIntegerDictionary extends IntegerDictionary { - - /** - * Get an array of all entries in this dictionary. - * - * @return the array of entries. - */ - IntegerEntry[] entries(); - - /** - * Remove an entry for the key. - * - * @param key the key of the entry. - * @return removed entry. - */ - @Nullable - IntegerEntry removeEntryForKey(final int key); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeLongDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeLongDictionary.java deleted file mode 100644 index f9700e70..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeLongDictionary.java +++ /dev/null @@ -1,30 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -/** - * The interface for implementing Unsafe part of {@link LongDictionary} API. - * - * @param the type parameter - * @author JavaSaBr - */ -@NullMarked -public interface UnsafeLongDictionary extends LongDictionary { - - /** - * Get an array of all entries in this dictionary. - * - * @return the array of entries. - */ - LongEntry[] entries(); - - /** - * Remove an entry for the key. - * - * @param key the key of the entry. - * @return removed entry. - */ - @Nullable - LongEntry removeEntryForKey(long key); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeObjectDictionary.java b/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeObjectDictionary.java deleted file mode 100644 index d3661237..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/dictionary/UnsafeObjectDictionary.java +++ /dev/null @@ -1,30 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -/** - * The interface for implementing Unsafe part of {@link ObjectDictionary} API. - * - * @param the type parameter - * @param the type parameter - * @author JavaSaBr - */ -@NullMarked -public interface UnsafeObjectDictionary extends ObjectDictionary { - - /** - * Get an array of all entries in this dictionary. - * - * @return the array of entries. - */ - ObjectEntry[] entries(); - - /** - * Remove an entry for the key. - * - * @param key the key of the entry. - * @return removed entry. - */ - @Nullable ObjectEntry removeEntryForKey(K key); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/random/FastRandom.java b/rlib-common/src/main/java/javasabr/rlib/common/util/random/FastRandom.java deleted file mode 100644 index 0f97cd39..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/random/FastRandom.java +++ /dev/null @@ -1,79 +0,0 @@ -package javasabr.rlib.common.util.random; - -import org.jspecify.annotations.NullMarked; - -/** - * @author JavaSaBr - */ -@NullMarked -public final class FastRandom implements Random { - - /** - * Генератор чисел. - */ - private final java.util.Random random; - - /** - * Instantiates a new Fast random. - */ - public FastRandom() { - this.random = new java.util.Random(); - } - - @Override - public void byteArray(byte [] array, int offset, int length) { - length += offset; - for (int i = offset; i < length; i++) { - array[i] = (byte) nextInt(256); - } - } - - @Override - public boolean chance(float chance) { - - if (chance < 0F) { - return false; - } else if (chance > 99.999999F) { - return true; - } - - return nextFloat() * nextInt(100) <= chance; - } - - @Override - public boolean chance(int chance) { - - if (chance < 1) { - return false; - } else if (chance > 99) { - return true; - } - - return nextInt(99) <= chance; - } - - @Override - public float nextFloat() { - return random.nextFloat(); - } - - @Override - public int nextInt() { - return random.nextInt(); - } - - @Override - public int nextInt(int max) { - return random.nextInt(max); - } - - @Override - public int nextInt(int min, int max) { - return min + nextInt(Math.abs(max - min) + 1); - } - - @Override - public long nextLong(long min, long max) { - return min + Math.round(nextFloat() * Math.abs(max - min) + 1); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/random/Random.java b/rlib-common/src/main/java/javasabr/rlib/common/util/random/Random.java deleted file mode 100644 index 066bdcd3..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/random/Random.java +++ /dev/null @@ -1,74 +0,0 @@ -package javasabr.rlib.common.util.random; - -/** - * The interface to implement a random. - * - * @author JavaSaBr - */ -public interface Random { - - /** - * Fill an array random values. - * - * @param array the array. - * @param offset the offset. - * @param length the length. - */ - void byteArray(byte[] array, int offset, int length); - - /** - * Try to get success. - * - * @param chance the chance from 0 to 100. - * @return true if the chance was successful. - */ - boolean chance(float chance); - - /** - * Try to get success. - * - * @param chance the chance from 0 to 100. - * @return true if the chance was successful. - */ - boolean chance(int chance); - - /** - * Get a next random float value. - * - * @return the next value from 0.0 to 1.0. - */ - float nextFloat(); - - /** - * Get a next random int value. - * - * @return the next value from int_min to int_max. - */ - int nextInt(); - - /** - * Get a next random int value. - * - * @param max the max value. - * @return the next value [0, max]. - */ - int nextInt(int max); - - /** - * Get a next random int value. - * - * @param min the min value. - * @param max the max value. - * @return the next value [min, max]. - */ - int nextInt(int min, int max); - - /** - * Get a next random long value. - * - * @param min the min value. - * @param max the max value. - * @return the next value [min, max]. - */ - long nextLong(long min, long max); -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/random/RandomFactory.java b/rlib-common/src/main/java/javasabr/rlib/common/util/random/RandomFactory.java deleted file mode 100644 index 960c2ca3..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/random/RandomFactory.java +++ /dev/null @@ -1,22 +0,0 @@ -package javasabr.rlib.common.util.random; - -/** - * The factory of randoms implementations. - * - * @author JavaSaBr - */ -public final class RandomFactory { - - /** - * New fast random random. - * - * @return the random - */ - public static Random newFastRandom() { - return new FastRandom(); - } - - private RandomFactory() { - throw new RuntimeException(); - } -} diff --git a/rlib-common/src/main/java/javasabr/rlib/common/util/random/package-info.java b/rlib-common/src/main/java/javasabr/rlib/common/util/random/package-info.java deleted file mode 100644 index b426bf69..00000000 --- a/rlib-common/src/main/java/javasabr/rlib/common/util/random/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -@NullMarked -package javasabr.rlib.common.util.random; - -import org.jspecify.annotations.NullMarked; \ No newline at end of file diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/ArrayUtilsTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/ArrayUtilsTest.java deleted file mode 100644 index d008c665..00000000 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/ArrayUtilsTest.java +++ /dev/null @@ -1,138 +0,0 @@ -package javasabr.rlib.common.util; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import javasabr.rlib.common.util.array.ArrayFactory; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * Test of methods in ArrayUtils class. - * - * @author JavaSaBr - */ -public class ArrayUtilsTest { - - @Test - void convertIntegerArrayToIntArrayTest() { - - Integer[] integers = ArrayFactory.toArray(1, 2, 3, 4, 5); - int[] ints = ArrayUtils.toIntArray(integers); - int[] empty = ArrayUtils.toIntArray(new Integer[0]); - - assertArrayEquals(ints, ArrayFactory.toIntArray(1, 2, 3, 4, 5)); - assertArrayEquals(empty, ArrayFactory.toIntArray()); - } - - @Test - void convertStringToIntArrayTest() { - - assertArrayEquals(ArrayUtils.toIntArray("1,2,3,4,5", ","), ArrayFactory.toIntArray(1, 2, 3, 4, 5)); - assertArrayEquals(ArrayUtils.toIntArray(" 1 ,2 , 3,4, 5", ","), ArrayFactory.toIntArray(1, 2, 3, 4, 5)); - assertArrayEquals(ArrayUtils.toIntArray(" 1 ,2 , 3,4, 5", ","), ArrayFactory.toIntArray(1, 2, 3, 4, 5)); - - assertThrows(NumberFormatException.class, () -> ArrayUtils.toIntArray(" 1 ,,2 , 3,4, 5,", ",")); - assertThrows(NumberFormatException.class, () -> ArrayUtils.toIntArray(" 1 ,qwd , 3,4, 5", ",")); - assertThrows(NumberFormatException.class, () -> ArrayUtils.toIntArray(" 1 ,2.5 , 3,4, 5", ",")); - } - - @Test - void mapNullableTest() { - - String[] nullStrings = null; - String[] emptyStrings = new String[0]; - String[] singleStrings = ArrayFactory.toArray("5"); - String[] strings = ArrayFactory.toArray("8", "1", "6"); - - Assertions.assertNull(ArrayUtils.mapNullable(nullStrings, Integer::parseInt, Integer.class)); - - assertArrayEquals(new Integer[0], ArrayUtils.mapNullable(emptyStrings, Integer::parseInt, Integer.class)); - assertArrayEquals(ArrayFactory.toArray(5), ArrayUtils.mapNullable(singleStrings, Integer::parseInt, Integer.class)); - assertArrayEquals(ArrayFactory.toArray(8, 1, 6), ArrayUtils.mapNullable(strings, Integer::parseInt, Integer.class)); - } - - @Test - void longsToIntsTest() { - - assertArrayEquals(ArrayFactory.toIntArray(1, 5, 3), ArrayUtils.longsToInts(ArrayFactory.toLongArray(1, 5, 3))); - - assertArrayEquals(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.longsToInts(ArrayUtils.EMPTY_LONG_ARRAY)); - } - - @Test - void mapTest() { - - String[] emptyStrings = new String[0]; - String[] singleStrings = ArrayFactory.toArray("5"); - String[] strings = ArrayFactory.toArray("8", "1", "6"); - - assertArrayEquals(new Integer[0], ArrayUtils.map(emptyStrings, Integer::parseInt, Integer.class)); - assertArrayEquals(ArrayFactory.toArray(5), ArrayUtils.map(singleStrings, Integer::parseInt, Integer.class)); - assertArrayEquals(ArrayFactory.toArray(8, 1, 6), ArrayUtils.map(strings, Integer::parseInt, Integer.class)); - } - - @Test - void mapWithDefTest() { - - String[] nullStrings = null; - String[] emptyStrings = new String[0]; - String[] singleStrings = ArrayFactory.toArray("5"); - String[] strings = ArrayFactory.toArray("8", "1", "6"); - - assertArrayEquals(new Integer[0], ArrayUtils.map(nullStrings, Integer::parseInt, new Integer[0])); - - assertArrayEquals(new Integer[0], ArrayUtils.map(emptyStrings, Integer::parseInt, new Integer[0])); - assertArrayEquals(ArrayFactory.toArray(5), ArrayUtils.map(singleStrings, Integer::parseInt, new Integer[0])); - assertArrayEquals(ArrayFactory.toArray(8, 1, 6), ArrayUtils.map(strings, Integer::parseInt, new Integer[0])); - } - - @Test - void copyOfAndExtendTest() { - - var array = ArrayFactory.toArray("First", "Second"); - var newArray = ArrayUtils.copyOfAndExtend(array, 2); - - assertEquals(4, newArray.length); - assertArrayEquals(ArrayFactory.toArray("First", "Second", null, null), newArray); - } - - @Test - void isNotEmptyTest() { - - assertTrue(ArrayUtils.isNotEmpty(new byte[1])); - assertFalse(ArrayUtils.isNotEmpty(new byte[0])); - assertFalse(ArrayUtils.isNotEmpty((byte[]) null)); - - assertTrue(ArrayUtils.isNotEmpty(new short[1])); - assertFalse(ArrayUtils.isNotEmpty(new short[0])); - assertFalse(ArrayUtils.isNotEmpty((short[]) null)); - - assertTrue(ArrayUtils.isNotEmpty(new int[1])); - assertFalse(ArrayUtils.isNotEmpty(new int[0])); - assertFalse(ArrayUtils.isNotEmpty((int[]) null)); - - assertTrue(ArrayUtils.isNotEmpty(new char[1])); - assertFalse(ArrayUtils.isNotEmpty(new char[0])); - assertFalse(ArrayUtils.isNotEmpty((char[]) null)); - - assertTrue(ArrayUtils.isNotEmpty(new long[1])); - assertFalse(ArrayUtils.isNotEmpty(new long[0])); - assertFalse(ArrayUtils.isNotEmpty((long[]) null)); - - assertTrue(ArrayUtils.isNotEmpty(new float[1])); - assertFalse(ArrayUtils.isNotEmpty(new float[0])); - assertFalse(ArrayUtils.isNotEmpty((float[]) null)); - - assertTrue(ArrayUtils.isNotEmpty(new double[1])); - assertFalse(ArrayUtils.isNotEmpty(new double[0])); - assertFalse(ArrayUtils.isNotEmpty((double[]) null)); - - assertTrue(ArrayUtils.isNotEmpty(new Object[1])); - assertFalse(ArrayUtils.isNotEmpty(new Object[0])); - assertFalse(ArrayUtils.isNotEmpty((Object[]) null)); - } -} diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/VarTableTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/VarTableTest.java deleted file mode 100644 index e1976c54..00000000 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/VarTableTest.java +++ /dev/null @@ -1,167 +0,0 @@ -package javasabr.rlib.common.util; - -import static javasabr.rlib.common.util.array.ArrayFactory.toArray; -import static javasabr.rlib.common.util.array.ArrayFactory.toBooleanArray; -import static javasabr.rlib.common.util.array.ArrayFactory.toIntArray; - -import javasabr.rlib.common.util.array.ArrayFactory; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * The list of tests {@link VarTable}. - * - * @author JavaSaBr - */ -public class VarTableTest { - - @Test - void testAllGets() { - - var vars = new VarTable(); - vars.put("number", 10); - vars.put("array", toArray(1, 2, 3, 4)); - vars.put("arrayString", "1,2,3,4"); - vars.put("boolean", true); - vars.put("booleanString", "true"); - vars.put("booleanArray", toBooleanArray(true, false, true)); - vars.put("booleanArrayString", "true, false, true"); - - Assertions.assertEquals(vars.get("number"), 10); - - Assertions.assertEquals(vars.get("number", Integer.class), 10); - Assertions.assertThrows(IllegalArgumentException.class, () -> vars.get("number", Double.class)); - - Assertions.assertEquals(vars.get("number", Integer.class, 11), 10); - Assertions.assertEquals(vars.get("not_exist", Integer.class, 11), 11); - Assertions.assertEquals(vars.get("number", Double.class, 12D), 12D); - - Assertions.assertEquals(vars.getNullable("number", Integer.class, null), 10); - Assertions.assertNull(vars.getNullable("not_exist", Double.class, null)); - Assertions.assertThrows(IllegalArgumentException.class, () -> vars.getNullable("number", Double.class, null)); - - Assertions.assertEquals(vars.get("number", 11), 10); - Assertions.assertEquals(vars.get("not_exist", 11), 11); - Assertions.assertThrows(IllegalArgumentException.class, () -> vars.get("number", 11D)); - - Assertions.assertNull(vars.getNullable("not_exist", null)); - Assertions.assertEquals(vars.getNullable("number", 11D), 11D); - Assertions.assertEquals(vars.getNullable("number", 11), 10); - Assertions.assertEquals(vars.getNullable("number", null), 10); - Assertions.assertThrows( - ClassCastException.class, () -> { - Double d = vars.getNullable("number", null); - }); - - Assertions.assertArrayEquals(vars.getArray("array", Integer[].class, 1, 3, 3), toArray(1, 2, 3, 4)); - Assertions.assertArrayEquals(vars.getArray("not_exist", Integer[].class, 1, 3, 3), toArray(1, 3, 3)); - Assertions.assertThrows(IllegalArgumentException.class, () -> vars.getArray("array", Double[].class, 1D, 3D, 3D)); - - Assertions.assertTrue(vars.getBoolean("boolean")); - Assertions.assertTrue(vars.getBoolean("booleanString")); - Assertions.assertThrows(IllegalArgumentException.class, () -> vars.getBoolean("not_exist")); - Assertions.assertThrows(IllegalArgumentException.class, () -> vars.getBoolean("number")); - - Assertions.assertTrue(vars.getBoolean("boolean", false)); - Assertions.assertTrue(vars.getBoolean("booleanString", false)); - Assertions.assertFalse(vars.getBoolean("not_exist", false)); - Assertions.assertThrows(IllegalArgumentException.class, () -> vars.getBoolean("number", false)); - - Assertions.assertArrayEquals(vars.getBooleanArray("booleanArray", ","), toBooleanArray(true, false, true)); - Assertions.assertArrayEquals(vars.getBooleanArray("booleanArrayString", ","), toBooleanArray(true, false, true)); - } - - @Test - void testGetIntArrays() { - - var vars = new VarTable(); - vars.put("array", toArray(1, 2, 3, 4)); - vars.put("arrayInt", toIntArray(2, 4, 6, 1)); - vars.put("arrayString", "1, 2, 3, 4"); - - Assertions.assertArrayEquals(vars.getIntArray("array"), toIntArray(1, 2, 3, 4)); - Assertions.assertArrayEquals(vars.getIntArray("arrayInt"), toIntArray(2, 4, 6, 1)); - Assertions.assertArrayEquals(vars.getIntArray("arrayString", ","), toIntArray(1, 2, 3, 4)); - } - - @Test - void testAddAndGetIntegers() { - - var vars = new VarTable(); - vars.put("stringInt", "1234"); - vars.put("objectInt", 222); - - var stringInt = vars.getString("stringInt"); - var stringIntAsInt = vars.getInt("stringInt"); - var objectIntAsInt = vars.getInt("objectInt"); - - Assertions.assertEquals("1234", stringInt); - Assertions.assertEquals(1234, stringIntAsInt); - Assertions.assertEquals(222, objectIntAsInt); - } - - @Test - void testCheckExisting() { - - var vars = new VarTable(); - vars.put("value", "1234"); - - Assertions.assertTrue(vars.has("value")); - Assertions.assertFalse(vars.has("no value")); - } - - @Test - void testCopyingAnotherVarsTable() { - - var vars = new VarTable(); - vars.put("val1", "1"); - vars.put("val2", "2"); - - var anotherVars = new VarTable(); - anotherVars.put("val3", "3"); - anotherVars.put("val4", "4"); - - vars.put(anotherVars); - - Assertions.assertEquals("3", vars.getString("val3")); - Assertions.assertEquals("4", vars.getString("val4")); - - try { - vars.put(vars); - throw new IllegalStateException("Can't copy vars recursive."); - } catch (IllegalArgumentException e) { - // it's ok - } - } - - enum SimpleEnum { - FIRST, - SECOND, - THIRD - } - - @Test - void testAddAndGetSomeTypes() { - - var vars = new VarTable(); - vars.put("string", "Hello"); - vars.put("intArray", toIntArray(1, 2, 3, 5)); - vars.put("floatStringArray", "1.5,4.2,5.5"); - vars.put("stringEnum", "THIRD"); - vars.put("enum", SimpleEnum.SECOND); - - var string = vars.getString("string"); - var array = vars.getIntArray("intArray", ""); - var floatStringArray = vars.getFloatArray("floatStringArray", ","); - var stringEnum = vars.getEnum("stringEnum", SimpleEnum.class); - var anEnum = vars.getEnum("enum", SimpleEnum.class); - var unsafeGet = vars.get("enum"); - - Assertions.assertEquals("Hello", string); - Assertions.assertArrayEquals(array, toIntArray(1, 2, 3, 5)); - Assertions.assertArrayEquals(floatStringArray, ArrayFactory.toFloatArray(1.5F, 4.2F, 5.5F)); - Assertions.assertEquals(SimpleEnum.THIRD, stringEnum); - Assertions.assertEquals(SimpleEnum.SECOND, anEnum); - Assertions.assertEquals(SimpleEnum.SECOND, unsafeGet); - } -} diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/array/ArrayTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/array/ArrayTest.java deleted file mode 100644 index a35e923e..00000000 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/array/ArrayTest.java +++ /dev/null @@ -1,446 +0,0 @@ -package javasabr.rlib.common.util.array; - -import java.util.Objects; -import java.util.concurrent.atomic.AtomicInteger; -import javasabr.rlib.common.BaseTest; -import javasabr.rlib.common.util.NumberUtils; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * The list of tests {@link Array}. - * - * @author JavaSaBr - */ -public class ArrayTest extends BaseTest { - - @Test - void ofTest() { - - var array = ArrayFactory.asArray("First", "Second", "Third", " "); - array.add("Temp"); - array.remove("Temp"); - - var copy = Array.of(array); - - Assertions.assertEquals(array, copy); - - var array2 = Array.of("First", "Second", "Third", " "); - - Assertions.assertEquals(array, array2); - - var single = ArrayFactory.asArray("First"); - var single2 = Array.of("First"); - - Assertions.assertEquals(single, single2); - } - - @Test - void removeIfTest() { - - var array = ArrayFactory.asArray("First", "Second", "Third", " "); - - Assertions.assertTrue(array.removeIf(String::isBlank)); - Assertions.assertEquals(3, array.size()); - - Assertions.assertFalse(array.removeIf( - Type1.EXAMPLE, (arg, element) -> { - assertType(arg, Type1.class); - assertType(element, String.class); - return false; - })); - - Assertions.assertTrue(array.removeIf("Third", String::equals)); - Assertions.assertEquals(2, array.size()); - - array.add("Third"); - - Assertions.assertEquals(3, array.size()); - - Assertions.assertFalse(array.removeIf( - Type1.EXAMPLE, arg -> { - assertType(arg, Type1.class); - return arg; - }, (arg, element) -> { - assertType(arg, Type1.class); - assertType(element, String.class); - return false; - })); - - Assertions.assertTrue(array.removeIf( - "Second", - String::hashCode, - (first, second) -> first.equals(second.hashCode()))); - - Assertions.assertEquals(2, array.size()); - - array = ArrayFactory.asArray("10", "5", "2", "1"); - - Assertions.assertTrue(array.removeIfConverted(5, Integer::parseInt, Integer::equals)); - - Assertions.assertEquals(3, array.size()); - } - - @Test - void toArrayTest() { - - var array = ArrayFactory.asArray("First", "Second", "Third", " "); - - Assertions.assertArrayEquals(ArrayFactory.toArray("First", "Second", "Third", " "), array.toArray()); - - Assertions.assertArrayEquals(ArrayFactory.toArray("First", "Second", "Third", " "), array.toArray(String.class)); - - Assertions.assertArrayEquals(ArrayFactory.toArray("First", "Second", "Third", " "), array.toArray(new String[0])); - - //noinspection ToArrayCallWithZeroLengthArrayArgument - Assertions.assertArrayEquals( - ArrayFactory.toArray("First", "Second", "Third", " "), - array.toArray(new String[array.size()])); - } - - @Test - void removeTest() { - - var array = ArrayFactory.asArray("First", "Second", "Third", " "); - - Assertions.assertArrayEquals(ArrayFactory.toArray("First", "Second", "Third", " "), array.toArray()); - - array.remove("Second"); - - Assertions.assertArrayEquals(ArrayFactory.toArray("First", "Third", " "), array.toArray()); - - array.remove(" "); - - Assertions.assertArrayEquals(ArrayFactory.toArray("First", "Third"), array.toArray()); - - array.remove("First"); - - Assertions.assertArrayEquals(ArrayFactory.toArray("Third"), array.toArray()); - - array = ArrayFactory.asArray("First", "Second", "Third", " "); - - Assertions.assertArrayEquals(ArrayFactory.toArray("First", "Second", "Third", " "), array.toArray()); - - array.remove(1); - - Assertions.assertArrayEquals(ArrayFactory.toArray("First", "Third", " "), array.toArray()); - - array.remove(2); - - Assertions.assertArrayEquals(ArrayFactory.toArray("First", "Third"), array.toArray()); - - array.remove(0); - - Assertions.assertArrayEquals(ArrayFactory.toArray("Third"), array.toArray()); - } - - @Test - void findAnyTest() { - - var array = ArrayFactory.asArray("First", "Second", "Third", " "); - - Assertions.assertNotNull(array.findAny("Second"::equals)); - - Assertions.assertNull(array.findAny( - Type1.EXAMPLE, (arg, element) -> { - assertType(arg, Type1.class); - assertType(element, String.class); - return false; - })); - - Assertions.assertNotNull(array.findAny("Third", String::equals)); - - Assertions.assertNull(array.findAnyR( - Type1.EXAMPLE, (element, arg) -> { - assertType(element, String.class); - assertType(arg, Type1.class); - return false; - })); - - Assertions.assertNotNull(array.findAnyR("Third", String::equals)); - - Assertions.assertNull(array.findAny( - Type1.EXAMPLE, Type2.EXAMPLE, (arg1, arg2, element) -> { - assertType(arg1, Type1.class); - assertType(arg2, Type2.class); - assertType(element, String.class); - return false; - })); - - Assertions.assertNotNull(array.findAny( - "First", - "Second", - (first, second, element) -> first.equals(element) || second.equals(element))); - - Assertions.assertNotNull(array.findAny( - "First".hashCode(), (num, element) -> { - assertIntType(num); - assertType(element, String.class); - return num == element.hashCode(); - })); - - Assertions.assertNotNull(array.findAny("First".hashCode(), (num, element) -> num == element.hashCode())); - - Assertions.assertNotNull(array.findAnyL( - "First".hashCode(), (num, element) -> { - assertLongType(num); - assertType(element, String.class); - return num == element.hashCode(); - })); - - Assertions.assertNotNull(array.findAnyL("First".hashCode(), (num, element) -> num == element.hashCode())); - - Assertions.assertNotNull(array.findAnyConvertedToInt("First".hashCode(), String::hashCode, NumberUtils::equals)); - - Assertions.assertNotNull(array.findAnyConvertedToInt( - "MyValue".hashCode(), - object -> "MyValue", - String::hashCode, - NumberUtils::equals)); - - Assertions.assertNull(array.findAnyConvertedToInt( - "MyValue".hashCode(), - object -> "First", - String::hashCode, - NumberUtils::equals)); - - Assertions.assertNotNull(array.findAnyConverted("First".hashCode(), String::hashCode, Objects::equals)); - } - - @Test - void anyMatchTest() { - - var array = ArrayFactory.asArray("First", "Second", "Third", " "); - - Assertions.assertFalse(array.anyMatch( - Type1.EXAMPLE, (arg, element) -> { - assertType(arg, Type1.class); - assertType(element, String.class); - return false; - })); - - Assertions.assertTrue(array.anyMatch("Second", String::equals)); - Assertions.assertFalse(array.anyMatch("None", String::equals)); - - Assertions.assertFalse(array.anyMatch( - "None".hashCode(), (arg, element) -> { - assertIntType(arg); - assertType(element, String.class); - return arg == element.hashCode(); - })); - - Assertions.assertTrue(array.anyMatch("Second".hashCode(), (num, element) -> num == element.hashCode())); - Assertions.assertFalse(array.anyMatch("None".hashCode(), (num, element) -> num == element.hashCode())); - - Assertions.assertFalse(array.anyMatchR( - Type1.EXAMPLE, (element, arg) -> { - assertType(element, String.class); - assertType(arg, Type1.class); - return false; - })); - - Assertions.assertTrue(array.anyMatchR("Second".hashCode(), (element, num) -> element.hashCode() == num)); - Assertions.assertFalse(array.anyMatchR("None".hashCode(), (element, num) -> element.hashCode() == num)); - - Assertions.assertTrue(array.anyMatchConverted("Second".hashCode(), String::hashCode, Objects::equals)); - Assertions.assertFalse(array.anyMatchConverted("None".hashCode(), String::hashCode, Objects::equals)); - } - - @Test - void replaceTest() { - - var array = ArrayFactory.asArray("First", "Second", "Third", " "); - - Assertions.assertArrayEquals(ArrayFactory.toArray("First", "Second", "Third", " "), array.toArray()); - - array.replace(1, "NotSecond"); - - Assertions.assertEquals(4, array.size()); - Assertions.assertArrayEquals(ArrayFactory.toArray("First", "NotSecond", "Third", " "), array.toArray()); - - array.replace(3, "NotEmpty"); - - Assertions.assertEquals(4, array.size()); - Assertions.assertArrayEquals(ArrayFactory.toArray("First", "NotSecond", "Third", "NotEmpty"), array.toArray()); - } - - @Test - void countTest() { - - var array = ArrayFactory.asArray("First", "Second", "First", "Third"); - - Assertions.assertEquals(2, array.count("First"::equals)); - Assertions.assertEquals(1, array.count("Second"::equals)); - - Assertions.assertEquals(2, array.count("First", String::equals)); - Assertions.assertEquals(1, array.count("Second", String::equals)); - - Assertions.assertEquals(2, array.countR("First", String::equals)); - Assertions.assertEquals(1, array.countR("Second", String::equals)); - } - - @Test - void forEachTest() { - - var array = Array.of("First", "Second", "Third", " ", "Third"); - var counter = new AtomicInteger(0); - - array.forEach(element -> counter.incrementAndGet()); - - Assertions.assertEquals(array.size(), counter.getAndSet(0)); - - array.forEachFiltered("First"::equals, el -> counter.incrementAndGet()); - - Assertions.assertEquals(1, counter.getAndSet(0)); - - array.forEach( - Type1.EXAMPLE, (arg, element) -> { - assertType(arg, Type1.class); - assertType(element, String.class); - counter.incrementAndGet(); - }); - - Assertions.assertEquals(array.size(), counter.getAndSet(0)); - - array.forEachR( - Type1.EXAMPLE, (element, arg) -> { - assertType(arg, Type1.class); - assertType(element, String.class); - counter.incrementAndGet(); - }); - - Assertions.assertEquals(array.size(), counter.getAndSet(0)); - - array.forEachConverted( - Type1.EXAMPLE, String::getBytes, (arg, converted) -> { - assertType(arg, Type1.class); - assertType(converted, byte[].class); - counter.incrementAndGet(); - }); - - Assertions.assertEquals(array.size(), counter.getAndSet(0)); - - array.forEachConverted( - Type1.EXAMPLE, Type2.EXAMPLE, String::getBytes, (arg1, arg2, converted) -> { - assertType(arg1, Type1.class); - assertType(arg2, Type2.class); - assertType(converted, byte[].class); - counter.incrementAndGet(); - }); - - Assertions.assertEquals(array.size(), counter.getAndSet(0)); - - array.forEach( - "Arg", String::getBytes, (arg, element) -> { - assertType(arg, byte[].class); - assertType(element, String.class); - counter.incrementAndGet(); - }); - - Assertions.assertEquals(array.size(), counter.getAndSet(0)); - - array.forEachFiltered( - Type1.EXAMPLE, (arg, element) -> { - assertType(arg, Type1.class); - assertType(element, String.class); - return "Second".equals(element); - }, (arg, element) -> { - assertType(arg, Type1.class); - assertType(element, String.class); - counter.incrementAndGet(); - }); - - Assertions.assertEquals(1, counter.getAndSet(0)); - - array.forEach( - Type1.EXAMPLE, Type2.EXAMPLE, (arg1, arg2, element) -> { - assertType(arg1, Type1.class); - assertType(arg2, Type2.class); - assertType(element, String.class); - counter.incrementAndGet(); - }); - - Assertions.assertEquals(array.size(), counter.getAndSet(0)); - - array.forEachR( - Type1.EXAMPLE, Type2.EXAMPLE, (element, arg1, arg2) -> { - assertType(element, String.class); - assertType(arg1, Type1.class); - assertType(arg2, Type2.class); - counter.incrementAndGet(); - }); - - Assertions.assertEquals(array.size(), counter.getAndSet(0)); - - array.forEachFiltered( - Type1.EXAMPLE, Type2.EXAMPLE, (arg1, arg2, element) -> { - assertType(arg1, Type1.class); - assertType(arg2, Type2.class); - assertType(element, String.class); - return "First".equals(element) || "Second".equals(element); - }, (arg1, arg2, element) -> { - assertType(arg1, Type1.class); - assertType(arg2, Type2.class); - assertType(element, String.class); - counter.incrementAndGet(); - }); - - Assertions.assertEquals(2, counter.getAndSet(0)); - - array.forEachL( - 1L, Type1.EXAMPLE, (arg1, arg2, element) -> { - assertLongType(arg1); - assertType(arg2, Type1.class); - assertType(element, String.class); - counter.incrementAndGet(); - }); - - Assertions.assertEquals(array.size(), counter.getAndSet(0)); - - array.forEachF( - 1F, Type1.EXAMPLE, (arg1, arg2, element) -> { - assertFloatType(arg1); - assertType(arg2, Type1.class); - assertType(element, String.class); - counter.incrementAndGet(); - }); - - Assertions.assertEquals(array.size(), counter.getAndSet(0)); - - array.forEach( - 0, Type2.EXAMPLE, (arg1, arg2, element) -> { - assertIntType(arg1); - assertType(arg2, Type2.class); - assertType(element, String.class); - counter.incrementAndGet(); - }); - - Assertions.assertEquals(array.size(), counter.getAndSet(0)); - } - - @Test - void fastRemoveAllTest() { - - var array = ArrayFactory.asArray("First", "Second", "Third", " ", "55", "66", "22", "22", "11"); - var toRemove = ArrayFactory.asArray("First", "Third", "66", "22"); - var result = ArrayFactory.asArray("Second", " ", "55", "11"); - result.sort(String::compareTo); - - array.fastRemoveAll(toRemove); - array.sort(String::compareTo); - - Assertions.assertEquals(result, array); - } - - @Test - void copyToTest() { - - var toCopy = ArrayFactory.asArray("123", "321", "555"); - var toCombine = ArrayFactory.asArray("First", "Second"); - var result = ArrayFactory.asArray("First", "Second", "123", "321", "555"); - - toCopy.copyTo(toCombine); - - Assertions.assertEquals(result, toCombine); - } -} diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/array/ConcurrentArrayTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/array/ConcurrentArrayTest.java deleted file mode 100644 index 0b69839e..00000000 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/array/ConcurrentArrayTest.java +++ /dev/null @@ -1,355 +0,0 @@ -package javasabr.rlib.common.util.array; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.Collections; -import java.util.Objects; -import java.util.concurrent.atomic.AtomicInteger; -import javasabr.rlib.common.BaseTest; -import javasabr.rlib.common.util.NumberUtils; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * @author JavaSaBr - */ -public class ConcurrentArrayTest extends BaseTest { - - @Test - void addTest() { - - var array = ConcurrentArray.ofType(String.class); - - assertEquals(0, array.size()); - - array.add("First"); - - assertEquals(1, array.size()); - assertEquals(Array.of("First"), array); - assertEquals(array, Array.of("First")); - - array.addAll(ArrayFactory.toArray("Second", "Third")); - - assertEquals(3, array.size()); - assertEquals(Array.of("First", "Second", "Third"), array); - - array.addAll(ArrayFactory.asArray("Fourth", "Fifth")); - - assertEquals(5, array.size()); - assertEquals(Array.of("First", "Second", "Third", "Fourth", "Fifth"), array); - } - - @Test - void removeTest() { - - var array = ConcurrentArray.of("First", "Second", "Third", "Fourth"); - - assertEquals(4, array.size()); - - array.remove("Second"); - - assertEquals(3, array.size()); - assertEquals(Array.of("First", "Third", "Fourth"), array); - - array.removeAll(ArrayFactory.asArray("First", "Fourth")); - - assertEquals(1, array.size()); - assertEquals(Array.of("Third"), array); - - array = ConcurrentArray.of("First", "Second", "Third", "Fourth"); - - assertEquals(4, array.size()); - - array.remove(2); - - assertEquals(3, array.size()); - assertEquals(Array.of("First", "Second", "Fourth"), array); - - array.removeAll(Collections.singletonList("First")); - - assertEquals(2, array.size()); - assertEquals(Array.of("Second", "Fourth"), array); - } - - @Test - void fastRemoveTest() { - - var array = ConcurrentArray.of("First", "Second", "Third", "Fourth"); - - assertEquals(4, array.size()); - - array.fastRemove("Second"); - - assertEquals(3, array.size()); - assertEquals(Array.of("First", "Fourth", "Third"), array); - - array.fastRemoveAll(ArrayFactory.asArray("First", "Fourth")); - - assertEquals(1, array.size()); - assertEquals(Array.of("Third"), array); - - array = ConcurrentArray.of("First", "Second", "Third", "Fourth"); - - assertEquals(4, array.size()); - - array.fastRemove(1); - - assertEquals(3, array.size()); - assertEquals(Array.of("First", "Fourth", "Third"), array); - - array.fastRemoveAll(ArrayFactory.toArray("First", "Third")); - - assertEquals(1, array.size()); - assertEquals(Array.of("Fourth"), array); - } - - @Test - void removeIfInWriteLockTest() { - - var array = ConcurrentArray.of("First", "Second", "Third", " "); - - assertTrue(array.removeIfInWriteLock(String::isBlank)); - assertEquals(3, array.size()); - - assertFalse(array.removeIfInWriteLock( - Type1.EXAMPLE, (arg, element) -> { - assertType(arg, Type1.class); - assertType(element, String.class); - return false; - })); - - assertTrue(array.removeIfInWriteLock("Third", String::equals)); - assertEquals(2, array.size()); - - array.add("Third"); - - assertEquals(3, array.size()); - - assertFalse(array.removeIfInWriteLock( - Type1.EXAMPLE, arg -> { - assertType(arg, Type1.class); - return arg; - }, (arg, element) -> { - assertType(arg, Type1.class); - assertType(element, String.class); - return false; - })); - - assertTrue(array.removeIfInWriteLock( - "Second", - String::hashCode, - (first, second) -> first.equals(second.hashCode()))); - - assertEquals(2, array.size()); - - array = ConcurrentArray.of("10", "5", "2", "1"); - - assertTrue(array.removeIfConvertedInWriteLock(5, Integer::parseInt, Integer::equals)); - - assertEquals(3, array.size()); - } - - @Test - void anyMatchInReadLockTest() { - - var array = ConcurrentArray.of("First", "Second", "Third", " "); - - assertFalse(array.anyMatchInReadLock( - Type1.EXAMPLE, (arg, element) -> { - assertType(arg, Type1.class); - assertType(element, String.class); - return false; - })); - - assertTrue(array.anyMatchInReadLock("Second", String::equals)); - assertFalse(array.anyMatchInReadLock("None", String::equals)); - - assertFalse(array.anyMatchInReadLock( - "None".hashCode(), (arg, element) -> { - assertIntType(arg); - assertType(element, String.class); - return arg == element.hashCode(); - })); - - assertTrue(array.anyMatchInReadLock("Second".hashCode(), (val, string) -> val == string.hashCode())); - assertFalse(array.anyMatchInReadLock("None".hashCode(), (val, string) -> val == string.hashCode())); - - assertTrue(array.anyMatchConvertedInReadLock("Second".hashCode(), String::hashCode, Objects::equals)); - - assertFalse(array.anyMatchConvertedInReadLock("None".hashCode(), String::hashCode, Objects::equals)); - } - - @Test - void findAnyInReadLockTest() { - - var array = ConcurrentArray.of("First", "Second", "Third", " "); - - assertNull(array.findAnyInReadLock( - "None".hashCode(), (arg, element) -> { - assertIntType(arg); - assertType(element, String.class); - return arg == element.hashCode(); - })); - - assertNotNull(array.findAnyInReadLock("Second".hashCode(), (val, string) -> val == string.hashCode())); - assertNull(array.findAnyInReadLock("None".hashCode(), (val, string) -> val == string.hashCode())); - - assertNotNull(array.findAnyConvertedToIntInReadLock("First".hashCode(), String::hashCode, NumberUtils::equals)); - - assertNotNull(array.findAnyConvertedInReadLock("First".hashCode(), String::hashCode, Objects::equals)); - - Assertions.assertNotNull(array.findAnyConvertedToIntInReadLock( - "MyValue".hashCode(), - object -> "MyValue", - String::hashCode, - NumberUtils::equals)); - - Assertions.assertNull(array.findAnyConvertedToIntInReadLock( - "MyValue".hashCode(), - object -> "First", - String::hashCode, - NumberUtils::equals)); - } - - @Test - void runInWriteLockTest() { - - var array = ConcurrentArray.of("First", "Second", "Third", " "); - - array.runInWriteLock(1, "Second", (arr, first, second) -> assertEquals(second, arr.get(first))); - - array.runInWriteLock(object -> object.remove("Second")); - - assertEquals(3, array.size()); - - array.runInWriteLock( - Type1.EXAMPLE, (arr, arg) -> { - assertType(arr, Array.class); - assertType(arg, Type1.class); - }); - - array.runInWriteLock("Third", Array::remove); - - assertEquals(2, array.size()); - } - - @Test - void runInReadLockTest() { - - var array = ConcurrentArray.of("First", "Second", "Third", " ", "Third"); - - array.runInReadLock(arr -> assertEquals(2, arr.count(el -> el.equals("Third")))); - - array.runInReadLock( - "Third", (arr, arg) -> { - assertType(arr, Array.class); - assertType(arg, String.class); - assertEquals(2, arr.count(arg, String::equals)); - }); - - array.runInReadLock("Third", (arr, arg) -> assertEquals(2, arr.count(arg, String::equals))); - - array.runInReadLock( - 2, "Third", (arr, first, second) -> { - assertType(arr, Array.class); - assertIntType(first); - assertType(second, String.class); - assertEquals(first, arr.count(second, String::equals)); - }); - } - - @Test - void getInWriteLockTest() { - - var array = ConcurrentArray.of("First", "Second", "Third", " ", "Third"); - - assertEquals("Third", array.getInWriteLock(arr -> arr.get(2))); - assertEquals("Second", array.getInWriteLock(1, Array::get)); - assertEquals("FirstSecond", array.getInWriteLock(0, 1, (arr, first, second) -> arr.get(first) + arr.get(second))); - } - - @Test - void getInReadLockTest() { - - var array = ConcurrentArray.of("First", "Second", "Third", " ", "Third"); - - assertEquals("Third", array.getInReadLock(arr -> arr.get(2))); - assertEquals("Second", array.getInReadLock(1, Array::get)); - assertEquals("FirstSecond", array.getInReadLock(0, 1, (arr, first, second) -> arr.get(first) + arr.get(second))); - } - - @Test - void forEachInReadLockTest() { - - var array = ConcurrentArray.of("First", "Second", "Third", " ", "Third"); - var counter = new AtomicInteger(0); - - array.forEachInReadLock(element -> counter.incrementAndGet()); - - assertEquals(array.size(), counter.getAndSet(0)); - - array.forEachInReadLock( - Type1.EXAMPLE, (arg, element) -> { - assertType(arg, Type1.class); - assertType(element, String.class); - counter.incrementAndGet(); - }); - - assertEquals(array.size(), counter.getAndSet(0)); - - array.forEachInReadLock( - Type1.EXAMPLE, arg -> { - assertType(arg, Type1.class); - return arg; - }, (arg, element) -> { - assertType(arg, Type1.class); - assertType(element, String.class); - counter.incrementAndGet(); - }); - - assertEquals(array.size(), counter.getAndSet(0)); - - array.forEachConvertedInReadLock( - Type1.EXAMPLE, String::hashCode, (arg, element) -> { - assertType(arg, Type1.class); - assertIntType(element); - counter.incrementAndGet(); - }); - - assertEquals(array.size(), counter.getAndSet(0)); - - array.forEachConvertedInReadLock( - Type1.EXAMPLE, Type2.EXAMPLE, String::hashCode, (arg1, arg2, element) -> { - assertType(arg1, Type1.class); - assertType(arg2, Type2.class); - assertIntType(element); - counter.incrementAndGet(); - }); - - assertEquals(array.size(), counter.getAndSet(0)); - - array.forEachInReadLock( - 0, Type1.EXAMPLE, (arg1, arg2, element) -> { - assertIntType(arg1); - assertType(arg2, Type1.class); - assertType(element, String.class); - counter.incrementAndGet(); - }); - - assertEquals(array.size(), counter.getAndSet(0)); - - array.forEachInReadLock( - Type1.EXAMPLE, Type2.EXAMPLE, (arg1, arg2, element) -> { - assertType(arg1, Type1.class); - assertType(arg2, Type2.class); - assertType(element, String.class); - counter.incrementAndGet(); - }); - - assertEquals(array.size(), counter.getAndSet(0)); - } -} diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/array/CopyOnModifyArrayTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/array/CopyOnModifyArrayTest.java deleted file mode 100644 index 2b7cc66e..00000000 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/array/CopyOnModifyArrayTest.java +++ /dev/null @@ -1,246 +0,0 @@ -package javasabr.rlib.common.util.array; - -import static javasabr.rlib.common.util.array.ArrayFactory.asArray; -import static javasabr.rlib.common.util.array.ArrayFactory.toArray; - -import java.util.List; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public class CopyOnModifyArrayTest { - - @Test - void addTest() { - - var array = ArrayFactory.newCopyOnModifyArray(String.class); - array.add("First"); - - Assertions.assertEquals(1, array.size()); - - array.add("Second"); - - Assertions.assertEquals(2, array.size()); - - array.add("Third"); - - Assertions.assertEquals(3, array.size()); - Assertions.assertArrayEquals(toArray("First", "Second", "Third"), array.array()); - Assertions.assertEquals("Second", array.get(1)); - } - - @Test - void addArrayTest() { - - var array = ArrayFactory.newCopyOnModifyArray(String.class); - array.add("First"); - array.add("Second"); - array.addAll(Array.of("Third", "Fourth")); - - Assertions.assertEquals(4, array.size()); - Assertions.assertArrayEquals(toArray("First", "Second", "Third", "Fourth"), array.array()); - Assertions.assertEquals("Second", array.get(1)); - - array.addAll(Array.of("Fifth", "Six")); - - Assertions.assertEquals(6, array.size()); - Assertions.assertEquals("Fifth", array.get(4)); - } - - @Test - void addCollectionTest() { - - var array = ArrayFactory.newCopyOnModifyArray(String.class); - array.add("First"); - array.add("Second"); - array.addAll(List.of("Third", "Fourth")); - - Assertions.assertEquals(4, array.size()); - Assertions.assertArrayEquals(toArray("First", "Second", "Third", "Fourth"), array.array()); - Assertions.assertEquals("Second", array.get(1)); - - array.addAll(List.of("Fifth", "Six")); - - Assertions.assertEquals(6, array.size()); - Assertions.assertEquals("Fifth", array.get(4)); - } - - @Test - void addNativeArrayTest() { - - var array = ArrayFactory.newCopyOnModifyArray(String.class); - array.add("First"); - array.add("Second"); - array.addAll(toArray("Third", "Fourth")); - - Assertions.assertEquals(4, array.size()); - Assertions.assertArrayEquals(toArray("First", "Second", "Third", "Fourth"), array.array()); - Assertions.assertEquals("Second", array.get(1)); - - array.addAll(toArray("Fifth", "Six")); - - Assertions.assertEquals(6, array.size()); - Assertions.assertEquals("Fifth", array.get(4)); - } - - @Test - void arrayTest() { - - var array = ArrayFactory.newCopyOnModifyArray(String.class); - array.add("First"); - - Assertions.assertArrayEquals(toArray("First"), array.array()); - - array.add("Second"); - - Assertions.assertArrayEquals(toArray("First", "Second"), array.array()); - - array.addAll(toArray("Third", "Fourth")); - - Assertions.assertEquals(4, array.size()); - Assertions.assertArrayEquals(toArray("First", "Second", "Third", "Fourth"), array.array()); - - array.remove("Second"); - - Assertions.assertArrayEquals(toArray("First", "Third", "Fourth"), array.array()); - - array.removeAll(asArray("First", "Fourth")); - - Assertions.assertArrayEquals(toArray("Third"), array.array()); - - Assertions.assertEquals(1, array.size()); - } - - @Test - void removeArrayTest() { - - var array = ArrayFactory.newCopyOnModifyArray(String.class); - array.add("First"); - array.add("Second"); - array.add("Third"); - array.add("Fourth"); - - array.removeAll(Array.of("Second", "Third")); - - Assertions.assertEquals(2, array.size()); - Assertions.assertArrayEquals(toArray("First", "Fourth"), array.array()); - - array.add("Second"); - array.add("Third"); - - array.removeAll(Array.of("First")); - - Assertions.assertArrayEquals(toArray("Fourth", "Second", "Third"), array.array()); - - array.removeAll(Array.of("Second", "Third")); - - Assertions.assertArrayEquals(toArray("Fourth"), array.array()); - - array.clear(); - - Assertions.assertArrayEquals(toArray(), array.array()); - - array.add("First"); - array.add("First"); - array.add("First"); - array.add("Second"); - array.add("Second"); - - array.removeAll(Array.of("First", "Second")); - - Assertions.assertArrayEquals(toArray("First", "First", "Second"), array.array()); - } - - @Test - void removeCollectionTest() { - - var array = ArrayFactory.newCopyOnModifyArray(String.class); - array.add("First"); - array.add("Second"); - array.add("Third"); - array.add("Fourth"); - - array.removeAll(List.of("Second", "Third")); - - Assertions.assertEquals(2, array.size()); - Assertions.assertArrayEquals(toArray("First", "Fourth"), array.array()); - - array.add("Second"); - array.add("Third"); - - array.removeAll(List.of("First")); - - Assertions.assertArrayEquals(toArray("Fourth", "Second", "Third"), array.array()); - - array.removeAll(List.of("Second", "Third")); - - Assertions.assertArrayEquals(toArray("Fourth"), array.array()); - - array.clear(); - - Assertions.assertArrayEquals(toArray(), array.array()); - - array.add("First"); - array.add("First"); - array.add("First"); - array.add("Second"); - array.add("Second"); - - array.removeAll(List.of("First", "Second")); - - Assertions.assertArrayEquals(toArray("First", "First", "Second"), array.array()); - } - - @Test - void removeElementTest() { - - var array = ArrayFactory.newCopyOnModifyArray(String.class); - array.add("First"); - array.add("Second"); - array.add("Third"); - array.add("Fourth"); - - array.remove("Second"); - - Assertions.assertEquals(3, array.size()); - Assertions.assertArrayEquals(toArray("First", "Third", "Fourth"), array.array()); - - array.add("Second"); - - array.remove("First"); - - Assertions.assertArrayEquals(toArray("Third", "Fourth", "Second"), array.array()); - - array.remove("Third"); - array.remove("Second"); - - Assertions.assertArrayEquals(toArray("Fourth"), array.array()); - - array.clear(); - - Assertions.assertArrayEquals(toArray(), array.array()); - - array.add("First"); - array.add("First"); - array.add("First"); - array.add("Second"); - array.add("Second"); - - array.remove("First"); - array.remove("Second"); - - Assertions.assertArrayEquals(toArray("First", "First", "Second"), array.array()); - } - - @Test - void sortTest() { - - var array = ArrayFactory.newCopyOnModifyArray(Integer.class); - array.add(10); - array.add(5); - array.add(9); - array.add(1); - array.sort(Integer::compareTo); - - Assertions.assertArrayEquals(toArray(1, 5, 9, 10), array.array()); - } -} diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/array/FastArrayTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/array/FastArrayTest.java deleted file mode 100644 index 94b40d49..00000000 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/array/FastArrayTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package javasabr.rlib.common.util.array; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * @author JavaSaBr - */ -public class FastArrayTest { - - @Test - void equalsTest() { - - var integerArray = ArrayFactory.asArray(2, 5, 1, 7, 6, 8, 4); - var stringArray = ArrayFactory.asArray("third", "first", "fifth"); - - Assertions.assertEquals(ArrayFactory.asArray(2, 5, 1, 7, 6, 8, 4), integerArray); - Assertions.assertNotEquals(ArrayFactory.asArray(2, 5, 1, 2, 6, 8, 4), integerArray); - - Assertions.assertEquals(ArrayFactory.asArray("third", "first", "fifth"), stringArray); - Assertions.assertNotEquals(ArrayFactory.asArray("third", "first", "fi2fth"), stringArray); - - Assertions.assertEquals(ArrayFactory.newArray(String.class), ArrayFactory.newArray(String.class)); - Assertions.assertEquals(Array.empty(), ArrayFactory.newArray(String.class)); - } -} diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/ConcurrentObjectDictionaryTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/ConcurrentObjectDictionaryTest.java deleted file mode 100644 index 781d510f..00000000 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/ConcurrentObjectDictionaryTest.java +++ /dev/null @@ -1,119 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import javasabr.rlib.common.BaseTest; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public class ConcurrentObjectDictionaryTest extends BaseTest { - - @Test - void runInWriteLockTest() { - - var dictionary = ConcurrentObjectDictionary.ofType(String.class, Integer.class); - - Assertions.assertEquals(0, dictionary.size()); - - dictionary.runInWriteLock(dic -> { - dic.put("1", 1); - dic.put("2", 2); - dic.put("3", 3); - }); - - Assertions.assertEquals(3, dictionary.size()); - - dictionary.runInWriteLock( - "4", (dic, arg) -> { - assertType(dic, ConcurrentObjectDictionary.class); - assertType(arg, String.class); - dic.put(arg, Integer.valueOf(arg)); - }); - - Assertions.assertEquals(4, dictionary.size()); - - dictionary.runInWriteLock("5", 5, ObjectDictionary::put); - - Assertions.assertEquals(5, dictionary.size()); - - dictionary.runInWriteLock( - "6", 6, (dic, arg1, arg2) -> { - assertType(dic, ConcurrentObjectDictionary.class); - assertType(arg1, String.class); - assertType(arg2, Integer.class); - }); - } - - @Test - void runInReadLockTest() { - - var dictionary = ConcurrentObjectDictionary.ofType(String.class, Integer.class); - - dictionary.runInReadLock( - "4", (dic, arg) -> { - assertType(dic, ConcurrentObjectDictionary.class); - assertType(arg, String.class); - dic.get(arg); - }); - } - - @Test - void getInWriteLockTest() { - - var dictionary = ConcurrentObjectDictionary.ofType(String.class, Integer.class); - - dictionary.runInWriteLock(dic -> { - dic.put("1", 1); - dic.put("2", 2); - dic.put("3", 3); - }); - - Integer val1 = dictionary.getInWriteLock( - "1", (dic, arg) -> { - assertType(dic, ConcurrentObjectDictionary.class); - assertType(arg, String.class); - return dic.get(arg); - }); - - Assertions.assertEquals(1, val1); - - Integer val2 = dictionary.getInWriteLock( - "2", Type1.EXAMPLE, (dic, arg1, arg2) -> { - assertType(dic, ConcurrentObjectDictionary.class); - assertType(arg1, String.class); - assertType(arg2, Type1.class); - return dic.get(arg1); - }); - - Assertions.assertEquals(2, val2); - } - - @Test - void getInReadLockTest() { - - var dictionary = ConcurrentObjectDictionary.ofType(String.class, Integer.class); - - dictionary.runInWriteLock(dic -> { - dic.put("1", 1); - dic.put("2", 2); - dic.put("3", 3); - }); - - Integer val1 = dictionary.getFromReadLock( - "1", (dic, arg) -> { - assertType(dic, ConcurrentObjectDictionary.class); - assertType(arg, String.class); - return dic.get(arg); - }); - - Assertions.assertEquals(1, val1); - - Integer val2 = dictionary.getInReadLock( - "2", Type1.EXAMPLE, (dic, arg1, arg2) -> { - assertType(dic, ConcurrentObjectDictionary.class); - assertType(arg1, String.class); - assertType(arg2, Type1.class); - return dic.get(arg1); - }); - - Assertions.assertEquals(2, val2); - } -} diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/ConcurrentStampedLockObjectDictionaryTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/ConcurrentStampedLockObjectDictionaryTest.java deleted file mode 100644 index 353dafa7..00000000 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/ConcurrentStampedLockObjectDictionaryTest.java +++ /dev/null @@ -1,80 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.TimeUnit; -import javasabr.rlib.common.util.Utils; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * @author JavaSaBr - */ -public class ConcurrentStampedLockObjectDictionaryTest { - - @Test - void writeLockTest() { - - var dictionary = DictionaryFactory.newConcurrentStampedLockObjectDictionary(); - dictionary.runInWriteLock(dic -> { - dic.put("Key1", 1); - dic.put("Key2", 2); - dic.put("Key3", 3); - dic.put("Key4", 4); - }); - - long stamp = dictionary.writeLock(); - - Assertions.assertNotEquals(0, stamp); - - var pendingWrite = CompletableFuture.runAsync(() -> dictionary.runInWriteLock(dic -> dic.put("Key5", 5))); - - Utils.tryGet(() -> pendingWrite.get(10, TimeUnit.MILLISECONDS)); - - Assertions.assertEquals(4, dictionary.size()); - - dictionary.writeUnlock(stamp); - - pendingWrite.join(); - - Assertions.assertEquals(5, dictionary.size()); - - stamp = dictionary.readLock(); - - Assertions.assertNotEquals(0, stamp); - - var pendingWrite2 = CompletableFuture.runAsync(() -> dictionary.runInWriteLock(dic -> dic.put("Key6", 6))); - - Utils.tryGet(() -> pendingWrite2.get(10, TimeUnit.MILLISECONDS)); - - Assertions.assertEquals(5, dictionary.size()); - - dictionary.readUnlock(stamp); - - pendingWrite2.join(); - - Assertions.assertEquals(6, dictionary.size()); - } - - @Test - void writeReadLockTest() { - - var dictionary = DictionaryFactory.newConcurrentStampedLockObjectDictionary(); - dictionary.runInWriteLock(dic -> { - dic.put("Key1", 1); - dic.put("Key2", 2); - dic.put("Key3", 3); - dic.put("Key4", 4); - }); - - long stamp = dictionary.readLock(); - - Assertions.assertNotEquals(0, stamp); - - var asyncRead = CompletableFuture.supplyAsync(() -> dictionary.getFromReadLock("Key1", ObjectDictionary::get)); - var result = Utils.uncheckedGet(() -> asyncRead.get(100, TimeUnit.MILLISECONDS)); - - Assertions.assertEquals(dictionary.get("Key1"), result); - - dictionary.readUnlock(stamp); - } -} diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/FastLongDictionaryTests.java b/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/FastLongDictionaryTests.java deleted file mode 100644 index 29e38577..00000000 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/FastLongDictionaryTests.java +++ /dev/null @@ -1,78 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import static javasabr.rlib.common.util.dictionary.DictionaryCollectors.toLongDictionary; -import static javasabr.rlib.common.util.dictionary.DictionaryFactory.newLongDictionary; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.util.List; -import java.util.function.Function; -import org.junit.jupiter.api.Test; - -/** - * The list of tests {@link FastLongDictionary}. - * - * @author JavaSaBr - */ -public class FastLongDictionaryTests { - - @Test - void generalTest() { - - var dictionary = DictionaryFactory.newLongDictionary(); - dictionary.put(5, "5"); - dictionary.put(6, "6"); - - assertEquals(2, dictionary.size()); - - dictionary.put(7, "7"); - - assertEquals(3, dictionary.size()); - assertEquals("7", dictionary.get(7)); - - assertEquals("8", dictionary.getOrCompute(8, () -> "8")); - assertEquals("9", dictionary.getOrCompute(9, key -> "9")); - - assertEquals(5, dictionary.size()); - - assertEquals("8", dictionary.remove(8)); - - assertEquals(4, dictionary.size()); - } - - @Test - void emptyDictionaryTest() { - - var emptyDictionary = LongDictionary.empty(); - - assertThrows(IllegalStateException.class, () -> emptyDictionary.put(1, "1")); - assertThrows(IllegalStateException.class, () -> emptyDictionary.remove(1)); - assertThrows(IllegalStateException.class, () -> emptyDictionary.put(newLongDictionary())); - assertThrows(IllegalStateException.class, emptyDictionary::clear); - } - - @Test - void dictionaryOfTest() { - - var dictionary = LongDictionary.of(1, "val1", 2, "val2", 3, "val3"); - - assertEquals(3, dictionary.size()); - assertEquals("val1", dictionary.get(1)); - assertEquals("val3", dictionary.get(3)); - - assertThrows(IllegalArgumentException.class, () -> LongDictionary.of("Key1", 1, "Key2", 2, "Key3")); - assertThrows(IllegalArgumentException.class, () -> LongDictionary.of("Key1")); - } - - @Test - void collectorTest() { - - var dictionary = List - .of(1, 2, 3, 4, 5) - .stream() - .collect(toLongDictionary(Function.identity(), Function.identity())); - - assertEquals(5, dictionary.size()); - assertEquals(3, (int) dictionary.get(3)); - } -} diff --git a/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/ObjectDictionaryTest.java b/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/ObjectDictionaryTest.java deleted file mode 100644 index e08c1694..00000000 --- a/rlib-common/src/test/java/javasabr/rlib/common/util/dictionary/ObjectDictionaryTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package javasabr.rlib.common.util.dictionary; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * The list of tests {@link ObjectDictionary}. - * - * @author JavaSaBr - */ -public class ObjectDictionaryTest { - - @Test - void generalTest() { - - var dictionary = DictionaryFactory.newObjectDictionary(); - dictionary.put("Key5", 5); - dictionary.put("Key6", 6); - - Assertions.assertEquals(2, dictionary.size()); - - dictionary.put("Key7", 7); - - Assertions.assertEquals(3, dictionary.size()); - Assertions.assertEquals(7, (int) dictionary.get("Key7")); - - Assertions.assertEquals(8, (int) dictionary.getOrCompute("Key8", () -> 8)); - Assertions.assertEquals(9, (int) dictionary.getOrCompute("Key9", key -> 9)); - - Assertions.assertEquals(5, dictionary.size()); - - Assertions.assertEquals(8, (int) dictionary.remove("Key8")); - - Assertions.assertEquals(4, dictionary.size()); - } - - @Test - void dictionaryOfTest() { - - var dictionary = ObjectDictionary.of("Key1", 1, "Key2", 2, "Key3", 3); - - Assertions.assertEquals(3, dictionary.size()); - - Assertions.assertThrows(IllegalArgumentException.class, () -> ObjectDictionary.of("Key1", 1, "Key2", 2, "Key3")); - - Assertions.assertThrows(IllegalArgumentException.class, () -> ObjectDictionary.of("Key1")); - } - - @Test - void getOrDefaultTest() { - - var dictionary = ObjectDictionary.of("Key1", 1, "Key2", 2, "Key3", 3); - - Assertions.assertEquals(1, dictionary.get("Key1")); - Assertions.assertNull(dictionary.get("Key10")); - Assertions.assertEquals(10, dictionary.getOrDefault("Key10", 10)); - } -} diff --git a/rlib-concurrent/src/main/java/javasabr/rlib/concurrent/executor/impl/SingleThreadPeriodicTaskExecutor.java b/rlib-concurrent/src/main/java/javasabr/rlib/concurrent/executor/impl/SingleThreadPeriodicTaskExecutor.java index 6882f508..be85e367 100644 --- a/rlib-concurrent/src/main/java/javasabr/rlib/concurrent/executor/impl/SingleThreadPeriodicTaskExecutor.java +++ b/rlib-concurrent/src/main/java/javasabr/rlib/concurrent/executor/impl/SingleThreadPeriodicTaskExecutor.java @@ -9,12 +9,12 @@ import javasabr.rlib.collections.array.Array; import javasabr.rlib.collections.array.ArrayFactory; import javasabr.rlib.collections.array.MutableArray; +import javasabr.rlib.common.util.ThreadUtils; import javasabr.rlib.concurrent.executor.PeriodicTaskExecutor; import javasabr.rlib.concurrent.lock.LockFactory; import javasabr.rlib.concurrent.lock.Lockable; import javasabr.rlib.concurrent.task.PeriodicTask; import javasabr.rlib.concurrent.util.ConcurrentUtils; -import javasabr.rlib.common.util.ThreadUtils; import javasabr.rlib.functions.LongObjConsumer; import javasabr.rlib.logger.api.Logger; import javasabr.rlib.logger.api.LoggerManager; diff --git a/rlib-concurrent/src/main/java/javasabr/rlib/concurrent/lock/LockFactory.java b/rlib-concurrent/src/main/java/javasabr/rlib/concurrent/lock/LockFactory.java index 30c83ec0..490b93aa 100644 --- a/rlib-concurrent/src/main/java/javasabr/rlib/concurrent/lock/LockFactory.java +++ b/rlib-concurrent/src/main/java/javasabr/rlib/concurrent/lock/LockFactory.java @@ -5,8 +5,8 @@ import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.StampedLock; -import javasabr.rlib.concurrent.lock.impl.AtomicLock; import javasabr.rlib.concurrent.lock.impl.AtomicAsyncReadSyncWriteLock; +import javasabr.rlib.concurrent.lock.impl.AtomicLock; import javasabr.rlib.concurrent.lock.impl.ReentrantARSWLock; import javasabr.rlib.concurrent.lock.impl.ReentrantAtomicLock; diff --git a/rlib-concurrent/src/main/java/javasabr/rlib/concurrent/lock/impl/AtomicLock.java b/rlib-concurrent/src/main/java/javasabr/rlib/concurrent/lock/impl/AtomicLock.java index 4e465794..30c1655a 100644 --- a/rlib-concurrent/src/main/java/javasabr/rlib/concurrent/lock/impl/AtomicLock.java +++ b/rlib-concurrent/src/main/java/javasabr/rlib/concurrent/lock/impl/AtomicLock.java @@ -6,7 +6,6 @@ import java.util.concurrent.locks.Lock; import lombok.AccessLevel; import lombok.experimental.FieldDefaults; -import org.jspecify.annotations.NullMarked; /** * @author JavaSaBr diff --git a/rlib-functions/src/main/java/javasabr/rlib/functions/IntObjFunction.java b/rlib-functions/src/main/java/javasabr/rlib/functions/IntObjFunction.java new file mode 100644 index 00000000..0b7aab83 --- /dev/null +++ b/rlib-functions/src/main/java/javasabr/rlib/functions/IntObjFunction.java @@ -0,0 +1,10 @@ +package javasabr.rlib.functions; + +/** + * @author JavaSaBr + */ +@FunctionalInterface +public interface IntObjFunction { + + R apply(int arg1, T arg2); +} diff --git a/rlib-geometry/src/main/java/javasabr/rlib/geometry/Polygon.java b/rlib-geometry/src/main/java/javasabr/rlib/geometry/Polygon.java index 03675169..ce510ee3 100644 --- a/rlib-geometry/src/main/java/javasabr/rlib/geometry/Polygon.java +++ b/rlib-geometry/src/main/java/javasabr/rlib/geometry/Polygon.java @@ -1,7 +1,5 @@ package javasabr.rlib.geometry; -import static javasabr.rlib.common.util.array.ArrayFactory.toArray; - import java.util.Arrays; import lombok.AccessLevel; import lombok.Getter; @@ -81,11 +79,21 @@ public Polygon( Vector3f second, Vector3f third, Vector3fBuffer buffer) { - this(toArray(first, second, third), buffer); + this( + new Vector3f[]{ + first, + second, + third + }, buffer); } public Polygon(Vector3f first, Vector3f second, Vector3f third) { - this(toArray(first, second, third), Vector3fBuffer.NO_REUSE); + this( + new Vector3f[]{ + first, + second, + third + }, Vector3fBuffer.NO_REUSE); } /** diff --git a/rlib-geometry/src/main/java/javasabr/rlib/geometry/Quaternion4f.java b/rlib-geometry/src/main/java/javasabr/rlib/geometry/Quaternion4f.java index 44bef689..a2cb27d4 100644 --- a/rlib-geometry/src/main/java/javasabr/rlib/geometry/Quaternion4f.java +++ b/rlib-geometry/src/main/java/javasabr/rlib/geometry/Quaternion4f.java @@ -1,8 +1,8 @@ package javasabr.rlib.geometry; +import java.util.Random; +import java.util.concurrent.ThreadLocalRandom; import javasabr.rlib.common.util.ExtMath; -import javasabr.rlib.common.util.random.Random; -import javasabr.rlib.common.util.random.RandomFactory; import javasabr.rlib.geometry.util.AngleUtils; import lombok.AccessLevel; import lombok.AllArgsConstructor; @@ -24,8 +24,6 @@ public class Quaternion4f { public static final Quaternion4f IDENTITY = new Quaternion4f(0, 0, 0, 1); - private static final ThreadLocal RANDOM_LOCAL = ThreadLocal.withInitial(RandomFactory::newFastRandom); - private static final ThreadLocal ROTATION_LOCAL = ThreadLocal.withInitial(Quaternion4f::new); public static Quaternion4f threadLocal() { @@ -333,7 +331,7 @@ public final Quaternion4f normalizeLocal() { } public void random() { - random(RANDOM_LOCAL.get()); + random(ThreadLocalRandom.current()); } public void random(Random random) { diff --git a/rlib-network/src/main/java/javasabr/rlib/network/client/impl/DefaultClientNetwork.java b/rlib-network/src/main/java/javasabr/rlib/network/client/impl/DefaultClientNetwork.java index f4e5fb48..81f612a0 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/client/impl/DefaultClientNetwork.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/client/impl/DefaultClientNetwork.java @@ -10,8 +10,8 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BiFunction; -import javasabr.rlib.common.util.ThreadUtils; import javasabr.rlib.common.util.AsyncUtils; +import javasabr.rlib.common.util.ThreadUtils; import javasabr.rlib.logger.api.Logger; import javasabr.rlib.logger.api.LoggerManager; import javasabr.rlib.network.Connection; diff --git a/rlib-network/src/main/java/javasabr/rlib/network/server/impl/DefaultServerNetwork.java b/rlib-network/src/main/java/javasabr/rlib/network/server/impl/DefaultServerNetwork.java index 0d140639..579a04ea 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/server/impl/DefaultServerNetwork.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/server/impl/DefaultServerNetwork.java @@ -19,8 +19,8 @@ import java.util.function.Consumer; import javasabr.rlib.collections.array.ArrayFactory; import javasabr.rlib.collections.array.MutableArray; -import javasabr.rlib.common.util.GroupThreadFactory; import javasabr.rlib.common.util.ClassUtils; +import javasabr.rlib.common.util.GroupThreadFactory; import javasabr.rlib.common.util.Utils; import javasabr.rlib.logger.api.Logger; import javasabr.rlib.logger.api.LoggerManager; diff --git a/rlib-network/src/main/java/javasabr/rlib/network/util/NetworkUtils.java b/rlib-network/src/main/java/javasabr/rlib/network/util/NetworkUtils.java index 374a2186..de891beb 100644 --- a/rlib-network/src/main/java/javasabr/rlib/network/util/NetworkUtils.java +++ b/rlib-network/src/main/java/javasabr/rlib/network/util/NetworkUtils.java @@ -12,7 +12,6 @@ import java.security.cert.X509Certificate; import java.util.stream.IntStream; import javasabr.rlib.common.util.Utils; -import javasabr.rlib.common.util.array.ArrayFactory; import javasabr.rlib.network.BufferAllocator; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; @@ -101,7 +100,7 @@ public static SSLContext createAllTrustedClientSslContext() { try { var sslContext = SSLContext.getInstance("TLSv1.2"); - sslContext.init(null, ArrayFactory.toArray(new AllTrustManager()), new SecureRandom()); + sslContext.init(null, new TrustManager[]{new AllTrustManager()}, new SecureRandom()); return sslContext; diff --git a/rlib-plugin-system/src/main/java/javasabr/rlib/plugin/system/extension/ExtensionPointManager.java b/rlib-plugin-system/src/main/java/javasabr/rlib/plugin/system/extension/ExtensionPointManager.java index e9b6711c..16a77f37 100644 --- a/rlib-plugin-system/src/main/java/javasabr/rlib/plugin/system/extension/ExtensionPointManager.java +++ b/rlib-plugin-system/src/main/java/javasabr/rlib/plugin/system/extension/ExtensionPointManager.java @@ -2,7 +2,7 @@ import javasabr.rlib.collections.dictionary.Dictionary; import javasabr.rlib.collections.dictionary.DictionaryFactory; -import javasabr.rlib.collections.dictionary.LockableRefDictionary; +import javasabr.rlib.collections.dictionary.LockableRefToRefDictionary; import javasabr.rlib.common.util.ClassUtils; import javasabr.rlib.logger.api.Logger; import javasabr.rlib.logger.api.LoggerManager; @@ -27,10 +27,10 @@ public static ExtensionPoint register(String id) { return getInstance().create(id); } - LockableRefDictionary> extensionPoints; + LockableRefToRefDictionary> extensionPoints; public ExtensionPointManager() { - this.extensionPoints = DictionaryFactory.stampedLockBasedRefDictionary(); + this.extensionPoints = DictionaryFactory.stampedLockBasedRefToRefDictionary(); } public ExtensionPoint create(String id) { diff --git a/rlib-plugin-system/src/main/java/javasabr/rlib/plugin/system/impl/BasePluginSystem.java b/rlib-plugin-system/src/main/java/javasabr/rlib/plugin/system/impl/BasePluginSystem.java index dc12c9ac..f22f125f 100644 --- a/rlib-plugin-system/src/main/java/javasabr/rlib/plugin/system/impl/BasePluginSystem.java +++ b/rlib-plugin-system/src/main/java/javasabr/rlib/plugin/system/impl/BasePluginSystem.java @@ -25,8 +25,8 @@ import javasabr.rlib.collections.array.Array; import javasabr.rlib.collections.array.ArrayCollectors; import javasabr.rlib.collections.dictionary.DictionaryCollectors; -import javasabr.rlib.collections.dictionary.MutableRefDictionary; -import javasabr.rlib.collections.dictionary.RefDictionary; +import javasabr.rlib.collections.dictionary.MutableRefToRefDictionary; +import javasabr.rlib.collections.dictionary.RefToRefDictionary; import javasabr.rlib.common.util.ClassUtils; import javasabr.rlib.common.util.Utils; import javasabr.rlib.io.util.FileUtils; @@ -58,14 +58,14 @@ public class BasePluginSystem implements ConfigurablePluginSystem { protected record State( Array containers, Array plugins, - RefDictionary idToContainer, - RefDictionary idToPlugin) { + RefToRefDictionary idToContainer, + RefToRefDictionary idToPlugin) { static final State EMPTY = new State( Array.empty(PluginContainer.class), Array.empty(Plugin.class), - RefDictionary.empty(), - RefDictionary.empty()); + RefToRefDictionary.empty(), + RefToRefDictionary.empty()); } final ClassLoader baseLoader; @@ -130,13 +130,13 @@ protected BasePluginSystem preLoadImpl(Executor executor) { var idToContainer = containers .stream() - .collect(DictionaryCollectors.toRefDictionary(PluginContainer::id)); + .collect(DictionaryCollectors.toRefToRefDictionary(PluginContainer::id)); State newState = new State( containers, Array.empty(Plugin.class), idToContainer, - RefDictionary.empty()); + RefToRefDictionary.empty()); if (state.compareAndSet(current, newState)) { LOGGER.debug(containers, "Pre-loaded:%s"::formatted); @@ -172,7 +172,7 @@ protected BasePluginSystem initializeImpl(Executor executor) { .map(future -> future.thenApply(this::initializePlugin)) .map(CompletionStage::toCompletableFuture) .map(CompletableFuture::join) - .collect(DictionaryCollectors.toRefDictionary(Plugin::id)); + .collect(DictionaryCollectors.toRefToRefDictionary(Plugin::id)); State newState = new State( current.containers, @@ -458,11 +458,11 @@ public Plugin installPlugin(Path file, boolean needInitialize) { } } - var idToContainer = MutableRefDictionary.ofTypes(String.class, PluginContainer.class); + var idToContainer = MutableRefToRefDictionary.ofTypes(String.class, PluginContainer.class); idToContainer.putAll(current.idToContainer); idToContainer.put(container.id(), container); - var idToPlugin = MutableRefDictionary.ofTypes(String.class, Plugin.class); + var idToPlugin = MutableRefToRefDictionary.ofTypes(String.class, Plugin.class); idToPlugin.putAll(current.idToPlugin); idToPlugin.put(plugin.id(), plugin); @@ -491,11 +491,11 @@ public boolean removePlugin(Plugin plugin) { return false; } - var idToContainer = MutableRefDictionary.ofTypes(String.class, PluginContainer.class); + var idToContainer = MutableRefToRefDictionary.ofTypes(String.class, PluginContainer.class); idToContainer.putAll(current.idToContainer); idToContainer.remove(pluginId); - var idToPlugin = MutableRefDictionary.ofTypes(String.class, Plugin.class); + var idToPlugin = MutableRefToRefDictionary.ofTypes(String.class, Plugin.class); idToPlugin.putAll(current.idToPlugin); idToPlugin.remove(pluginId); diff --git a/settings.gradle b/settings.gradle index 8bfc2fb8..1a97b9d7 100644 --- a/settings.gradle +++ b/settings.gradle @@ -19,4 +19,5 @@ include ':rlib-collections' include ':rlib-functions' include ':rlib-reusable' include ':rlib-reference' -include ':rlib-concurrent' \ No newline at end of file +include ':rlib-concurrent' +include ':test-coverage' \ No newline at end of file diff --git a/test-coverage/build.gradle b/test-coverage/build.gradle new file mode 100644 index 00000000..7b385d79 --- /dev/null +++ b/test-coverage/build.gradle @@ -0,0 +1,24 @@ +plugins { + id 'jacoco-report-aggregation' +} + +dependencies { + jacocoAggregation projects.rlibClasspath + jacocoAggregation projects.rlibCollections + jacocoAggregation projects.rlibCommon + jacocoAggregation projects.rlibConcurrent + jacocoAggregation projects.rlibFunctions + jacocoAggregation projects.rlibGeometry + jacocoAggregation projects.rlibIo + jacocoAggregation projects.rlibLoggerApi + jacocoAggregation projects.rlibLoggerImpl + jacocoAggregation projects.rlibLoggerSlf4j + jacocoAggregation projects.rlibMail + jacocoAggregation projects.rlibNetwork + jacocoAggregation projects.rlibPluginSystem + jacocoAggregation projects.rlibReference + jacocoAggregation projects.rlibReusable + jacocoAggregation projects.rlibTestcontainers +} + +publishing.publications.remove(publishing.publications.mavenJava) \ No newline at end of file