From 7a5c195762cd301eba81d866fb42b0d01cca7143 Mon Sep 17 00:00:00 2001 From: Rasmus Ros Date: Mon, 16 Nov 2026 12:43:59 +0100 Subject: [PATCH] refactor: clarify utility package contracts --- README.md | 5 +- api/util.api | 203 ++++++++++----- api/util.klib.api | 199 +++++++++----- docs/packages.md | 242 ++++++++++++++++++ .../kotlin/com/eignex/util/arrays/ArgSort.kt | 6 +- .../com/eignex/util/arrays/EmptyArrays.kt | 10 +- .../com/eignex/util/collections/Bits.kt | 97 +------ .../util/collections/CollectionExtras.kt | 8 - .../eignex/util/collections/DynamicBits.kt | 13 +- .../eignex/util/collections/IntArrayDeque.kt | 4 +- .../eignex/util/collections/IntArrayList.kt | 14 +- .../com/eignex/util/collections/IntHashSet.kt | 22 +- .../com/eignex/util/collections/IntIntMap.kt | 16 +- .../com/eignex/util/collections/IntLongMap.kt | 8 +- .../com/eignex/util/collections/IntSwapSet.kt | 25 +- .../eignex/util/collections/LongArrayList.kt | 15 +- .../eignex/util/collections/LongHashSet.kt | 121 ++------- .../eignex/util/collections/MapOperations.kt | 26 ++ .../util/collections/MutableIntDoubleMap.kt | 2 + .../util/collections/MutableIntIntMap.kt | 2 +- .../util/collections/MutableIntLongMap.kt | 2 + .../util/collections/MutableIntObjectMap.kt | 40 +-- .../util/collections/MutableLongIntMap.kt | 69 +---- .../util/collections/MutableLongObjectMap.kt | 2 + .../cooperative/BoundedLongHashSet.kt | 101 ++++++++ .../cooperative/FundedMapUpdates.kt | 63 +++++ .../cooperative/PrepareIntSwapSet.kt | 22 ++ .../util/collections/internals/BitWords.kt | 11 + .../collections/internals/EmptyStorage.kt | 8 - .../util/collections/internals/IntKeyTable.kt | 9 +- .../collections/internals/LongKeyTable.kt | 9 +- .../collections/internals/OpenAddressing.kt | 15 -- .../util/collections/storage/BitsStorage.kt | 22 ++ .../collections/storage/CollectionStorage.kt | 111 ++++++++ .../util/collections/storage/PackedBits.kt | 83 ++++++ .../eignex/util/concurrent/AdderCounters.kt | 2 +- .../com/eignex/util/concurrent/AtomicCells.kt | 1 + .../com/eignex/util/concurrent/CellMode.kt | 67 ++--- .../com/eignex/util/concurrent/Counters.kt | 39 +++ .../com/eignex/util/concurrent/SerialCells.kt | 2 +- .../kotlin/com/eignex/util/hash/Hashes.kt | 17 +- .../kotlin/com/eignex/util/io/CharReader.kt | 1 + .../kotlin/com/eignex/util/io/CharSource.kt | 16 +- .../com/eignex/util/collections/BitsTest.kt | 75 +++--- .../util/collections/CollectionExtrasTest.kt | 1 + .../util/collections/CollectionModelTest.kt | 4 +- .../util/collections/IntArrayListTest.kt | 12 +- .../util/collections/LongArrayListTest.kt | 12 +- .../util/collections/LongHashSetTest.kt | 19 +- .../util/collections/MutableLongIntMapTest.kt | 1 + .../cooperative/PrepareIntSwapSetTest.kt | 22 ++ .../storage/CollectionStorageTest.kt | 74 ++++++ .../eignex/util/concurrent/CellModeTest.kt | 39 +++ .../com/eignex/util/io/CharSourceUseTest.kt | 26 +- .../com/eignex/util/io/ChunkedCharSource.kt | 6 +- .../{platform => runtime}/IdentityHash.kt | 2 +- .../diagnostics}/HeapSample.kt | 2 +- .../diagnostics}/RuntimeDiagnostics.kt | 2 +- .../{platform => runtime}/IdentityHashTest.kt | 2 +- .../util/concurrent/AdderCounters.jvm.kt | 26 -- .../com/eignex/util/io/TextFiles.jvm.kt | 3 +- .../{platform => runtime}/IdentityHash.jvm.kt | 2 +- .../diagnostics}/RuntimeDiagnostics.jvm.kt | 2 +- .../util/concurrent/AdderCountersTest.kt | 24 +- .../diagnostics}/RuntimeDiagnosticsTest.kt | 2 +- .../IdentityHash.native.kt | 2 +- .../diagnostics}/RuntimeDiagnostics.native.kt | 2 +- .../eignex/util/consumer/CommonConsumer.kt | 38 ++- .../util/consumer/CommonConsumerTest.kt | 7 + .../java/com/eignex/util/bench/Workloads.java | 4 +- 70 files changed, 1425 insertions(+), 736 deletions(-) create mode 100644 docs/packages.md create mode 100644 src/commonMain/kotlin/com/eignex/util/collections/MapOperations.kt create mode 100644 src/commonMain/kotlin/com/eignex/util/collections/cooperative/BoundedLongHashSet.kt create mode 100644 src/commonMain/kotlin/com/eignex/util/collections/cooperative/FundedMapUpdates.kt create mode 100644 src/commonMain/kotlin/com/eignex/util/collections/cooperative/PrepareIntSwapSet.kt create mode 100644 src/commonMain/kotlin/com/eignex/util/collections/storage/BitsStorage.kt create mode 100644 src/commonMain/kotlin/com/eignex/util/collections/storage/CollectionStorage.kt create mode 100644 src/commonMain/kotlin/com/eignex/util/collections/storage/PackedBits.kt create mode 100644 src/commonMain/kotlin/com/eignex/util/concurrent/Counters.kt create mode 100644 src/commonTest/kotlin/com/eignex/util/collections/cooperative/PrepareIntSwapSetTest.kt create mode 100644 src/commonTest/kotlin/com/eignex/util/collections/storage/CollectionStorageTest.kt rename src/hostMain/kotlin/com/eignex/util/{platform => runtime}/IdentityHash.kt (88%) rename src/hostMain/kotlin/com/eignex/util/{platform => runtime/diagnostics}/HeapSample.kt (89%) rename src/hostMain/kotlin/com/eignex/util/{platform => runtime/diagnostics}/RuntimeDiagnostics.kt (93%) rename src/hostTest/kotlin/com/eignex/util/{platform => runtime}/IdentityHashTest.kt (93%) rename src/jvmMain/kotlin/com/eignex/util/{platform => runtime}/IdentityHash.jvm.kt (83%) rename src/jvmMain/kotlin/com/eignex/util/{platform => runtime/diagnostics}/RuntimeDiagnostics.jvm.kt (97%) rename src/jvmTest/kotlin/com/eignex/util/{platform => runtime/diagnostics}/RuntimeDiagnosticsTest.kt (94%) rename src/nativeMain/kotlin/com/eignex/util/{platform => runtime}/IdentityHash.native.kt (89%) rename src/nativeMain/kotlin/com/eignex/util/{platform => runtime/diagnostics}/RuntimeDiagnostics.native.kt (88%) diff --git a/README.md b/README.md index d66f9bb..5887474 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,9 @@ Shared Kotlin Multiplatform primitives for Eignex libraries and applications. - Text input: chunked character sources, buffered character reading and compressed file input. - Host concurrency: ordered parallel execution on JVM threads and Native workers. - Process support: properties/environment, standard output flushing, error output and process exit. -- Runtime diagnostics: reference identity hashing, JVM heap samples and cumulative JIT compilation time. +- Runtime identity and diagnostics: reference identity hashing, JVM heap samples and cumulative JIT compilation time. Primitive collection benchmarks and the eignex-lab adapter are in [util-bench](util-bench/README.md). + +Package ownership, target availability, behavioral contracts and API migrations are documented in +[Package contracts](docs/packages.md). diff --git a/api/util.api b/api/util.api index 4a76677..71a6ce5 100644 --- a/api/util.api +++ b/api/util.api @@ -1,3 +1,7 @@ +public final class com/eignex/util/arrays/ArgMaxKt { + public static final fun argMaxOf (ILkotlin/jvm/functions/Function1;)I +} + public final class com/eignex/util/arrays/ArgSortKt { public static final fun argsortBy (ILkotlin/jvm/functions/Function2;)[I public static final fun argsortBy (I[I[ILkotlin/jvm/functions/Function2;)[I @@ -72,14 +76,11 @@ public final class com/eignex/util/collections/Bits : com/eignex/util/collection public final fun copy ()Lcom/eignex/util/collections/Bits; public fun copyFrom (Lcom/eignex/util/collections/BitSet;)V public final fun copyFrom (Lcom/eignex/util/collections/Bits;)V - public final fun copyWordsFrom (Lcom/eignex/util/collections/Bits;II)V public fun equals (Ljava/lang/Object;)Z public fun forEachSet (Lcom/eignex/util/collections/IntConsumer;)V public final fun forEachSet (Lkotlin/jvm/functions/Function1;)V public fun get (I)Z public fun getSize ()I - public final fun getWord (I)J - public final fun getWordCount ()I public final fun getWords ()[J public fun hashCode ()I public fun orInPlace (Lcom/eignex/util/collections/BitSet;)V @@ -87,30 +88,18 @@ public final class com/eignex/util/collections/Bits : com/eignex/util/collection public fun set (I)V public fun set (IZ)V public fun setRange (II)V - public final fun setWord (IJ)V public fun toBooleanArray ()[Z public fun toIntArray ()[I public fun toString ()Ljava/lang/String; } public final class com/eignex/util/collections/Bits$Companion { - public final fun clear ([JI)V - public final fun clearAbove ([JI)V - public final fun clearBelow ([JI)V public final fun empty (I)Lcom/eignex/util/collections/Bits; - public final fun fillRange ([JII)V - public final fun firstSet ([J)I public final fun full (I)Lcom/eignex/util/collections/Bits; - public final fun has ([JI)Z - public final fun lastSet ([J)I public final fun of (I[I)Lcom/eignex/util/collections/Bits; - public final fun popcount ([J)I - public final fun set ([JI)V - public final fun xorInto ([J[J)V } public final class com/eignex/util/collections/CollectionExtrasKt { - public static final fun hashTableCapacity (I)I public static final fun sortedKeys (Lcom/eignex/util/collections/IntKeyed;)[I public static final fun sortedKeys (Lcom/eignex/util/collections/LongKeyed;)[J public static final fun toSortedIntArray (Lcom/eignex/util/collections/IntCollection;)[I @@ -173,7 +162,6 @@ public final class com/eignex/util/collections/IntArrayDeque : com/eignex/util/c public fun contains (I)Z public fun forEach (Lcom/eignex/util/collections/IntConsumer;)V public fun get (I)I - public final fun getAllocatedBytes ()J public fun getSize ()I public fun isEmpty ()Z public final fun isNotEmpty ()Z @@ -195,7 +183,7 @@ public final class com/eignex/util/collections/IntArrayList : com/eignex/util/co public fun forEach (Lcom/eignex/util/collections/IntConsumer;)V public final fun forEach (Lkotlin/jvm/functions/Function1;)V public fun get (I)I - public final fun getBackingData ()[I + public final fun getBackingDataInternal ()[I public fun getSize ()I public final fun indexOf (I)I public final fun insertAt (II)V @@ -203,8 +191,8 @@ public final class com/eignex/util/collections/IntArrayList : com/eignex/util/co public final fun last ()I public final fun lowerBound (I)I public final fun lowerBoundDescending (I)I - public final fun removeAt (I)V - public final fun removeValue (I)Z + public final fun removeAtSwap (I)V + public final fun removeValueSwap (I)Z public final fun set (II)V public final fun sortByIntKey (ZLkotlin/jvm/functions/Function1;)V public static synthetic fun sortByIntKey$default (Lcom/eignex/util/collections/IntArrayList;ZLkotlin/jvm/functions/Function1;ILjava/lang/Object;)V @@ -248,8 +236,6 @@ public final class com/eignex/util/collections/IntHashSet : com/eignex/util/coll public fun contains (I)Z public fun forEach (Lcom/eignex/util/collections/IntConsumer;)V public final fun forEach (Lkotlin/jvm/functions/Function1;)V - public final fun forEachSlot (Lkotlin/jvm/functions/Function2;)V - public final fun getAllocatedBytes ()J public final fun getKeysInternal ()[I public fun getSize ()I public final fun getUsedInternal ()[Z @@ -339,7 +325,6 @@ public final class com/eignex/util/collections/IntSet$DefaultImpls { } public final class com/eignex/util/collections/IntSwapSet : com/eignex/util/collections/IntIndexedCollection, com/eignex/util/collections/MutableIntSet { - public static final field Companion Lcom/eignex/util/collections/IntSwapSet$Companion; public fun (I)V public fun add (I)Z public fun clear ()V @@ -354,10 +339,6 @@ public final class com/eignex/util/collections/IntSwapSet : com/eignex/util/coll public fun toIntArray ()[I } -public final class com/eignex/util/collections/IntSwapSet$Companion { - public final fun preparation (II)Lkotlin/sequences/Sequence; -} - public final class com/eignex/util/collections/LongArrayList : com/eignex/util/collections/LongIndexedCollection { public fun ()V public fun (I)V @@ -368,15 +349,14 @@ public final class com/eignex/util/collections/LongArrayList : com/eignex/util/c public fun forEach (Lcom/eignex/util/collections/LongConsumer;)V public final fun forEach (Lkotlin/jvm/functions/Function1;)V public fun get (I)J - public final fun getAllocatedBytes ()J public fun getSize ()I public final fun indexOf (J)I public final fun insertAt (IJ)V public fun isEmpty ()Z public final fun last ()J public final fun lowerBound (J)I - public final fun removeAt (I)V - public final fun removeValue (J)Z + public final fun removeAtSwap (I)V + public final fun removeValueSwap (J)Z public final fun set (IJ)V public final fun sort (Z)V public static synthetic fun sort$default (Lcom/eignex/util/collections/LongArrayList;ZILjava/lang/Object;)V @@ -411,10 +391,8 @@ public final class com/eignex/util/collections/LongHashSet : com/eignex/util/col public final fun canAddWithoutGrowing (I)Z public fun clear ()V public fun contains (J)Z - public final fun containsBounded (JJLkotlin/jvm/functions/Function0;Lkotlin/jvm/functions/Function0;)Ljava/lang/Boolean; public fun forEach (Lcom/eignex/util/collections/LongConsumer;)V public final fun forEach (Lkotlin/jvm/functions/Function1;)V - public final fun getAllocatedBytes ()J public final fun getKeysInternal ()[J public fun getSize ()I public final fun getUsedInternal ()[Z @@ -422,7 +400,6 @@ public final class com/eignex/util/collections/LongHashSet : com/eignex/util/col public final fun release ()V public fun remove (J)Z public fun toLongArray ()[J - public final fun tryAddBounded (JJJJLkotlin/jvm/functions/Function0;Lkotlin/jvm/functions/Function0;)Ljava/lang/Boolean; } public abstract interface class com/eignex/util/collections/LongIndexedCollection : com/eignex/util/collections/LongCollection { @@ -457,6 +434,11 @@ public final class com/eignex/util/collections/LongSet$DefaultImpls { public static fun toLongArray (Lcom/eignex/util/collections/LongSet;)[J } +public final class com/eignex/util/collections/MapOperationsKt { + public static final fun removeKeysAbove (Lcom/eignex/util/collections/MutableIntObjectMap;I)V + public static final fun valueAtMaxKey (Lcom/eignex/util/collections/MutableIntObjectMap;)Ljava/lang/Object; +} + public final class com/eignex/util/collections/MutableIntDoubleMap : com/eignex/util/collections/IntKeyed { public fun ()V public fun (I)V @@ -525,23 +507,17 @@ public final class com/eignex/util/collections/MutableIntObjectMap : com/eignex/ public fun containsKey (I)Z public final fun forEach (Lkotlin/jvm/functions/Function2;)V public fun forEachKey (Lcom/eignex/util/collections/IntConsumer;)V - public final fun forEachValueSlot (Lkotlin/jvm/functions/Function1;)V public final fun get (I)Ljava/lang/Object; public final fun getKeysInternal ()[I public final fun getOrPut (ILkotlin/jvm/functions/Function0;)Ljava/lang/Object; - public final fun getPrimitiveCapacityBytes ()J - public final fun getReferenceCapacity ()I public fun getSize ()I public final fun getUsedInternal ()[Z public final fun getValue (I)Ljava/lang/Object; - public final fun getValueStorageIdentity ()Ljava/lang/Object; public final fun getValuesInternal ()[Ljava/lang/Object; public final fun isEmpty ()Z public fun keysToIntArray ()[I public final fun put (ILjava/lang/Object;)V public final fun remove (I)Z - public final fun removeKeysAbove (I)V - public final fun valueAtMaxKey ()Ljava/lang/Object; } public abstract interface class com/eignex/util/collections/MutableIntSet : com/eignex/util/collections/IntSet { @@ -566,7 +542,6 @@ public final class com/eignex/util/collections/MutableLongIntMap : com/eignex/ut public fun forEachKey (Lcom/eignex/util/collections/LongConsumer;)V public final fun getKeysInternal ()[J public final fun getOrDefault (JI)I - public final fun getPrimitiveCapacityBytes ()J public fun getSize ()I public final fun getUsedInternal ()[Z public final fun getValuesInternal ()[I @@ -575,7 +550,6 @@ public final class com/eignex/util/collections/MutableLongIntMap : com/eignex/ut public final fun put (JI)V public final fun remove (J)Z public final fun removeAndGet (JI)I - public final fun removeAndUpdate (JLjava/lang/Long;ILkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function0;)Z } public final class com/eignex/util/collections/MutableLongObjectMap : com/eignex/util/collections/LongKeyed { @@ -610,10 +584,71 @@ public final class com/eignex/util/collections/MutableLongSet$DefaultImpls { public static fun toLongArray (Lcom/eignex/util/collections/MutableLongSet;)[J } +public final class com/eignex/util/collections/cooperative/BoundedLongHashSetKt { + public static final fun containsBounded (Lcom/eignex/util/collections/LongHashSet;JJLkotlin/jvm/functions/Function0;Lkotlin/jvm/functions/Function0;)Ljava/lang/Boolean; + public static final fun tryAddBounded (Lcom/eignex/util/collections/LongHashSet;JJJJLkotlin/jvm/functions/Function0;Lkotlin/jvm/functions/Function0;)Ljava/lang/Boolean; +} + +public final class com/eignex/util/collections/cooperative/FundedMapUpdatesKt { + public static final fun removeAndUpdate (Lcom/eignex/util/collections/MutableLongIntMap;JLjava/lang/Long;ILkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function0;)Z +} + +public final class com/eignex/util/collections/cooperative/PrepareIntSwapSetKt { + public static final fun prepareIntSwapSet (II)Lkotlin/sequences/Sequence; +} + public final class com/eignex/util/collections/internals/BitWordsKt { public static final fun forEachSetBit ([JILkotlin/jvm/functions/Function1;)V } +public final class com/eignex/util/collections/storage/BitsStorageKt { + public static final fun copyWordsFrom (Lcom/eignex/util/collections/Bits;Lcom/eignex/util/collections/Bits;II)V + public static final fun getWord (Lcom/eignex/util/collections/Bits;I)J + public static final fun getWordCount (Lcom/eignex/util/collections/Bits;)I + public static final fun setWord (Lcom/eignex/util/collections/Bits;IJ)V +} + +public final class com/eignex/util/collections/storage/CollectionStorageKt { + public static final fun borrowBackingArray (Lcom/eignex/util/collections/IntArrayList;)[I + public static final fun borrowBackingArray (Lcom/eignex/util/collections/LongArrayList;)[J + public static final fun forEachSlot (Lcom/eignex/util/collections/IntHashSet;Lkotlin/jvm/functions/Function2;)V + public static final fun forEachSlot (Lcom/eignex/util/collections/LongHashSet;Lkotlin/jvm/functions/Function2;)V + public static final fun forEachValueSlot (Lcom/eignex/util/collections/MutableIntObjectMap;Lkotlin/jvm/functions/Function1;)V + public static final fun forEachValueSlot (Lcom/eignex/util/collections/MutableLongObjectMap;Lkotlin/jvm/functions/Function1;)V + public static final fun getPrimitiveCapacityBytes (Lcom/eignex/util/collections/Bits;)J + public static final fun getPrimitiveCapacityBytes (Lcom/eignex/util/collections/DynamicBits;)J + public static final fun getPrimitiveCapacityBytes (Lcom/eignex/util/collections/IntArrayDeque;)J + public static final fun getPrimitiveCapacityBytes (Lcom/eignex/util/collections/IntArrayList;)J + public static final fun getPrimitiveCapacityBytes (Lcom/eignex/util/collections/IntHashSet;)J + public static final fun getPrimitiveCapacityBytes (Lcom/eignex/util/collections/LongArrayList;)J + public static final fun getPrimitiveCapacityBytes (Lcom/eignex/util/collections/LongHashSet;)J + public static final fun getPrimitiveCapacityBytes (Lcom/eignex/util/collections/MutableIntDoubleMap;)J + public static final fun getPrimitiveCapacityBytes (Lcom/eignex/util/collections/MutableIntIntMap;)J + public static final fun getPrimitiveCapacityBytes (Lcom/eignex/util/collections/MutableIntLongMap;)J + public static final fun getPrimitiveCapacityBytes (Lcom/eignex/util/collections/MutableIntObjectMap;)J + public static final fun getPrimitiveCapacityBytes (Lcom/eignex/util/collections/MutableLongIntMap;)J + public static final fun getPrimitiveCapacityBytes (Lcom/eignex/util/collections/MutableLongObjectMap;)J + public static final fun getReferenceCapacity (Lcom/eignex/util/collections/MutableIntObjectMap;)I + public static final fun getReferenceCapacity (Lcom/eignex/util/collections/MutableLongObjectMap;)I + public static final fun getValueStorageIdentity (Lcom/eignex/util/collections/MutableIntObjectMap;)Ljava/lang/Object; + public static final fun getValueStorageIdentity (Lcom/eignex/util/collections/MutableLongObjectMap;)Ljava/lang/Object; + public static final fun hashTableCapacity (I)I +} + +public final class com/eignex/util/collections/storage/PackedBits { + public static final field INSTANCE Lcom/eignex/util/collections/storage/PackedBits; + public final fun clear ([JI)V + public final fun clearAbove ([JI)V + public final fun clearBelow ([JI)V + public final fun fillRange ([JII)V + public final fun firstSet ([J)I + public final fun has ([JI)Z + public final fun lastSet ([J)I + public final fun popcount ([J)I + public final fun set ([JI)V + public final fun xorInto ([J[J)V +} + public final class com/eignex/util/concurrent/AdderCountersKt { public static final fun getAdderCounters ()Lcom/eignex/util/concurrent/CounterMode; } @@ -657,11 +692,6 @@ public final class com/eignex/util/concurrent/CellMode$DefaultImpls { public static synthetic fun newLongArray$default (Lcom/eignex/util/concurrent/CellMode;ILkotlin/jvm/functions/Function1;ILjava/lang/Object;)Lcom/eignex/util/concurrent/LongCellArray; } -public final class com/eignex/util/concurrent/CellModeKt { - public static final fun getValue (Lcom/eignex/util/concurrent/DoubleCounter;Ljava/lang/Object;Lkotlin/reflect/KProperty;)D - public static final fun getValue (Lcom/eignex/util/concurrent/LongCounter;Ljava/lang/Object;Lkotlin/reflect/KProperty;)J -} - public abstract interface class com/eignex/util/concurrent/CounterMode { public abstract fun newDouble (D)Lcom/eignex/util/concurrent/DoubleCounter; public static synthetic fun newDouble$default (Lcom/eignex/util/concurrent/CounterMode;DILjava/lang/Object;)Lcom/eignex/util/concurrent/DoubleCounter; @@ -674,8 +704,15 @@ public final class com/eignex/util/concurrent/CounterMode$DefaultImpls { public static synthetic fun newLong$default (Lcom/eignex/util/concurrent/CounterMode;JILjava/lang/Object;)Lcom/eignex/util/concurrent/LongCounter; } +public final class com/eignex/util/concurrent/CountersKt { + public static final fun getValue (Lcom/eignex/util/concurrent/DoubleCounter;Ljava/lang/Object;Lkotlin/reflect/KProperty;)D + public static final fun getValue (Lcom/eignex/util/concurrent/LongCounter;Ljava/lang/Object;Lkotlin/reflect/KProperty;)J +} + public abstract interface class com/eignex/util/concurrent/DoubleCell : com/eignex/util/concurrent/DoubleCounter { + public abstract fun addAndGet (D)D public abstract fun compareAndSet (DD)Z + public abstract fun store (D)V } public abstract interface class com/eignex/util/concurrent/DoubleCellArray { @@ -688,13 +725,13 @@ public abstract interface class com/eignex/util/concurrent/DoubleCellArray { public abstract interface class com/eignex/util/concurrent/DoubleCounter { public abstract fun add (D)V - public abstract fun addAndGet (D)D public abstract fun load ()D - public abstract fun store (D)V } public abstract interface class com/eignex/util/concurrent/LongCell : com/eignex/util/concurrent/LongCounter { + public abstract fun addAndGet (J)J public abstract fun compareAndSet (JJ)Z + public abstract fun store (J)V } public abstract interface class com/eignex/util/concurrent/LongCellArray { @@ -708,9 +745,7 @@ public abstract interface class com/eignex/util/concurrent/LongCellArray { public abstract interface class com/eignex/util/concurrent/LongCounter { public abstract fun add (J)V - public abstract fun addAndGet (J)J public abstract fun load ()J - public abstract fun store (J)V } public abstract interface class com/eignex/util/concurrent/Mutex { @@ -770,7 +805,8 @@ public final class com/eignex/util/io/CharReader { public static synthetic fun peek$default (Lcom/eignex/util/io/CharReader;IILjava/lang/Object;)I } -public abstract interface class com/eignex/util/io/CharSource { +public abstract interface class com/eignex/util/io/CharSource : java/lang/AutoCloseable { + public abstract fun close ()V public abstract fun next ()Ljava/lang/String; } @@ -782,6 +818,7 @@ public final class com/eignex/util/io/CharSourceKt { public final class com/eignex/util/io/StringCharSource : com/eignex/util/io/CharSource { public fun (Ljava/lang/String;)V + public fun close ()V public fun next ()Ljava/lang/String; } @@ -900,27 +937,65 @@ public final class com/eignex/util/numbers/SaturatingArithmeticKt { public static final fun saturatedSub (JJ)J } -public final class com/eignex/util/platform/HeapSample { +public final class com/eignex/util/process/Process_jvmKt { + public static final fun exitProcess (I)Ljava/lang/Void; + public static final fun flushStandardOutput ()V + public static final fun printErrorLine (Ljava/lang/String;)V + public static final fun processProperty (Ljava/lang/String;)Ljava/lang/String; +} + +public final class com/eignex/util/random/CounterRandom : kotlin/random/Random { + public fun (JLcom/eignex/util/concurrent/CellMode;)V + public synthetic fun (JLcom/eignex/util/concurrent/CellMode;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun childSeed ()J + public fun nextBits (I)I + public final fun reset ()V +} + +public final class com/eignex/util/random/CounterRandomKt { + public static final fun deriveChildSeed (JJ)J +} + +public final class com/eignex/util/random/DistributionsKt { + public static final fun nextBeta (Lkotlin/random/Random;DD)D + public static final fun nextGamma (Lkotlin/random/Random;D)D + public static final fun nextNormal (Lkotlin/random/Random;DD)D + public static synthetic fun nextNormal$default (Lkotlin/random/Random;DDILjava/lang/Object;)D + public static final fun nextPoissonOne (Lkotlin/random/Random;)I +} + +public final class com/eignex/util/random/SobolSequence { + public static final field Companion Lcom/eignex/util/random/SobolSequence$Companion; + public static final field MAX_DIMENSIONS I + public fun (ILjava/lang/Long;I)V + public synthetic fun (ILjava/lang/Long;IILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun getDimensionOffset ()I + public final fun getDimensions ()I + public final fun getScrambleSeed ()Ljava/lang/Long; + public final fun nextNormal ([D)[D + public static synthetic fun nextNormal$default (Lcom/eignex/util/random/SobolSequence;[DILjava/lang/Object;)[D + public final fun nextPoint ([D)[D + public static synthetic fun nextPoint$default (Lcom/eignex/util/random/SobolSequence;[DILjava/lang/Object;)[D + public final fun skipTo (J)V +} + +public final class com/eignex/util/random/SobolSequence$Companion { +} + +public final class com/eignex/util/runtime/IdentityHash_jvmKt { + public static final fun identityHash (Ljava/lang/Object;)I +} + +public final class com/eignex/util/runtime/diagnostics/HeapSample { public fun (JJLjava/lang/Long;)V public final fun getCommittedBytes ()J public final fun getPeakBytes ()Ljava/lang/Long; public final fun getRetainedBytes ()J } -public final class com/eignex/util/platform/IdentityHash_jvmKt { - public static final fun identityHash (Ljava/lang/Object;)I -} - -public final class com/eignex/util/platform/RuntimeDiagnostics_jvmKt { +public final class com/eignex/util/runtime/diagnostics/RuntimeDiagnostics_jvmKt { public static final fun compilationTimeMillis ()Ljava/lang/Long; - public static final fun sampleHeap ()Lcom/eignex/util/platform/HeapSample; + public static final fun sampleHeap ()Lcom/eignex/util/runtime/diagnostics/HeapSample; public static final fun startHeapPeakSampler ()V } -public final class com/eignex/util/process/Process_jvmKt { - public static final fun exitProcess (I)Ljava/lang/Void; - public static final fun flushStandardOutput ()V - public static final fun printErrorLine (Ljava/lang/String;)V - public static final fun processProperty (Ljava/lang/String;)Ljava/lang/String; -} - diff --git a/api/util.klib.api b/api/util.klib.api index d1443ab..ee1c234 100644 --- a/api/util.klib.api +++ b/api/util.klib.api @@ -134,7 +134,9 @@ abstract interface com.eignex.util.concurrent/CounterMode { // com.eignex.util.c } abstract interface com.eignex.util.concurrent/DoubleCell : com.eignex.util.concurrent/DoubleCounter { // com.eignex.util.concurrent/DoubleCell|null[0] + abstract fun addAndGet(kotlin/Double): kotlin/Double // com.eignex.util.concurrent/DoubleCell.addAndGet|addAndGet(kotlin.Double){}[0] abstract fun compareAndSet(kotlin/Double, kotlin/Double): kotlin/Boolean // com.eignex.util.concurrent/DoubleCell.compareAndSet|compareAndSet(kotlin.Double;kotlin.Double){}[0] + abstract fun store(kotlin/Double) // com.eignex.util.concurrent/DoubleCell.store|store(kotlin.Double){}[0] } abstract interface com.eignex.util.concurrent/DoubleCellArray { // com.eignex.util.concurrent/DoubleCellArray|null[0] @@ -149,13 +151,13 @@ abstract interface com.eignex.util.concurrent/DoubleCellArray { // com.eignex.ut abstract interface com.eignex.util.concurrent/DoubleCounter { // com.eignex.util.concurrent/DoubleCounter|null[0] abstract fun add(kotlin/Double) // com.eignex.util.concurrent/DoubleCounter.add|add(kotlin.Double){}[0] - abstract fun addAndGet(kotlin/Double): kotlin/Double // com.eignex.util.concurrent/DoubleCounter.addAndGet|addAndGet(kotlin.Double){}[0] abstract fun load(): kotlin/Double // com.eignex.util.concurrent/DoubleCounter.load|load(){}[0] - abstract fun store(kotlin/Double) // com.eignex.util.concurrent/DoubleCounter.store|store(kotlin.Double){}[0] } abstract interface com.eignex.util.concurrent/LongCell : com.eignex.util.concurrent/LongCounter { // com.eignex.util.concurrent/LongCell|null[0] + abstract fun addAndGet(kotlin/Long): kotlin/Long // com.eignex.util.concurrent/LongCell.addAndGet|addAndGet(kotlin.Long){}[0] abstract fun compareAndSet(kotlin/Long, kotlin/Long): kotlin/Boolean // com.eignex.util.concurrent/LongCell.compareAndSet|compareAndSet(kotlin.Long;kotlin.Long){}[0] + abstract fun store(kotlin/Long) // com.eignex.util.concurrent/LongCell.store|store(kotlin.Long){}[0] } abstract interface com.eignex.util.concurrent/LongCellArray { // com.eignex.util.concurrent/LongCellArray|null[0] @@ -171,9 +173,7 @@ abstract interface com.eignex.util.concurrent/LongCellArray { // com.eignex.util abstract interface com.eignex.util.concurrent/LongCounter { // com.eignex.util.concurrent/LongCounter|null[0] abstract fun add(kotlin/Long) // com.eignex.util.concurrent/LongCounter.add|add(kotlin.Long){}[0] - abstract fun addAndGet(kotlin/Long): kotlin/Long // com.eignex.util.concurrent/LongCounter.addAndGet|addAndGet(kotlin.Long){}[0] abstract fun load(): kotlin/Long // com.eignex.util.concurrent/LongCounter.load|load(){}[0] - abstract fun store(kotlin/Long) // com.eignex.util.concurrent/LongCounter.store|store(kotlin.Long){}[0] } abstract interface com.eignex.util.concurrent/Mutex { // com.eignex.util.concurrent/Mutex|null[0] @@ -182,7 +182,8 @@ abstract interface com.eignex.util.concurrent/Mutex { // com.eignex.util.concurr abstract fun exit() // com.eignex.util.concurrent/Mutex.exit|exit(){}[0] } -abstract interface com.eignex.util.io/CharSource { // com.eignex.util.io/CharSource|null[0] +abstract interface com.eignex.util.io/CharSource : kotlin/AutoCloseable { // com.eignex.util.io/CharSource|null[0] + abstract fun close() // com.eignex.util.io/CharSource.close|close(){}[0] abstract fun next(): kotlin/String? // com.eignex.util.io/CharSource.next|next(){}[0] } @@ -191,14 +192,8 @@ final class <#A: kotlin/Any?> com.eignex.util.collections/MutableIntObjectMap : final val keysInternal // com.eignex.util.collections/MutableIntObjectMap.keysInternal|{}keysInternal[0] final fun (): kotlin/IntArray // com.eignex.util.collections/MutableIntObjectMap.keysInternal.|(){}[0] - final val primitiveCapacityBytes // com.eignex.util.collections/MutableIntObjectMap.primitiveCapacityBytes|{}primitiveCapacityBytes[0] - final fun (): kotlin/Long // com.eignex.util.collections/MutableIntObjectMap.primitiveCapacityBytes.|(){}[0] - final val referenceCapacity // com.eignex.util.collections/MutableIntObjectMap.referenceCapacity|{}referenceCapacity[0] - final fun (): kotlin/Int // com.eignex.util.collections/MutableIntObjectMap.referenceCapacity.|(){}[0] final val usedInternal // com.eignex.util.collections/MutableIntObjectMap.usedInternal|{}usedInternal[0] final fun (): kotlin/BooleanArray // com.eignex.util.collections/MutableIntObjectMap.usedInternal.|(){}[0] - final val valueStorageIdentity // com.eignex.util.collections/MutableIntObjectMap.valueStorageIdentity|{}valueStorageIdentity[0] - final fun (): kotlin/Any // com.eignex.util.collections/MutableIntObjectMap.valueStorageIdentity.|(){}[0] final val valuesInternal // com.eignex.util.collections/MutableIntObjectMap.valuesInternal|{}valuesInternal[0] final fun (): kotlin/Array // com.eignex.util.collections/MutableIntObjectMap.valuesInternal.|(){}[0] @@ -214,10 +209,7 @@ final class <#A: kotlin/Any?> com.eignex.util.collections/MutableIntObjectMap : final fun keysToIntArray(): kotlin/IntArray // com.eignex.util.collections/MutableIntObjectMap.keysToIntArray|keysToIntArray(){}[0] final fun put(kotlin/Int, #A) // com.eignex.util.collections/MutableIntObjectMap.put|put(kotlin.Int;1:0){}[0] final fun remove(kotlin/Int): kotlin/Boolean // com.eignex.util.collections/MutableIntObjectMap.remove|remove(kotlin.Int){}[0] - final fun removeKeysAbove(kotlin/Int) // com.eignex.util.collections/MutableIntObjectMap.removeKeysAbove|removeKeysAbove(kotlin.Int){}[0] - final fun valueAtMaxKey(): #A? // com.eignex.util.collections/MutableIntObjectMap.valueAtMaxKey|valueAtMaxKey(){}[0] final inline fun forEach(kotlin/Function2) // com.eignex.util.collections/MutableIntObjectMap.forEach|forEach(kotlin.Function2){}[0] - final inline fun forEachValueSlot(kotlin/Function1<#A?, kotlin/Unit>) // com.eignex.util.collections/MutableIntObjectMap.forEachValueSlot|forEachValueSlot(kotlin.Function1<1:0?,kotlin.Unit>){}[0] final inline fun getOrPut(kotlin/Int, kotlin/Function0<#A>): #A // com.eignex.util.collections/MutableIntObjectMap.getOrPut|getOrPut(kotlin.Int;kotlin.Function0<1:0>){}[0] } @@ -252,8 +244,6 @@ final class com.eignex.util.collections/Bits : com.eignex.util.collections/BitSe final val size // com.eignex.util.collections/Bits.size|{}size[0] final fun (): kotlin/Int // com.eignex.util.collections/Bits.size.|(){}[0] - final val wordCount // com.eignex.util.collections/Bits.wordCount|{}wordCount[0] - final fun (): kotlin/Int // com.eignex.util.collections/Bits.wordCount.|(){}[0] final val words // com.eignex.util.collections/Bits.words|{}words[0] final fun (): kotlin/LongArray // com.eignex.util.collections/Bits.words.|(){}[0] @@ -266,34 +256,21 @@ final class com.eignex.util.collections/Bits : com.eignex.util.collections/BitSe final fun containsAll(com.eignex.util.collections/Bits): kotlin/Boolean // com.eignex.util.collections/Bits.containsAll|containsAll(com.eignex.util.collections.Bits){}[0] final fun copy(): com.eignex.util.collections/Bits // com.eignex.util.collections/Bits.copy|copy(){}[0] final fun copyFrom(com.eignex.util.collections/Bits) // com.eignex.util.collections/Bits.copyFrom|copyFrom(com.eignex.util.collections.Bits){}[0] - final fun copyWordsFrom(com.eignex.util.collections/Bits, kotlin/Int, kotlin/Int) // com.eignex.util.collections/Bits.copyWordsFrom|copyWordsFrom(com.eignex.util.collections.Bits;kotlin.Int;kotlin.Int){}[0] final fun equals(kotlin/Any?): kotlin/Boolean // com.eignex.util.collections/Bits.equals|equals(kotlin.Any?){}[0] final fun forEachSet(com.eignex.util.collections/IntConsumer) // com.eignex.util.collections/Bits.forEachSet|forEachSet(com.eignex.util.collections.IntConsumer){}[0] final fun get(kotlin/Int): kotlin/Boolean // com.eignex.util.collections/Bits.get|get(kotlin.Int){}[0] - final fun getWord(kotlin/Int): kotlin/Long // com.eignex.util.collections/Bits.getWord|getWord(kotlin.Int){}[0] final fun hashCode(): kotlin/Int // com.eignex.util.collections/Bits.hashCode|hashCode(){}[0] final fun orInPlace(com.eignex.util.collections/Bits) // com.eignex.util.collections/Bits.orInPlace|orInPlace(com.eignex.util.collections.Bits){}[0] final fun set(kotlin/Int) // com.eignex.util.collections/Bits.set|set(kotlin.Int){}[0] final fun setRange(kotlin/Int, kotlin/Int) // com.eignex.util.collections/Bits.setRange|setRange(kotlin.Int;kotlin.Int){}[0] - final fun setWord(kotlin/Int, kotlin/Long) // com.eignex.util.collections/Bits.setWord|setWord(kotlin.Int;kotlin.Long){}[0] final fun toIntArray(): kotlin/IntArray // com.eignex.util.collections/Bits.toIntArray|toIntArray(){}[0] final fun toString(): kotlin/String // com.eignex.util.collections/Bits.toString|toString(){}[0] final inline fun forEachSet(kotlin/Function1) // com.eignex.util.collections/Bits.forEachSet|forEachSet(kotlin.Function1){}[0] final object Companion { // com.eignex.util.collections/Bits.Companion|null[0] - final fun clear(kotlin/LongArray, kotlin/Int) // com.eignex.util.collections/Bits.Companion.clear|clear(kotlin.LongArray;kotlin.Int){}[0] - final fun clearAbove(kotlin/LongArray, kotlin/Int) // com.eignex.util.collections/Bits.Companion.clearAbove|clearAbove(kotlin.LongArray;kotlin.Int){}[0] - final fun clearBelow(kotlin/LongArray, kotlin/Int) // com.eignex.util.collections/Bits.Companion.clearBelow|clearBelow(kotlin.LongArray;kotlin.Int){}[0] final fun empty(kotlin/Int): com.eignex.util.collections/Bits // com.eignex.util.collections/Bits.Companion.empty|empty(kotlin.Int){}[0] - final fun fillRange(kotlin/LongArray, kotlin/Int, kotlin/Int) // com.eignex.util.collections/Bits.Companion.fillRange|fillRange(kotlin.LongArray;kotlin.Int;kotlin.Int){}[0] - final fun firstSet(kotlin/LongArray): kotlin/Int // com.eignex.util.collections/Bits.Companion.firstSet|firstSet(kotlin.LongArray){}[0] final fun full(kotlin/Int): com.eignex.util.collections/Bits // com.eignex.util.collections/Bits.Companion.full|full(kotlin.Int){}[0] - final fun has(kotlin/LongArray, kotlin/Int): kotlin/Boolean // com.eignex.util.collections/Bits.Companion.has|has(kotlin.LongArray;kotlin.Int){}[0] - final fun lastSet(kotlin/LongArray): kotlin/Int // com.eignex.util.collections/Bits.Companion.lastSet|lastSet(kotlin.LongArray){}[0] final fun of(kotlin/Int, kotlin/IntArray): com.eignex.util.collections/Bits // com.eignex.util.collections/Bits.Companion.of|of(kotlin.Int;kotlin.IntArray){}[0] - final fun popcount(kotlin/LongArray): kotlin/Int // com.eignex.util.collections/Bits.Companion.popcount|popcount(kotlin.LongArray){}[0] - final fun set(kotlin/LongArray, kotlin/Int) // com.eignex.util.collections/Bits.Companion.set|set(kotlin.LongArray;kotlin.Int){}[0] - final fun xorInto(kotlin/LongArray, kotlin/LongArray) // com.eignex.util.collections/Bits.Companion.xorInto|xorInto(kotlin.LongArray;kotlin.LongArray){}[0] } } @@ -346,8 +323,6 @@ final class com.eignex.util.collections/IndexedMaxHeap { // com.eignex.util.coll final class com.eignex.util.collections/IntArrayDeque : com.eignex.util.collections/IntIndexedCollection { // com.eignex.util.collections/IntArrayDeque|null[0] constructor (kotlin/Int = ...) // com.eignex.util.collections/IntArrayDeque.|(kotlin.Int){}[0] - final val allocatedBytes // com.eignex.util.collections/IntArrayDeque.allocatedBytes|{}allocatedBytes[0] - final fun (): kotlin/Long // com.eignex.util.collections/IntArrayDeque.allocatedBytes.|(){}[0] final val size // com.eignex.util.collections/IntArrayDeque.size|{}size[0] final fun (): kotlin/Int // com.eignex.util.collections/IntArrayDeque.size.|(){}[0] @@ -366,8 +341,8 @@ final class com.eignex.util.collections/IntArrayDeque : com.eignex.util.collecti final class com.eignex.util.collections/IntArrayList : com.eignex.util.collections/IntIndexedCollection { // com.eignex.util.collections/IntArrayList|null[0] constructor (kotlin/Int = ...) // com.eignex.util.collections/IntArrayList.|(kotlin.Int){}[0] - final val backingData // com.eignex.util.collections/IntArrayList.backingData|{}backingData[0] - final fun (): kotlin/IntArray // com.eignex.util.collections/IntArrayList.backingData.|(){}[0] + final val backingDataInternal // com.eignex.util.collections/IntArrayList.backingDataInternal|{}backingDataInternal[0] + final fun (): kotlin/IntArray // com.eignex.util.collections/IntArrayList.backingDataInternal.|(){}[0] final var size // com.eignex.util.collections/IntArrayList.size|{}size[0] final fun (): kotlin/Int // com.eignex.util.collections/IntArrayList.size.|(){}[0] @@ -384,8 +359,8 @@ final class com.eignex.util.collections/IntArrayList : com.eignex.util.collectio final fun last(): kotlin/Int // com.eignex.util.collections/IntArrayList.last|last(){}[0] final fun lowerBound(kotlin/Int): kotlin/Int // com.eignex.util.collections/IntArrayList.lowerBound|lowerBound(kotlin.Int){}[0] final fun lowerBoundDescending(kotlin/Int): kotlin/Int // com.eignex.util.collections/IntArrayList.lowerBoundDescending|lowerBoundDescending(kotlin.Int){}[0] - final fun removeAt(kotlin/Int) // com.eignex.util.collections/IntArrayList.removeAt|removeAt(kotlin.Int){}[0] - final fun removeValue(kotlin/Int): kotlin/Boolean // com.eignex.util.collections/IntArrayList.removeValue|removeValue(kotlin.Int){}[0] + final fun removeAtSwap(kotlin/Int) // com.eignex.util.collections/IntArrayList.removeAtSwap|removeAtSwap(kotlin.Int){}[0] + final fun removeValueSwap(kotlin/Int): kotlin/Boolean // com.eignex.util.collections/IntArrayList.removeValueSwap|removeValueSwap(kotlin.Int){}[0] final fun set(kotlin/Int, kotlin/Int) // com.eignex.util.collections/IntArrayList.set|set(kotlin.Int;kotlin.Int){}[0] final fun toIntArray(): kotlin/IntArray // com.eignex.util.collections/IntArrayList.toIntArray|toIntArray(){}[0] final fun toSet(): kotlin.collections/Set // com.eignex.util.collections/IntArrayList.toSet|toSet(){}[0] @@ -407,8 +382,6 @@ final class com.eignex.util.collections/IntDisjointSet { // com.eignex.util.coll final class com.eignex.util.collections/IntHashSet : com.eignex.util.collections/MutableIntSet { // com.eignex.util.collections/IntHashSet|null[0] constructor (kotlin/Int = ...) // com.eignex.util.collections/IntHashSet.|(kotlin.Int){}[0] - final val allocatedBytes // com.eignex.util.collections/IntHashSet.allocatedBytes|{}allocatedBytes[0] - final fun (): kotlin/Long // com.eignex.util.collections/IntHashSet.allocatedBytes.|(){}[0] final val keysInternal // com.eignex.util.collections/IntHashSet.keysInternal|{}keysInternal[0] final fun (): kotlin/IntArray // com.eignex.util.collections/IntHashSet.keysInternal.|(){}[0] final val usedInternal // com.eignex.util.collections/IntHashSet.usedInternal|{}usedInternal[0] @@ -425,7 +398,6 @@ final class com.eignex.util.collections/IntHashSet : com.eignex.util.collections final fun remove(kotlin/Int): kotlin/Boolean // com.eignex.util.collections/IntHashSet.remove|remove(kotlin.Int){}[0] final fun toIntArray(): kotlin/IntArray // com.eignex.util.collections/IntHashSet.toIntArray|toIntArray(){}[0] final inline fun forEach(kotlin/Function1) // com.eignex.util.collections/IntHashSet.forEach|forEach(kotlin.Function1){}[0] - final inline fun forEachSlot(kotlin/Function2) // com.eignex.util.collections/IntHashSet.forEachSlot|forEachSlot(kotlin.Function2){}[0] } final class com.eignex.util.collections/IntIntMap : com.eignex.util.collections/IntIntLookup { // com.eignex.util.collections/IntIntMap|null[0] @@ -474,18 +446,11 @@ final class com.eignex.util.collections/IntSwapSet : com.eignex.util.collections final fun remove(kotlin/Int): kotlin/Boolean // com.eignex.util.collections/IntSwapSet.remove|remove(kotlin.Int){}[0] final fun toIntArray(): kotlin/IntArray // com.eignex.util.collections/IntSwapSet.toIntArray|toIntArray(){}[0] final inline fun forEach(kotlin/Function1) // com.eignex.util.collections/IntSwapSet.forEach|forEach(kotlin.Function1){}[0] - - final object Companion { // com.eignex.util.collections/IntSwapSet.Companion|null[0] - final fun preparation(kotlin/Int, kotlin/Int): kotlin.sequences/Sequence // com.eignex.util.collections/IntSwapSet.Companion.preparation|preparation(kotlin.Int;kotlin.Int){}[0] - } } final class com.eignex.util.collections/LongArrayList : com.eignex.util.collections/LongIndexedCollection { // com.eignex.util.collections/LongArrayList|null[0] constructor (kotlin/Int = ...) // com.eignex.util.collections/LongArrayList.|(kotlin.Int){}[0] - final val allocatedBytes // com.eignex.util.collections/LongArrayList.allocatedBytes|{}allocatedBytes[0] - final fun (): kotlin/Long // com.eignex.util.collections/LongArrayList.allocatedBytes.|(){}[0] - final var size // com.eignex.util.collections/LongArrayList.size|{}size[0] final fun (): kotlin/Int // com.eignex.util.collections/LongArrayList.size.|(){}[0] @@ -499,8 +464,8 @@ final class com.eignex.util.collections/LongArrayList : com.eignex.util.collecti final fun isEmpty(): kotlin/Boolean // com.eignex.util.collections/LongArrayList.isEmpty|isEmpty(){}[0] final fun last(): kotlin/Long // com.eignex.util.collections/LongArrayList.last|last(){}[0] final fun lowerBound(kotlin/Long): kotlin/Int // com.eignex.util.collections/LongArrayList.lowerBound|lowerBound(kotlin.Long){}[0] - final fun removeAt(kotlin/Int) // com.eignex.util.collections/LongArrayList.removeAt|removeAt(kotlin.Int){}[0] - final fun removeValue(kotlin/Long): kotlin/Boolean // com.eignex.util.collections/LongArrayList.removeValue|removeValue(kotlin.Long){}[0] + final fun removeAtSwap(kotlin/Int) // com.eignex.util.collections/LongArrayList.removeAtSwap|removeAtSwap(kotlin.Int){}[0] + final fun removeValueSwap(kotlin/Long): kotlin/Boolean // com.eignex.util.collections/LongArrayList.removeValueSwap|removeValueSwap(kotlin.Long){}[0] final fun set(kotlin/Int, kotlin/Long) // com.eignex.util.collections/LongArrayList.set|set(kotlin.Int;kotlin.Long){}[0] final fun sort(kotlin/Boolean = ...) // com.eignex.util.collections/LongArrayList.sort|sort(kotlin.Boolean){}[0] final fun toLongArray(): kotlin/LongArray // com.eignex.util.collections/LongArrayList.toLongArray|toLongArray(){}[0] @@ -513,8 +478,6 @@ final class com.eignex.util.collections/LongArrayList : com.eignex.util.collecti final class com.eignex.util.collections/LongHashSet : com.eignex.util.collections/MutableLongSet { // com.eignex.util.collections/LongHashSet|null[0] constructor (kotlin/Int = ...) // com.eignex.util.collections/LongHashSet.|(kotlin.Int){}[0] - final val allocatedBytes // com.eignex.util.collections/LongHashSet.allocatedBytes|{}allocatedBytes[0] - final fun (): kotlin/Long // com.eignex.util.collections/LongHashSet.allocatedBytes.|(){}[0] final val keysInternal // com.eignex.util.collections/LongHashSet.keysInternal|{}keysInternal[0] final fun (): kotlin/LongArray // com.eignex.util.collections/LongHashSet.keysInternal.|(){}[0] final val usedInternal // com.eignex.util.collections/LongHashSet.usedInternal|{}usedInternal[0] @@ -527,13 +490,11 @@ final class com.eignex.util.collections/LongHashSet : com.eignex.util.collection final fun canAddWithoutGrowing(kotlin/Int): kotlin/Boolean // com.eignex.util.collections/LongHashSet.canAddWithoutGrowing|canAddWithoutGrowing(kotlin.Int){}[0] final fun clear() // com.eignex.util.collections/LongHashSet.clear|clear(){}[0] final fun contains(kotlin/Long): kotlin/Boolean // com.eignex.util.collections/LongHashSet.contains|contains(kotlin.Long){}[0] - final fun containsBounded(kotlin/Long, kotlin/Long, kotlin/Function0, kotlin/Function0): kotlin/Boolean? // com.eignex.util.collections/LongHashSet.containsBounded|containsBounded(kotlin.Long;kotlin.Long;kotlin.Function0;kotlin.Function0){}[0] final fun forEach(com.eignex.util.collections/LongConsumer) // com.eignex.util.collections/LongHashSet.forEach|forEach(com.eignex.util.collections.LongConsumer){}[0] final fun isEmpty(): kotlin/Boolean // com.eignex.util.collections/LongHashSet.isEmpty|isEmpty(){}[0] final fun release() // com.eignex.util.collections/LongHashSet.release|release(){}[0] final fun remove(kotlin/Long): kotlin/Boolean // com.eignex.util.collections/LongHashSet.remove|remove(kotlin.Long){}[0] final fun toLongArray(): kotlin/LongArray // com.eignex.util.collections/LongHashSet.toLongArray|toLongArray(){}[0] - final fun tryAddBounded(kotlin/Long, kotlin/Long, kotlin/Long, kotlin/Long, kotlin/Function0, kotlin/Function0): kotlin/Boolean? // com.eignex.util.collections/LongHashSet.tryAddBounded|tryAddBounded(kotlin.Long;kotlin.Long;kotlin.Long;kotlin.Long;kotlin.Function0;kotlin.Function0){}[0] final inline fun forEach(kotlin/Function1) // com.eignex.util.collections/LongHashSet.forEach|forEach(kotlin.Function1){}[0] } @@ -617,8 +578,6 @@ final class com.eignex.util.collections/MutableLongIntMap : com.eignex.util.coll final val keysInternal // com.eignex.util.collections/MutableLongIntMap.keysInternal|{}keysInternal[0] final fun (): kotlin/LongArray // com.eignex.util.collections/MutableLongIntMap.keysInternal.|(){}[0] - final val primitiveCapacityBytes // com.eignex.util.collections/MutableLongIntMap.primitiveCapacityBytes|{}primitiveCapacityBytes[0] - final fun (): kotlin/Long // com.eignex.util.collections/MutableLongIntMap.primitiveCapacityBytes.|(){}[0] final val usedInternal // com.eignex.util.collections/MutableLongIntMap.usedInternal|{}usedInternal[0] final fun (): kotlin/BooleanArray // com.eignex.util.collections/MutableLongIntMap.usedInternal.|(){}[0] final val valuesInternal // com.eignex.util.collections/MutableLongIntMap.valuesInternal|{}valuesInternal[0] @@ -637,7 +596,6 @@ final class com.eignex.util.collections/MutableLongIntMap : com.eignex.util.coll final fun put(kotlin/Long, kotlin/Int) // com.eignex.util.collections/MutableLongIntMap.put|put(kotlin.Long;kotlin.Int){}[0] final fun remove(kotlin/Long): kotlin/Boolean // com.eignex.util.collections/MutableLongIntMap.remove|remove(kotlin.Long){}[0] final fun removeAndGet(kotlin/Long, kotlin/Int): kotlin/Int // com.eignex.util.collections/MutableLongIntMap.removeAndGet|removeAndGet(kotlin.Long;kotlin.Int){}[0] - final fun removeAndUpdate(kotlin/Long, kotlin/Long?, kotlin/Int, kotlin/Function1, kotlin/Function0): kotlin/Boolean // com.eignex.util.collections/MutableLongIntMap.removeAndUpdate|removeAndUpdate(kotlin.Long;kotlin.Long?;kotlin.Int;kotlin.Function1;kotlin.Function0){}[0] final inline fun forEach(kotlin/Function2) // com.eignex.util.collections/MutableLongIntMap.forEach|forEach(kotlin.Function2){}[0] } @@ -652,6 +610,7 @@ final class com.eignex.util.io/CharReader { // com.eignex.util.io/CharReader|nul final class com.eignex.util.io/StringCharSource : com.eignex.util.io/CharSource { // com.eignex.util.io/StringCharSource|null[0] constructor (kotlin/String) // com.eignex.util.io/StringCharSource.|(kotlin.String){}[0] + final fun close() // com.eignex.util.io/StringCharSource.close|close(){}[0] final fun next(): kotlin/String? // com.eignex.util.io/StringCharSource.next|next(){}[0] } @@ -684,6 +643,47 @@ final class com.eignex.util.numbers/Int128 { // com.eignex.util.numbers/Int128|n final fun toLong(): kotlin/Long // com.eignex.util.numbers/Int128.toLong|toLong(){}[0] } +final class com.eignex.util.random/CounterRandom : kotlin.random/Random { // com.eignex.util.random/CounterRandom|null[0] + constructor (kotlin/Long, com.eignex.util.concurrent/CellMode = ...) // com.eignex.util.random/CounterRandom.|(kotlin.Long;com.eignex.util.concurrent.CellMode){}[0] + + final fun childSeed(): kotlin/Long // com.eignex.util.random/CounterRandom.childSeed|childSeed(){}[0] + final fun nextBits(kotlin/Int): kotlin/Int // com.eignex.util.random/CounterRandom.nextBits|nextBits(kotlin.Int){}[0] + final fun reset() // com.eignex.util.random/CounterRandom.reset|reset(){}[0] +} + +final class com.eignex.util.random/SobolSequence { // com.eignex.util.random/SobolSequence|null[0] + constructor (kotlin/Int, kotlin/Long? = ..., kotlin/Int = ...) // com.eignex.util.random/SobolSequence.|(kotlin.Int;kotlin.Long?;kotlin.Int){}[0] + + final val dimensionOffset // com.eignex.util.random/SobolSequence.dimensionOffset|{}dimensionOffset[0] + final fun (): kotlin/Int // com.eignex.util.random/SobolSequence.dimensionOffset.|(){}[0] + final val dimensions // com.eignex.util.random/SobolSequence.dimensions|{}dimensions[0] + final fun (): kotlin/Int // com.eignex.util.random/SobolSequence.dimensions.|(){}[0] + final val scrambleSeed // com.eignex.util.random/SobolSequence.scrambleSeed|{}scrambleSeed[0] + final fun (): kotlin/Long? // com.eignex.util.random/SobolSequence.scrambleSeed.|(){}[0] + + final fun nextNormal(kotlin/DoubleArray = ...): kotlin/DoubleArray // com.eignex.util.random/SobolSequence.nextNormal|nextNormal(kotlin.DoubleArray){}[0] + final fun nextPoint(kotlin/DoubleArray = ...): kotlin/DoubleArray // com.eignex.util.random/SobolSequence.nextPoint|nextPoint(kotlin.DoubleArray){}[0] + final fun skipTo(kotlin/Long) // com.eignex.util.random/SobolSequence.skipTo|skipTo(kotlin.Long){}[0] + + final object Companion { // com.eignex.util.random/SobolSequence.Companion|null[0] + final const val MAX_DIMENSIONS // com.eignex.util.random/SobolSequence.Companion.MAX_DIMENSIONS|{}MAX_DIMENSIONS[0] + final fun (): kotlin/Int // com.eignex.util.random/SobolSequence.Companion.MAX_DIMENSIONS.|(){}[0] + } +} + +final object com.eignex.util.collections.storage/PackedBits { // com.eignex.util.collections.storage/PackedBits|null[0] + final fun clear(kotlin/LongArray, kotlin/Int) // com.eignex.util.collections.storage/PackedBits.clear|clear(kotlin.LongArray;kotlin.Int){}[0] + final fun clearAbove(kotlin/LongArray, kotlin/Int) // com.eignex.util.collections.storage/PackedBits.clearAbove|clearAbove(kotlin.LongArray;kotlin.Int){}[0] + final fun clearBelow(kotlin/LongArray, kotlin/Int) // com.eignex.util.collections.storage/PackedBits.clearBelow|clearBelow(kotlin.LongArray;kotlin.Int){}[0] + final fun fillRange(kotlin/LongArray, kotlin/Int, kotlin/Int) // com.eignex.util.collections.storage/PackedBits.fillRange|fillRange(kotlin.LongArray;kotlin.Int;kotlin.Int){}[0] + final fun firstSet(kotlin/LongArray): kotlin/Int // com.eignex.util.collections.storage/PackedBits.firstSet|firstSet(kotlin.LongArray){}[0] + final fun has(kotlin/LongArray, kotlin/Int): kotlin/Boolean // com.eignex.util.collections.storage/PackedBits.has|has(kotlin.LongArray;kotlin.Int){}[0] + final fun lastSet(kotlin/LongArray): kotlin/Int // com.eignex.util.collections.storage/PackedBits.lastSet|lastSet(kotlin.LongArray){}[0] + final fun popcount(kotlin/LongArray): kotlin/Int // com.eignex.util.collections.storage/PackedBits.popcount|popcount(kotlin.LongArray){}[0] + final fun set(kotlin/LongArray, kotlin/Int) // com.eignex.util.collections.storage/PackedBits.set|set(kotlin.LongArray;kotlin.Int){}[0] + final fun xorInto(kotlin/LongArray, kotlin/LongArray) // com.eignex.util.collections.storage/PackedBits.xorInto|xorInto(kotlin.LongArray;kotlin.LongArray){}[0] +} + final object com.eignex.util.concurrent/AtomicCells : com.eignex.util.concurrent/CellMode { // com.eignex.util.concurrent/AtomicCells|null[0] final fun <#A1: kotlin/Any?> newReference(#A1): com.eignex.util.concurrent/ReferenceCell<#A1> // com.eignex.util.concurrent/AtomicCells.newReference|newReference(0:0){0§}[0] final fun newDouble(kotlin/Double): com.eignex.util.concurrent/DoubleCell // com.eignex.util.concurrent/AtomicCells.newDouble|newDouble(kotlin.Double){}[0] @@ -706,25 +706,76 @@ final object com.eignex.util.concurrent/SerialCells : com.eignex.util.concurrent final fun newLongArray(kotlin/Int, kotlin/Function1): com.eignex.util.concurrent/LongCellArray // com.eignex.util.concurrent/SerialCells.newLongArray|newLongArray(kotlin.Int;kotlin.Function1){}[0] } +final val com.eignex.util.collections.storage/primitiveCapacityBytes // com.eignex.util.collections.storage/primitiveCapacityBytes|@com.eignex.util.collections.Bits{}primitiveCapacityBytes[0] + final fun (com.eignex.util.collections/Bits).(): kotlin/Long // com.eignex.util.collections.storage/primitiveCapacityBytes.|@com.eignex.util.collections.Bits(){}[0] +final val com.eignex.util.collections.storage/primitiveCapacityBytes // com.eignex.util.collections.storage/primitiveCapacityBytes|@com.eignex.util.collections.DynamicBits{}primitiveCapacityBytes[0] + final fun (com.eignex.util.collections/DynamicBits).(): kotlin/Long // com.eignex.util.collections.storage/primitiveCapacityBytes.|@com.eignex.util.collections.DynamicBits(){}[0] +final val com.eignex.util.collections.storage/primitiveCapacityBytes // com.eignex.util.collections.storage/primitiveCapacityBytes|@com.eignex.util.collections.IntArrayDeque{}primitiveCapacityBytes[0] + final fun (com.eignex.util.collections/IntArrayDeque).(): kotlin/Long // com.eignex.util.collections.storage/primitiveCapacityBytes.|@com.eignex.util.collections.IntArrayDeque(){}[0] +final val com.eignex.util.collections.storage/primitiveCapacityBytes // com.eignex.util.collections.storage/primitiveCapacityBytes|@com.eignex.util.collections.IntArrayList{}primitiveCapacityBytes[0] + final fun (com.eignex.util.collections/IntArrayList).(): kotlin/Long // com.eignex.util.collections.storage/primitiveCapacityBytes.|@com.eignex.util.collections.IntArrayList(){}[0] +final val com.eignex.util.collections.storage/primitiveCapacityBytes // com.eignex.util.collections.storage/primitiveCapacityBytes|@com.eignex.util.collections.IntHashSet{}primitiveCapacityBytes[0] + final fun (com.eignex.util.collections/IntHashSet).(): kotlin/Long // com.eignex.util.collections.storage/primitiveCapacityBytes.|@com.eignex.util.collections.IntHashSet(){}[0] +final val com.eignex.util.collections.storage/primitiveCapacityBytes // com.eignex.util.collections.storage/primitiveCapacityBytes|@com.eignex.util.collections.LongArrayList{}primitiveCapacityBytes[0] + final fun (com.eignex.util.collections/LongArrayList).(): kotlin/Long // com.eignex.util.collections.storage/primitiveCapacityBytes.|@com.eignex.util.collections.LongArrayList(){}[0] +final val com.eignex.util.collections.storage/primitiveCapacityBytes // com.eignex.util.collections.storage/primitiveCapacityBytes|@com.eignex.util.collections.LongHashSet{}primitiveCapacityBytes[0] + final fun (com.eignex.util.collections/LongHashSet).(): kotlin/Long // com.eignex.util.collections.storage/primitiveCapacityBytes.|@com.eignex.util.collections.LongHashSet(){}[0] +final val com.eignex.util.collections.storage/primitiveCapacityBytes // com.eignex.util.collections.storage/primitiveCapacityBytes|@com.eignex.util.collections.MutableIntDoubleMap{}primitiveCapacityBytes[0] + final fun (com.eignex.util.collections/MutableIntDoubleMap).(): kotlin/Long // com.eignex.util.collections.storage/primitiveCapacityBytes.|@com.eignex.util.collections.MutableIntDoubleMap(){}[0] +final val com.eignex.util.collections.storage/primitiveCapacityBytes // com.eignex.util.collections.storage/primitiveCapacityBytes|@com.eignex.util.collections.MutableIntIntMap{}primitiveCapacityBytes[0] + final fun (com.eignex.util.collections/MutableIntIntMap).(): kotlin/Long // com.eignex.util.collections.storage/primitiveCapacityBytes.|@com.eignex.util.collections.MutableIntIntMap(){}[0] +final val com.eignex.util.collections.storage/primitiveCapacityBytes // com.eignex.util.collections.storage/primitiveCapacityBytes|@com.eignex.util.collections.MutableIntLongMap{}primitiveCapacityBytes[0] + final fun (com.eignex.util.collections/MutableIntLongMap).(): kotlin/Long // com.eignex.util.collections.storage/primitiveCapacityBytes.|@com.eignex.util.collections.MutableIntLongMap(){}[0] +final val com.eignex.util.collections.storage/primitiveCapacityBytes // com.eignex.util.collections.storage/primitiveCapacityBytes|@com.eignex.util.collections.MutableIntObjectMap<0:0>{0§}primitiveCapacityBytes[0] + final fun <#A1: kotlin/Any?> (com.eignex.util.collections/MutableIntObjectMap<#A1>).(): kotlin/Long // com.eignex.util.collections.storage/primitiveCapacityBytes.|@com.eignex.util.collections.MutableIntObjectMap<0:0>(){0§}[0] +final val com.eignex.util.collections.storage/primitiveCapacityBytes // com.eignex.util.collections.storage/primitiveCapacityBytes|@com.eignex.util.collections.MutableLongIntMap{}primitiveCapacityBytes[0] + final fun (com.eignex.util.collections/MutableLongIntMap).(): kotlin/Long // com.eignex.util.collections.storage/primitiveCapacityBytes.|@com.eignex.util.collections.MutableLongIntMap(){}[0] +final val com.eignex.util.collections.storage/primitiveCapacityBytes // com.eignex.util.collections.storage/primitiveCapacityBytes|@com.eignex.util.collections.MutableLongObjectMap<0:0>{0§}primitiveCapacityBytes[0] + final fun <#A1: kotlin/Any?> (com.eignex.util.collections/MutableLongObjectMap<#A1>).(): kotlin/Long // com.eignex.util.collections.storage/primitiveCapacityBytes.|@com.eignex.util.collections.MutableLongObjectMap<0:0>(){0§}[0] +final val com.eignex.util.collections.storage/referenceCapacity // com.eignex.util.collections.storage/referenceCapacity|@com.eignex.util.collections.MutableIntObjectMap<0:0>{0§}referenceCapacity[0] + final fun <#A1: kotlin/Any?> (com.eignex.util.collections/MutableIntObjectMap<#A1>).(): kotlin/Int // com.eignex.util.collections.storage/referenceCapacity.|@com.eignex.util.collections.MutableIntObjectMap<0:0>(){0§}[0] +final val com.eignex.util.collections.storage/referenceCapacity // com.eignex.util.collections.storage/referenceCapacity|@com.eignex.util.collections.MutableLongObjectMap<0:0>{0§}referenceCapacity[0] + final fun <#A1: kotlin/Any?> (com.eignex.util.collections/MutableLongObjectMap<#A1>).(): kotlin/Int // com.eignex.util.collections.storage/referenceCapacity.|@com.eignex.util.collections.MutableLongObjectMap<0:0>(){0§}[0] +final val com.eignex.util.collections.storage/valueStorageIdentity // com.eignex.util.collections.storage/valueStorageIdentity|@com.eignex.util.collections.MutableIntObjectMap<0:0>{0§}valueStorageIdentity[0] + final fun <#A1: kotlin/Any?> (com.eignex.util.collections/MutableIntObjectMap<#A1>).(): kotlin/Any // com.eignex.util.collections.storage/valueStorageIdentity.|@com.eignex.util.collections.MutableIntObjectMap<0:0>(){0§}[0] +final val com.eignex.util.collections.storage/valueStorageIdentity // com.eignex.util.collections.storage/valueStorageIdentity|@com.eignex.util.collections.MutableLongObjectMap<0:0>{0§}valueStorageIdentity[0] + final fun <#A1: kotlin/Any?> (com.eignex.util.collections/MutableLongObjectMap<#A1>).(): kotlin/Any // com.eignex.util.collections.storage/valueStorageIdentity.|@com.eignex.util.collections.MutableLongObjectMap<0:0>(){0§}[0] +final val com.eignex.util.collections.storage/wordCount // com.eignex.util.collections.storage/wordCount|@com.eignex.util.collections.Bits{}wordCount[0] + final fun (com.eignex.util.collections/Bits).(): kotlin/Int // com.eignex.util.collections.storage/wordCount.|@com.eignex.util.collections.Bits(){}[0] final val com.eignex.util.concurrent/AdderCounters // com.eignex.util.concurrent/AdderCounters|{}AdderCounters[0] final fun (): com.eignex.util.concurrent/CounterMode // com.eignex.util.concurrent/AdderCounters.|(){}[0] +final fun (com.eignex.util.collections/Bits).com.eignex.util.collections.storage/copyWordsFrom(com.eignex.util.collections/Bits, kotlin/Int, kotlin/Int) // com.eignex.util.collections.storage/copyWordsFrom|copyWordsFrom@com.eignex.util.collections.Bits(com.eignex.util.collections.Bits;kotlin.Int;kotlin.Int){}[0] +final fun (com.eignex.util.collections/Bits).com.eignex.util.collections.storage/getWord(kotlin/Int): kotlin/Long // com.eignex.util.collections.storage/getWord|getWord@com.eignex.util.collections.Bits(kotlin.Int){}[0] +final fun (com.eignex.util.collections/Bits).com.eignex.util.collections.storage/setWord(kotlin/Int, kotlin/Long) // com.eignex.util.collections.storage/setWord|setWord@com.eignex.util.collections.Bits(kotlin.Int;kotlin.Long){}[0] +final fun (com.eignex.util.collections/IntArrayList).com.eignex.util.collections.storage/borrowBackingArray(): kotlin/IntArray // com.eignex.util.collections.storage/borrowBackingArray|borrowBackingArray@com.eignex.util.collections.IntArrayList(){}[0] final fun (com.eignex.util.collections/IntCollection).com.eignex.util.collections/toSortedIntArray(): kotlin/IntArray // com.eignex.util.collections/toSortedIntArray|toSortedIntArray@com.eignex.util.collections.IntCollection(){}[0] final fun (com.eignex.util.collections/IntKeyed).com.eignex.util.collections/sortedKeys(): kotlin/IntArray // com.eignex.util.collections/sortedKeys|sortedKeys@com.eignex.util.collections.IntKeyed(){}[0] +final fun (com.eignex.util.collections/LongArrayList).com.eignex.util.collections.storage/borrowBackingArray(): kotlin/LongArray // com.eignex.util.collections.storage/borrowBackingArray|borrowBackingArray@com.eignex.util.collections.LongArrayList(){}[0] final fun (com.eignex.util.collections/LongCollection).com.eignex.util.collections/toSortedLongArray(): kotlin/LongArray // com.eignex.util.collections/toSortedLongArray|toSortedLongArray@com.eignex.util.collections.LongCollection(){}[0] +final fun (com.eignex.util.collections/LongHashSet).com.eignex.util.collections.cooperative/containsBounded(kotlin/Long, kotlin/Long, kotlin/Function0, kotlin/Function0): kotlin/Boolean? // com.eignex.util.collections.cooperative/containsBounded|containsBounded@com.eignex.util.collections.LongHashSet(kotlin.Long;kotlin.Long;kotlin.Function0;kotlin.Function0){}[0] +final fun (com.eignex.util.collections/LongHashSet).com.eignex.util.collections.cooperative/tryAddBounded(kotlin/Long, kotlin/Long, kotlin/Long, kotlin/Long, kotlin/Function0, kotlin/Function0): kotlin/Boolean? // com.eignex.util.collections.cooperative/tryAddBounded|tryAddBounded@com.eignex.util.collections.LongHashSet(kotlin.Long;kotlin.Long;kotlin.Long;kotlin.Long;kotlin.Function0;kotlin.Function0){}[0] final fun (com.eignex.util.collections/LongKeyed).com.eignex.util.collections/sortedKeys(): kotlin/LongArray // com.eignex.util.collections/sortedKeys|sortedKeys@com.eignex.util.collections.LongKeyed(){}[0] +final fun (com.eignex.util.collections/MutableLongIntMap).com.eignex.util.collections.cooperative/removeAndUpdate(kotlin/Long, kotlin/Long?, kotlin/Int, kotlin/Function1, kotlin/Function0): kotlin/Boolean // com.eignex.util.collections.cooperative/removeAndUpdate|removeAndUpdate@com.eignex.util.collections.MutableLongIntMap(kotlin.Long;kotlin.Long?;kotlin.Int;kotlin.Function1;kotlin.Function0){}[0] final fun (com.eignex.util.concurrent/DoubleCounter).com.eignex.util.concurrent/getValue(kotlin/Any?, kotlin.reflect/KProperty<*>): kotlin/Double // com.eignex.util.concurrent/getValue|getValue@com.eignex.util.concurrent.DoubleCounter(kotlin.Any?;kotlin.reflect.KProperty<*>){}[0] final fun (com.eignex.util.concurrent/LongCounter).com.eignex.util.concurrent/getValue(kotlin/Any?, kotlin.reflect/KProperty<*>): kotlin/Long // com.eignex.util.concurrent/getValue|getValue@com.eignex.util.concurrent.LongCounter(kotlin.Any?;kotlin.reflect.KProperty<*>){}[0] final fun (com.eignex.util.io/CharSource).com.eignex.util.io/lineSequence(): kotlin.sequences/Sequence // com.eignex.util.io/lineSequence|lineSequence@com.eignex.util.io.CharSource(){}[0] final fun (com.eignex.util.io/CharSource).com.eignex.util.io/readText(): kotlin/String // com.eignex.util.io/readText|readText@com.eignex.util.io.CharSource(){}[0] +final fun (kotlin.random/Random).com.eignex.util.random/nextBeta(kotlin/Double, kotlin/Double): kotlin/Double // com.eignex.util.random/nextBeta|nextBeta@kotlin.random.Random(kotlin.Double;kotlin.Double){}[0] +final fun (kotlin.random/Random).com.eignex.util.random/nextGamma(kotlin/Double): kotlin/Double // com.eignex.util.random/nextGamma|nextGamma@kotlin.random.Random(kotlin.Double){}[0] +final fun (kotlin.random/Random).com.eignex.util.random/nextNormal(kotlin/Double = ..., kotlin/Double = ...): kotlin/Double // com.eignex.util.random/nextNormal|nextNormal@kotlin.random.Random(kotlin.Double;kotlin.Double){}[0] +final fun (kotlin.random/Random).com.eignex.util.random/nextPoissonOne(): kotlin/Int // com.eignex.util.random/nextPoissonOne|nextPoissonOne@kotlin.random.Random(){}[0] final fun (kotlin/IntArray).com.eignex.util.arrays/binarySearchInt(kotlin/Int, kotlin/Int = ..., kotlin/Int = ...): kotlin/Int // com.eignex.util.arrays/binarySearchInt|binarySearchInt@kotlin.IntArray(kotlin.Int;kotlin.Int;kotlin.Int){}[0] final fun (kotlin/IntArray).com.eignex.util.arrays/lowerBoundInt(kotlin/Int, kotlin/Int = ..., kotlin/Int = ...): kotlin/Int // com.eignex.util.arrays/lowerBoundInt|lowerBoundInt@kotlin.IntArray(kotlin.Int;kotlin.Int;kotlin.Int){}[0] final fun (kotlin/LongArray).com.eignex.util.arrays/binarySearchLong(kotlin/Long, kotlin/Int = ..., kotlin/Int = ...): kotlin/Int // com.eignex.util.arrays/binarySearchLong|binarySearchLong@kotlin.LongArray(kotlin.Long;kotlin.Int;kotlin.Int){}[0] +final fun <#A: kotlin/Any?> (com.eignex.util.collections/MutableIntObjectMap<#A>).com.eignex.util.collections/removeKeysAbove(kotlin/Int) // com.eignex.util.collections/removeKeysAbove|removeKeysAbove@com.eignex.util.collections.MutableIntObjectMap<0:0>(kotlin.Int){0§}[0] +final fun <#A: kotlin/Any?> (com.eignex.util.collections/MutableIntObjectMap<#A>).com.eignex.util.collections/valueAtMaxKey(): #A? // com.eignex.util.collections/valueAtMaxKey|valueAtMaxKey@com.eignex.util.collections.MutableIntObjectMap<0:0>(){0§}[0] final fun com.eignex.util.arrays/emptyBooleanArray(): kotlin/BooleanArray // com.eignex.util.arrays/emptyBooleanArray|emptyBooleanArray(){}[0] final fun com.eignex.util.arrays/emptyDoubleArray(): kotlin/DoubleArray // com.eignex.util.arrays/emptyDoubleArray|emptyDoubleArray(){}[0] final fun com.eignex.util.arrays/emptyIntArray(): kotlin/IntArray // com.eignex.util.arrays/emptyIntArray|emptyIntArray(){}[0] final fun com.eignex.util.arrays/emptyLongArray(): kotlin/LongArray // com.eignex.util.arrays/emptyLongArray|emptyLongArray(){}[0] -final fun com.eignex.util.collections/hashTableCapacity(kotlin/Int): kotlin/Int // com.eignex.util.collections/hashTableCapacity|hashTableCapacity(kotlin.Int){}[0] +final fun com.eignex.util.collections.cooperative/prepareIntSwapSet(kotlin/Int, kotlin/Int): kotlin.sequences/Sequence // com.eignex.util.collections.cooperative/prepareIntSwapSet|prepareIntSwapSet(kotlin.Int;kotlin.Int){}[0] +final fun com.eignex.util.collections.storage/hashTableCapacity(kotlin/Int): kotlin/Int // com.eignex.util.collections.storage/hashTableCapacity|hashTableCapacity(kotlin.Int){}[0] final fun com.eignex.util.concurrent/Mutex(kotlin/Boolean = ...): com.eignex.util.concurrent/Mutex // com.eignex.util.concurrent/Mutex|Mutex(kotlin.Boolean){}[0] final fun com.eignex.util.concurrent/casMax(com.eignex.util.concurrent/DoubleCell, kotlin/Double) // com.eignex.util.concurrent/casMax|casMax(com.eignex.util.concurrent.DoubleCell;kotlin.Double){}[0] final fun com.eignex.util.concurrent/casMax(com.eignex.util.concurrent/LongCell, kotlin/Long) // com.eignex.util.concurrent/casMax|casMax(com.eignex.util.concurrent.LongCell;kotlin.Long){}[0] @@ -746,8 +797,14 @@ final fun com.eignex.util.numbers/saturatedDistance(kotlin/Long, kotlin/Long): k final fun com.eignex.util.numbers/saturatedMul(kotlin/Long, kotlin/Long): kotlin/Long // com.eignex.util.numbers/saturatedMul|saturatedMul(kotlin.Long;kotlin.Long){}[0] final fun com.eignex.util.numbers/saturatedSub(kotlin/Long, kotlin/Long): kotlin/Long // com.eignex.util.numbers/saturatedSub|saturatedSub(kotlin.Long;kotlin.Long){}[0] final fun com.eignex.util.numbers/subExact(kotlin/Long, kotlin/Long): kotlin/Long // com.eignex.util.numbers/subExact|subExact(kotlin.Long;kotlin.Long){}[0] +final fun com.eignex.util.random/deriveChildSeed(kotlin/Long, kotlin/Long): kotlin/Long // com.eignex.util.random/deriveChildSeed|deriveChildSeed(kotlin.Long;kotlin.Long){}[0] +final inline fun (com.eignex.util.collections/IntHashSet).com.eignex.util.collections.storage/forEachSlot(kotlin/Function2) // com.eignex.util.collections.storage/forEachSlot|forEachSlot@com.eignex.util.collections.IntHashSet(kotlin.Function2){}[0] +final inline fun (com.eignex.util.collections/LongHashSet).com.eignex.util.collections.storage/forEachSlot(kotlin/Function2) // com.eignex.util.collections.storage/forEachSlot|forEachSlot@com.eignex.util.collections.LongHashSet(kotlin.Function2){}[0] +final inline fun <#A: kotlin/Any?> (com.eignex.util.collections/MutableIntObjectMap<#A>).com.eignex.util.collections.storage/forEachValueSlot(kotlin/Function1<#A?, kotlin/Unit>) // com.eignex.util.collections.storage/forEachValueSlot|forEachValueSlot@com.eignex.util.collections.MutableIntObjectMap<0:0>(kotlin.Function1<0:0?,kotlin.Unit>){0§}[0] +final inline fun <#A: kotlin/Any?> (com.eignex.util.collections/MutableLongObjectMap<#A>).com.eignex.util.collections.storage/forEachValueSlot(kotlin/Function1<#A?, kotlin/Unit>) // com.eignex.util.collections.storage/forEachValueSlot|forEachValueSlot@com.eignex.util.collections.MutableLongObjectMap<0:0>(kotlin.Function1<0:0?,kotlin.Unit>){0§}[0] final inline fun <#A: kotlin/Any?> (com.eignex.util.concurrent/Mutex).com.eignex.util.concurrent/guarded(kotlin/Function0<#A>): #A // com.eignex.util.concurrent/guarded|guarded@com.eignex.util.concurrent.Mutex(kotlin.Function0<0:0>){0§}[0] final inline fun <#A: kotlin/Any?> (com.eignex.util.io/CharSource).com.eignex.util.io/useSource(kotlin/Function1): #A // com.eignex.util.io/useSource|useSource@com.eignex.util.io.CharSource(kotlin.Function1){0§}[0] +final inline fun com.eignex.util.arrays/argMaxOf(kotlin/Int, kotlin/Function1): kotlin/Int // com.eignex.util.arrays/argMaxOf|argMaxOf(kotlin.Int;kotlin.Function1){}[0] final inline fun com.eignex.util.arrays/argsortBy(kotlin/Int, kotlin/Function2): kotlin/IntArray // com.eignex.util.arrays/argsortBy|argsortBy(kotlin.Int;kotlin.Function2){}[0] final inline fun com.eignex.util.arrays/argsortBy(kotlin/Int, kotlin/IntArray, kotlin/IntArray, kotlin/Function2): kotlin/IntArray // com.eignex.util.arrays/argsortBy|argsortBy(kotlin.Int;kotlin.IntArray;kotlin.IntArray;kotlin.Function2){}[0] final inline fun com.eignex.util.arrays/argsortByIntKey(kotlin/Int, kotlin/Function1): kotlin/IntArray // com.eignex.util.arrays/argsortByIntKey|argsortByIntKey(kotlin.Int;kotlin.Function1){}[0] @@ -790,15 +847,15 @@ final class com.eignex.util.numbers/BigFraction { // com.eignex.util.numbers/Big } // Targets: [native] -final class com.eignex.util.platform/HeapSample { // com.eignex.util.platform/HeapSample|null[0] - constructor (kotlin/Long, kotlin/Long, kotlin/Long?) // com.eignex.util.platform/HeapSample.|(kotlin.Long;kotlin.Long;kotlin.Long?){}[0] +final class com.eignex.util.runtime.diagnostics/HeapSample { // com.eignex.util.runtime.diagnostics/HeapSample|null[0] + constructor (kotlin/Long, kotlin/Long, kotlin/Long?) // com.eignex.util.runtime.diagnostics/HeapSample.|(kotlin.Long;kotlin.Long;kotlin.Long?){}[0] - final val committedBytes // com.eignex.util.platform/HeapSample.committedBytes|{}committedBytes[0] - final fun (): kotlin/Long // com.eignex.util.platform/HeapSample.committedBytes.|(){}[0] - final val peakBytes // com.eignex.util.platform/HeapSample.peakBytes|{}peakBytes[0] - final fun (): kotlin/Long? // com.eignex.util.platform/HeapSample.peakBytes.|(){}[0] - final val retainedBytes // com.eignex.util.platform/HeapSample.retainedBytes|{}retainedBytes[0] - final fun (): kotlin/Long // com.eignex.util.platform/HeapSample.retainedBytes.|(){}[0] + final val committedBytes // com.eignex.util.runtime.diagnostics/HeapSample.committedBytes|{}committedBytes[0] + final fun (): kotlin/Long // com.eignex.util.runtime.diagnostics/HeapSample.committedBytes.|(){}[0] + final val peakBytes // com.eignex.util.runtime.diagnostics/HeapSample.peakBytes|{}peakBytes[0] + final fun (): kotlin/Long? // com.eignex.util.runtime.diagnostics/HeapSample.peakBytes.|(){}[0] + final val retainedBytes // com.eignex.util.runtime.diagnostics/HeapSample.retainedBytes|{}retainedBytes[0] + final fun (): kotlin/Long // com.eignex.util.runtime.diagnostics/HeapSample.retainedBytes.|(){}[0] } // Targets: [native] @@ -845,28 +902,28 @@ final fun com.eignex.util.numbers/minOf(com.ionspin.kotlin.bignum.integer/BigInt final fun com.eignex.util.numbers/parseBigInt(kotlin/String): com.ionspin.kotlin.bignum.integer/BigInteger // com.eignex.util.numbers/parseBigInt|parseBigInt(kotlin.String){}[0] // Targets: [native] -final fun com.eignex.util.platform/compilationTimeMillis(): kotlin/Long? // com.eignex.util.platform/compilationTimeMillis|compilationTimeMillis(){}[0] +final fun com.eignex.util.process/exitProcess(kotlin/Int): kotlin/Nothing // com.eignex.util.process/exitProcess|exitProcess(kotlin.Int){}[0] // Targets: [native] -final fun com.eignex.util.platform/identityHash(kotlin/Any): kotlin/Int // com.eignex.util.platform/identityHash|identityHash(kotlin.Any){}[0] +final fun com.eignex.util.process/flushStandardOutput() // com.eignex.util.process/flushStandardOutput|flushStandardOutput(){}[0] // Targets: [native] -final fun com.eignex.util.platform/sampleHeap(): com.eignex.util.platform/HeapSample? // com.eignex.util.platform/sampleHeap|sampleHeap(){}[0] +final fun com.eignex.util.process/printErrorLine(kotlin/String) // com.eignex.util.process/printErrorLine|printErrorLine(kotlin.String){}[0] // Targets: [native] -final fun com.eignex.util.platform/startHeapPeakSampler() // com.eignex.util.platform/startHeapPeakSampler|startHeapPeakSampler(){}[0] +final fun com.eignex.util.process/processProperty(kotlin/String): kotlin/String? // com.eignex.util.process/processProperty|processProperty(kotlin.String){}[0] // Targets: [native] -final fun com.eignex.util.process/exitProcess(kotlin/Int): kotlin/Nothing // com.eignex.util.process/exitProcess|exitProcess(kotlin.Int){}[0] +final fun com.eignex.util.runtime.diagnostics/compilationTimeMillis(): kotlin/Long? // com.eignex.util.runtime.diagnostics/compilationTimeMillis|compilationTimeMillis(){}[0] // Targets: [native] -final fun com.eignex.util.process/flushStandardOutput() // com.eignex.util.process/flushStandardOutput|flushStandardOutput(){}[0] +final fun com.eignex.util.runtime.diagnostics/sampleHeap(): com.eignex.util.runtime.diagnostics/HeapSample? // com.eignex.util.runtime.diagnostics/sampleHeap|sampleHeap(){}[0] // Targets: [native] -final fun com.eignex.util.process/printErrorLine(kotlin/String) // com.eignex.util.process/printErrorLine|printErrorLine(kotlin.String){}[0] +final fun com.eignex.util.runtime.diagnostics/startHeapPeakSampler() // com.eignex.util.runtime.diagnostics/startHeapPeakSampler|startHeapPeakSampler(){}[0] // Targets: [native] -final fun com.eignex.util.process/processProperty(kotlin/String): kotlin/String? // com.eignex.util.process/processProperty|processProperty(kotlin.String){}[0] +final fun com.eignex.util.runtime/identityHash(kotlin/Any): kotlin/Int // com.eignex.util.runtime/identityHash|identityHash(kotlin.Any){}[0] // Targets: [native] final inline fun (com.ionspin.kotlin.bignum.integer/BigInteger).com.eignex.util.numbers/abs(): com.ionspin.kotlin.bignum.integer/BigInteger // com.eignex.util.numbers/abs|abs@com.ionspin.kotlin.bignum.integer.BigInteger(){}[0] diff --git a/docs/packages.md b/docs/packages.md new file mode 100644 index 0000000..5bd16f3 --- /dev/null +++ b/docs/packages.md @@ -0,0 +1,242 @@ +# Package contracts + +Util is one Kotlin Multiplatform library. Packages group APIs by responsibility; +source sets express where those APIs are available. Adding a target does not +justify adding unrelated helpers to a package. + +## Ownership and dependencies + +| Package | Responsibility | Availability | +| --- | --- | --- | +| `arrays` | Primitive-array algorithms and shared empty arrays | All targets | +| `hash` | Deterministic noncryptographic hashing and key mixing | All targets | +| `collections` | Primitive containers, lookup contracts and derived collection operations | All targets | +| `collections.storage` | Explicit storage inspection, borrowed arrays and packed-word operations | All targets | +| `collections.cooperative` | Budgeted, cancellable or yielding collection algorithms | All targets | +| `concurrent` | Synchronous locks, cells, additive counters and joined parallel execution | All targets; `parallelRun` requires JVM or Native | +| `io` | Forward-only text consumption and UTF-8 file adapters | Text sources on all targets; files on JVM and POSIX Native | +| `numbers` | Checked and saturating arithmetic, a mutable 128-bit accumulator, backend integers and exact fractions | Fixed-width arithmetic on all targets; `BigInt` and `BigFraction` on JVM and Native | +| `random` | Seeded streams, distribution samplers and Sobol sequences | All targets | +| `runtime` | Runtime reference-identity operations | JVM and Native | +| `runtime.diagnostics` | Explicit heap and compiler diagnostics with optional support | JVM and Native; unavailable Native measurements return null | +| `process` | Process configuration, standard streams and termination | JVM and Native | + +`arrays` and `hash` are independent foundations. Collections depend on them, +never the reverse. `random` consumes hashing and cell contracts; foundational packages +do not depend on random generators. `collections.internals` owns table and packed-bit kernels; +its types and functions remain internal. Public packages outside the collections +family must not import collection internals. + +`collections.storage` and `collections.cooperative` depend on the containers. +Core containers do not depend on these optional API layers. Internal accessors +and publication kernels let those layers reuse storage without wrapper objects, +copying arrays or reimplementing container invariants. + +The other top-level packages have independent responsibilities. Avoid a generic +`platform`, `helpers` or `misc` package. Put platform implementations in the source +set of the API they implement, keeping the same semantic package. + +## Arrays + +Algorithms operate on primitive arrays or integer index ranges. Arguments and +results express whether memory is allocated, borrowed or mutated. Shared empty +arrays belong here; callers must not rely on their identity. + +Argsort is stable: equal keys retain input-index order. The buffered overload +may return either supplied buffer. Always use its returned reference and consume +only `0 until n`; both buffers are scratch storage, with their suffixes preserved. + +Binary search requires ascending input and a valid half-open range. It returns +the first matching index, or `-(insertion point) - 1`. Comparator and key callbacks +must remain consistent throughout an operation. + +## Collections + +Containers use primitive storage and avoid generic boxing in their primitive +traversal APIs. They are not thread-safe. Read-only interfaces restrict mutation +through that reference; they do not promise immutable underlying state. + +- Lists preserve append and insertion order. `removeAtSwap` and `removeValueSwap` + explicitly replace a removed element with the tail; they do not preserve order. +- Deques preserve sequence order, including `removeAt`, which shifts elements. +- Hash sets and maps have unspecified traversal order. Dense-id sets restrict + membership to the id range documented by their constructor. +- Integer-keyed lookup interfaces expose missing values per call. A stored value + may equal the default; use `containsKey` when presence matters. Immutable map + builders retain the last value for duplicate keys and own their resulting storage. +- Object maps may store null. `get` cannot distinguish a missing key from a stored + null; `containsKey` can, and `getValue` throws only for absence. `getOrPut` replaces + null values, matching its documented contract. +- Fixed and dynamic bitsets have a logical size independent of cardinality and + backing capacity. Fixed bit indices must lie within that size. Dynamic writes + can extend it; clearing beyond it does not grow it. Bitwise operations require + equal logical sizes. No cross-implementation equality contract is implied. +- Heaps, union-find and swap sets belong here as primitive data structures. Their + dense-id ranges, priority rules and mutation costs are part of their own contracts. + +Mutating a container during traversal is unsupported. Snapshot methods return +independent arrays. `clear` normally retains capacity; explicitly named `release` +operations relinquish owned storage. Constructor capacity is a reservation in +logical elements or entries, not a promise about physical array length. + +Derived queries such as `valueAtMaxKey` and compound convenience operations such +as `removeKeysAbove` are extensions in `MapOperations.kt`. Core members own the +container's invariants and primitive mutations. + +### Storage inspection + +Import `collections.storage` deliberately when inspecting representation: + +- `primitiveCapacityBytes` counts primitive backing payload capacity, including + unused capacity, with one byte per Boolean occupancy slot. It excludes object + headers, alignment, reference slots, referenced objects and shared empty storage. + It is a portable accounting model, not an exact runtime heap measurement. +- `referenceCapacity` counts object-array slots. Runtime reference width and the + ownership of referenced objects must be accounted for separately. +- `valueStorageIdentity` borrows the backing array as an identity token. Use + reference comparison only; do not cast or mutate it. Growth invalidates a + previously observed storage identity. +- `forEachSlot` and `forEachValueSlot` expose physical slots, including unused ones. + Their order and capacity may change after mutation. +- `borrowBackingArray` explicitly lends mutable list storage. Only `0 until size` + contains live elements. Growth or trimming can replace it; acquire it again + after mutation. This API does not transfer ownership. +- `Bits` word access masks padding on writes. `PackedBits` instead operates on + caller-owned `LongArray` words without a logical size or automatic padding mask. +- `hashTableCapacity` describes this library's current half-load table layout. + Storage layout and accounting can change even when collection semantics do not. + +These queries avoid allocating diagnostic snapshots. Ordinary container use does +not require a storage-inspection abstraction or extra per-instance state. + +### Cooperative operations + +`collections.cooperative` holds work/byte-limited lookup and insertion, funded map +updates, and `prepareIntSwapSet`. Exhaustion and cancellation preserve the published +container state where documented. Preparation may allocate temporary storage before +it can publish a result; retained and scratch limits have distinct meanings. + +Callbacks must not mutate or re-enter the container. Work units describe these +algorithms, not wall-clock deadlines. Yielding construction emits null at progress +boundaries and exactly one completed set as its final value. It does not promise +that allocation itself is interruptible. + +## Concurrency + +`CounterMode` creates additive counters with only `add` and `load`. Concurrent +striped reads can be approximate; no operation combines an add with an exact +returned result. JVM adders normalize negative zero, and floating-point totals +depend on accumulation order. Integer addition wraps on overflow. + +`CellMode` also supports exact replacement, update results and compare-and-set. +`AtomicCells` operations are linearizable on JVM and Native, independently per +array slot. `SerialCells` requires confinement or external synchronization. +JS and Wasm implementations operate within one execution agent and do not +synchronize separate workers. Reading several slots is not an atomic snapshot. + +Double-cell compare-and-set uses raw bits, including NaN payloads and signed zero. +Zero additions preserve those bits. Reference cells compare identity. These +contracts do not make a compound sequence of separate operations atomic. + +Locks are synchronous and non-reentrant. No-op locks require caller-owned or +otherwise synchronized state. `parallelRun` owns and joins its workers, returns +results in input order and waits for started tasks before reporting failure; it +is a host-only execution helper rather than a coroutine scheduler. + +## Text input + +A `CharSource` is a single-consumer, forward-only resource. `next` returns a +nonempty chunk or null; chunk boundaries carry no token, line or Unicode +code-point boundary guarantee. Every source is closeable. Closing is idempotent, +releases owned resources and makes later reads return null, including in-memory +sources. + +The caller owns the source. Use `useSource` or `use` for both complete reads and +early exits. `readText`, `lineSequence` and `CharReader` borrow it; they do not +take ownership. Consume lazy lines inside the owning scope. A reader's peek +results are UTF-16 character codes, with -1 indicating end of input. + +File adapters decode UTF-8. Compression is selected by the final suffix and may +require a system decompressor. JVM input streams; POSIX Native currently buffers +before decoding. A common interface does not imply identical memory use. + +## Numbers + +Checked Long helpers throw `CheckedLongOverflowException` rather than wrap. +Saturating helpers clamp overflow to the signed range. Host integer division +helpers explicitly select floor or ceiling rounding; `BigFraction` represents +normalized exact rational values over the existing backend integers. +`Int128` is a mutable accumulator, not a general immutable numeric value. Its +overflow latch invalidates the result until reset; quotient helpers describe +rounding, range and null-result behavior individually. + +`BigInt` remains a direct backend typealias for performance and interoperability. +It does not encapsulate backend members. Shared adapters normalize supported +operations where possible, but backend members take precedence over extensions. +In particular, use `remainderOf` for the shared truncating-remainder contract. +Do not add wrappers or imply that every exposed backend operation has portable +semantics. Backend-specific operations belong in target-specific consuming code. + +## Random sampling + +`CounterRandom` owns draw and child-stream counters. Its `CellMode` determines +confinement or synchronization; concurrent draws are assigned according to thread +scheduling, and reset requires exclusive access. Child-seed generation is separate +from draw position. These generators are not cryptographically secure. + +Distribution samplers consume the caller's `Random` without adding shared mutable +stream state. `SobolSequence` owns its mutable position and scratch storage and is +single-threaded; its scrambling, dimension projection and finite period are part +of its documented sequence contract. Keep numerical tables and their license +resources with this package rather than mixing them into general hashing helpers. + +## Hashing + +Hashes are deterministic and noncryptographic. `hash64` has stable output across +platforms and library versions, with UTF-8 string encoding and fixed little-endian +byte assembly. Changing its output requires an explicit compatibility decision; +keep golden-vector coverage. It is not Kotlin's object `hashCode` contract. + +Fibonacci mixers produce table hashes; they own no table capacity or probing +policy. Collections consume them from `hash`. `runtime.identityHash` instead +tracks a reference during its lifetime in one process and is not a persistent +content hash or a unique object id. + +## Runtime and process + +Runtime identity is independent of an object's overridden equality or hash code. +Diagnostics are explicitly opt-in: heap sampling can trigger garbage collection, +peak sampling starts a process-lifetime JVM daemon, and unavailable measurements +return null. These are diagnostic readings, not allocation accounting. + +Process helpers own process-wide effects. Configuration lookup checks a JVM +property first, then an environment name uppercased with dots replaced by +underscores. Standard-error output, standard-output flushing and termination stay +in `process`; they do not belong in text-source adapters or runtime diagnostics. + +## API migration + +This cleanup intentionally changes public source and binary APIs. Update imports +and rebuild consumers together with the library; the old names are not retained +as a second public API surface. + +| Previous API | Replacement | +| --- | --- | +| Primitive list `removeAt` / `removeValue` | `removeAtSwap` / `removeValueSwap` | +| Collection `allocatedBytes` | Import `collections.storage.primitiveCapacityBytes` | +| Public map storage properties / slot traversal | Import matching extensions from `collections.storage` | +| `IntArrayList.backingData` | Import and call `collections.storage.borrowBackingArray` | +| `Bits` word access and `wordCount` | Import matching extensions from `collections.storage` | +| Raw-array helpers on `Bits` | `collections.storage.PackedBits` | +| `collections.hashTableCapacity` | `collections.storage.hashTableCapacity` | +| `MutableIntObjectMap` derived helpers | Import `collections.removeKeysAbove` / `collections.valueAtMaxKey` | +| Budgeted Long-set and funded map members | Import matching extensions from `collections.cooperative` | +| `IntSwapSet.preparation` | `collections.cooperative.prepareIntSwapSet` | +| Counter `store` / `addAndGet` | Use a `CellMode` when exact replacement or update results are required | +| `platform.identityHash` | `runtime.identityHash` | +| Other `platform` diagnostics | `runtime.diagnostics` | +| Custom `CharSource` implementations | Implement idempotent `close` and stop reading after closure | + +For an approximate add-then-read on a counter, call `add` followed by `load` and +accept that concurrent additions can be included. An exact cell update requires +`AtomicCells`, or `SerialCells` under the caller's synchronization. diff --git a/src/commonMain/kotlin/com/eignex/util/arrays/ArgSort.kt b/src/commonMain/kotlin/com/eignex/util/arrays/ArgSort.kt index 5f8de42..c1ca505 100644 --- a/src/commonMain/kotlin/com/eignex/util/arrays/ArgSort.kt +++ b/src/commonMain/kotlin/com/eignex/util/arrays/ArgSort.kt @@ -19,7 +19,11 @@ inline fun argsortBy(n: Int, compare: (Int, Int) -> Int): IntArray { return argsortBy(n, order, IntArray(n), compare) } -/** Stable argsort into distinct caller-owned [order] and [scratch] buffers of at least [n] entries. */ +/** + * Stable argsort using distinct caller-owned [order] and [scratch] buffers of at least [n] entries. + * Returns whichever buffer holds the result; consume only its first [n] entries. Both buffers may + * be modified. No result copy is made, and entries at or beyond [n] are left unchanged. + */ inline fun argsortBy(n: Int, order: IntArray, scratch: IntArray, compare: (Int, Int) -> Int): IntArray { require(n >= 0 && n <= order.size && n <= scratch.size) require(order !== scratch) diff --git a/src/commonMain/kotlin/com/eignex/util/arrays/EmptyArrays.kt b/src/commonMain/kotlin/com/eignex/util/arrays/EmptyArrays.kt index 966555a..7715002 100644 --- a/src/commonMain/kotlin/com/eignex/util/arrays/EmptyArrays.kt +++ b/src/commonMain/kotlin/com/eignex/util/arrays/EmptyArrays.kt @@ -1,10 +1,5 @@ package com.eignex.util.arrays -import com.eignex.util.collections.internals.EmptyBooleanArray -import com.eignex.util.collections.internals.EmptyDoubleArray -import com.eignex.util.collections.internals.EmptyIntArray -import com.eignex.util.collections.internals.EmptyLongArray - /** Shared zero-length primitive array. */ fun emptyIntArray(): IntArray = EmptyIntArray @@ -16,3 +11,8 @@ fun emptyBooleanArray(): BooleanArray = EmptyBooleanArray /** Shared zero-length primitive array. */ fun emptyDoubleArray(): DoubleArray = EmptyDoubleArray + +private val EmptyIntArray = IntArray(0) +private val EmptyLongArray = LongArray(0) +private val EmptyBooleanArray = BooleanArray(0) +private val EmptyDoubleArray = DoubleArray(0) diff --git a/src/commonMain/kotlin/com/eignex/util/collections/Bits.kt b/src/commonMain/kotlin/com/eignex/util/collections/Bits.kt index f046ffb..073cd79 100644 --- a/src/commonMain/kotlin/com/eignex/util/collections/Bits.kt +++ b/src/commonMain/kotlin/com/eignex/util/collections/Bits.kt @@ -10,25 +10,6 @@ class Bits(size: Int) : BitSet { @PublishedApi internal val words: LongArray = LongArray(bitWordCount(size)) - /** Number of packed 64-bit words, including a partial final word. */ - val wordCount: Int get() = words.size - - /** Packed word at [index], which must lie in `0 until wordCount`. */ - fun getWord(index: Int): Long = words[index] - - /** Replace packed word [index], clearing padding beyond [size] in the final word. */ - fun setWord(index: Int, value: Long) { - val tail = size and 63 - words[index] = if (index == words.lastIndex && tail != 0) value and (-1L ushr (64 - tail)) else value - } - - /** Copy matching word positions `[fromIndex, toIndex)` from equal-sized [other]. */ - fun copyWordsFrom(other: Bits, fromIndex: Int, toIndex: Int) { - require(size == other.size) - require(fromIndex >= 0 && fromIndex <= toIndex && toIndex <= wordCount) - other.words.copyInto(words, fromIndex, fromIndex, toIndex) - } - override operator fun get(i: Int): Boolean = (words[i ushr 6] ushr (i and 63)) and 1L == 1L override fun set(i: Int) { @@ -133,84 +114,8 @@ class Bits(size: Int) : BitSet { return sb.toString() } - /** Operations on packed bit arrays. */ + /** Factories for fixed-size logical bitsets. */ companion object { - /** Return whether [bit] is set in [bits]. */ - fun has(bits: LongArray, bit: Int): Boolean = ((bits[bit ushr 6] ushr (bit and 63)) and 1L) != 0L - - /** Set [bit] in [bits]. */ - fun set(bits: LongArray, bit: Int) { - bits[bit ushr 6] = bits[bit ushr 6] or (1L shl (bit and 63)) - } - - /** Clear [bit] in [bits]. */ - fun clear(bits: LongArray, bit: Int) { - val w = bit ushr 6 - bits[w] = bits[w] and (1L shl (bit and 63)).inv() - } - - /** Set bits `[from, to)`. */ - fun fillRange(bits: LongArray, from: Int, to: Int) { - if (from >= to) return - fillBitRange(bits, from, to, true) - } - - /** Clear all bits with index `< exclusiveBit`. */ - fun clearBelow(bits: LongArray, exclusiveBit: Int) { - if (exclusiveBit <= 0) return - val fullWords = exclusiveBit ushr 6 - val rem = exclusiveBit and 63 - val limit = minOf(fullWords, bits.size) - for (w in 0 until limit) bits[w] = 0L - if (fullWords < bits.size && rem > 0) { - bits[fullWords] = bits[fullWords] and ((1L shl rem) - 1L).inv() - } - } - - /** Clear all bits with index `> inclusiveBit`. */ - fun clearAbove(bits: LongArray, inclusiveBit: Int) { - if (inclusiveBit < 0) { - bits.fill(0L) - return - } - val fromWord = (inclusiveBit + 1) ushr 6 - val rem = (inclusiveBit + 1) and 63 - if (fromWord < bits.size && rem > 0) { - bits[fromWord] = bits[fromWord] and ((1L shl rem) - 1L) - for (w in fromWord + 1 until bits.size) bits[w] = 0L - } else { - for (w in fromWord until bits.size) bits[w] = 0L - } - } - - /** XOR [src] into [dst] word-by-word: `dst ^= src`. Both arrays must be the same length. */ - fun xorInto(dst: LongArray, src: LongArray) { - for (i in dst.indices) dst[i] = dst[i] xor src[i] - } - - /** Number of set bits across all words. */ - fun popcount(bits: LongArray): Int { - var c = 0 - for (w in bits) c += w.countOneBits() - return c - } - - /** Return the lowest set-bit index, or `-1` when [bits] is empty. */ - fun firstSet(bits: LongArray): Int { - for (w in bits.indices) { - if (bits[w] != 0L) return (w shl 6) + bits[w].countTrailingZeroBits() - } - return -1 - } - - /** Return the highest set-bit index, or `-1` when [bits] is empty. */ - fun lastSet(bits: LongArray): Int { - for (w in bits.indices.reversed()) { - if (bits[w] != 0L) return (w shl 6) + (63 - bits[w].countLeadingZeroBits()) - } - return -1 - } - /** Return an empty bitset of [size] bits. */ fun empty(size: Int): Bits = Bits(size) diff --git a/src/commonMain/kotlin/com/eignex/util/collections/CollectionExtras.kt b/src/commonMain/kotlin/com/eignex/util/collections/CollectionExtras.kt index cc1118a..8d98ea8 100644 --- a/src/commonMain/kotlin/com/eignex/util/collections/CollectionExtras.kt +++ b/src/commonMain/kotlin/com/eignex/util/collections/CollectionExtras.kt @@ -1,7 +1,5 @@ package com.eignex.util.collections -import com.eignex.util.collections.internals.openAddressingCapacity - /** A fresh ascending copy of the elements, preserving repeated values. */ fun IntCollection.toSortedIntArray(): IntArray = toIntArray().also { it.sort() } @@ -13,9 +11,3 @@ fun IntKeyed.sortedKeys(): IntArray = keysToIntArray().also { it.sort() } /** The map's keys as a fresh ascending array. */ fun LongKeyed.sortedKeys(): LongArray = keysToLongArray().also { it.sort() } - -/** Power-of-two capacity, at least 8, for [entries] at a maximum load factor of one half. */ -fun hashTableCapacity(entries: Int): Int { - require(entries in 0..(1 shl 29)) { "Entry count exceeds the supported table range" } - return openAddressingCapacity(entries) -} diff --git a/src/commonMain/kotlin/com/eignex/util/collections/DynamicBits.kt b/src/commonMain/kotlin/com/eignex/util/collections/DynamicBits.kt index 4e8dba7..146a3d6 100644 --- a/src/commonMain/kotlin/com/eignex/util/collections/DynamicBits.kt +++ b/src/commonMain/kotlin/com/eignex/util/collections/DynamicBits.kt @@ -1,8 +1,11 @@ package com.eignex.util.collections import com.eignex.util.collections.internals.bitWordCount +import com.eignex.util.collections.internals.clearPackedBit import com.eignex.util.collections.internals.fillBitRange import com.eignex.util.collections.internals.forEachSetBit +import com.eignex.util.collections.internals.getPackedBit +import com.eignex.util.collections.internals.setPackedBit /** * Growable packed bits, initially empty with storage for [initialCapacity] bits. @@ -19,26 +22,26 @@ class DynamicBits(initialCapacity: Int = 0) : BitSet { override operator fun get(i: Int): Boolean { if (i !in 0 until size) throw IndexOutOfBoundsException("Bit index $i outside 0 until $size") - return Bits.has(words, i) + return getPackedBit(words, i) } override fun set(i: Int) { require(i >= 0 && i < Int.MAX_VALUE) { "Bit index must be in 0 until Int.MAX_VALUE" } if (i >= size) resize(i + 1) - Bits.set(words, i) + setPackedBit(words, i) } /** Assign [value], extending [size] through [i] even when [value] is false. */ override operator fun set(i: Int, value: Boolean) { require(i >= 0 && i < Int.MAX_VALUE) { "Bit index must be in 0 until Int.MAX_VALUE" } if (i >= size) resize(i + 1) - if (value) Bits.set(words, i) else Bits.clear(words, i) + if (value) setPackedBit(words, i) else clearPackedBit(words, i) } /** Clear a non-negative [i]; indices beyond [size] have no effect and do not grow storage. */ override fun clear(i: Int) { require(i >= 0) { "Bit index must be non-negative" } - if (i < size) Bits.clear(words, i) + if (i < size) clearPackedBit(words, i) } override fun clear() { @@ -62,7 +65,7 @@ class DynamicBits(initialCapacity: Int = 0) : BitSet { /** Append [value]. */ fun add(value: Boolean) { val index = reserve(1) - if (value) Bits.set(words, index) + if (value) setPackedBit(words, index) } /** Append [count] false bits and return their first index; zero leaves [size] unchanged. */ diff --git a/src/commonMain/kotlin/com/eignex/util/collections/IntArrayDeque.kt b/src/commonMain/kotlin/com/eignex/util/collections/IntArrayDeque.kt index 421cabf..5d8ddcd 100644 --- a/src/commonMain/kotlin/com/eignex/util/collections/IntArrayDeque.kt +++ b/src/commonMain/kotlin/com/eignex/util/collections/IntArrayDeque.kt @@ -9,11 +9,11 @@ class IntArrayDeque(initialCapacity: Int = 8) : IntIndexedCollection { private var buf: IntArray = IntArray(nextPow2(maxOf(initialCapacity, 1))) - /** Bytes in the backing primitive array, excluding its object header. */ - val allocatedBytes: Long get() = buf.size.toLong() * Int.SIZE_BYTES private var head: Int = 0 private var count: Int = 0 + internal val primitiveCapacityBytesInternal: Long get() = buf.size.toLong() * Int.SIZE_BYTES + override val size: Int get() = count override fun isEmpty(): Boolean = count == 0 diff --git a/src/commonMain/kotlin/com/eignex/util/collections/IntArrayList.kt b/src/commonMain/kotlin/com/eignex/util/collections/IntArrayList.kt index 4b28fa7..640f616 100644 --- a/src/commonMain/kotlin/com/eignex/util/collections/IntArrayList.kt +++ b/src/commonMain/kotlin/com/eignex/util/collections/IntArrayList.kt @@ -9,6 +9,8 @@ import com.eignex.util.arrays.lowerBoundInt class IntArrayList(initialCapacity: Int = 8) : IntIndexedCollection { private var data: IntArray = IntArray(initialCapacity.coerceAtLeast(1)) + internal val primitiveCapacityBytesInternal: Long get() = data.size.toLong() * Int.SIZE_BYTES + override var size: Int = 0 private set @@ -59,13 +61,13 @@ class IntArrayList(initialCapacity: Int = 8) : IntIndexedCollection { * Swap-remove the element at [index] (O(1); does not preserve order). * @throws IndexOutOfBoundsException when [index] is outside the live elements. */ - fun removeAt(index: Int) { + fun removeAtSwap(index: Int) { if (index < 0 || index >= size) throw IndexOutOfBoundsException("Index $index, size $size") data[index] = data[--size] } /** Swap-remove the first occurrence of [value], returning true if found. Does not preserve order. */ - fun removeValue(value: Int): Boolean { + fun removeValueSwap(value: Int): Boolean { val d = data val n = size for (i in 0 until n) { @@ -150,7 +152,7 @@ class IntArrayList(initialCapacity: Int = 8) : IntIndexedCollection { /** Sort by integer [key] without boxing; ties use the element's unsigned bits. * [descending] reverses the result. */ inline fun sortByIntKey(descending: Boolean = false, key: (Int) -> Int) { - val d = backingData + val d = backingDataInternal val n = size val packed = LongArray(n) { (key(d[it]).toLong() shl 32) or (d[it].toLong() and 0xFFFFFFFFL) } packed.sort() @@ -161,9 +163,5 @@ class IntArrayList(initialCapacity: Int = 8) : IntIndexedCollection { } } - /** - * Borrow the backing array without copying; only `0 until size` contains live elements. - * Writes to live elements update this list. Growth and [trim] can replace this array. - */ - val backingData: IntArray get() = data + @PublishedApi internal val backingDataInternal: IntArray get() = data } diff --git a/src/commonMain/kotlin/com/eignex/util/collections/IntHashSet.kt b/src/commonMain/kotlin/com/eignex/util/collections/IntHashSet.kt index c774d64..cb9339b 100644 --- a/src/commonMain/kotlin/com/eignex/util/collections/IntHashSet.kt +++ b/src/commonMain/kotlin/com/eignex/util/collections/IntHashSet.kt @@ -7,8 +7,8 @@ import com.eignex.util.collections.internals.forEachIntKey import com.eignex.util.collections.internals.growIntKeyTable import com.eignex.util.collections.internals.intKeySlot import com.eignex.util.collections.internals.intKeysToArray -import com.eignex.util.collections.internals.mixIntKey import com.eignex.util.collections.internals.openAddressingCapacity +import com.eignex.util.hash.fibonacciHash /** * Primitive open-addressing Int set with linear probing, power-of-two capacity and @@ -23,9 +23,11 @@ class IntHashSet(initialCapacity: Int = 8) : MutableIntSet { private var mask: Int = 0 private val initialCap = openAddressingCapacity(initialCapacity) - /** Bytes in allocated primitive arrays, excluding object headers and shared empty storage. */ - val allocatedBytes: Long - get() = if (used === EmptyIntKeyTable.used) 0L else keys.size.toLong() * (Int.SIZE_BYTES + 1L) + internal val primitiveCapacityBytesInternal: Long + get() { + if (used === EmptyIntKeyTable.used) return 0L + return keys.size.toLong() * (Int.SIZE_BYTES + 1L) + } override var size: Int = 0 private set @@ -79,16 +81,6 @@ class IntHashSet(initialCapacity: Int = 8) : MutableIntSet { for (i in u.indices) if (u[i]) action(k[i]) } - /** - * Visit each allocated table slot, including unused slots, in table order. - * The key is meaningful only when the first argument is true. Mutation is unsupported. - */ - inline fun forEachSlot(action: (occupied: Boolean, key: Int) -> Unit) { - val keys = keysInternal - val used = usedInternal - for (i in used.indices) action(used[i], keys[i]) - } - override fun forEach(action: IntConsumer) = forEachIntKey(keys, used, action) @PublishedApi internal val keysInternal: IntArray get() = keys @@ -103,5 +95,5 @@ class IntHashSet(initialCapacity: Int = 8) : MutableIntSet { }) } - private fun mix(x: Int): Int = mixIntKey(x) + private fun mix(x: Int): Int = fibonacciHash(x) } diff --git a/src/commonMain/kotlin/com/eignex/util/collections/IntIntMap.kt b/src/commonMain/kotlin/com/eignex/util/collections/IntIntMap.kt index 03185f0..a22390b 100644 --- a/src/commonMain/kotlin/com/eignex/util/collections/IntIntMap.kt +++ b/src/commonMain/kotlin/com/eignex/util/collections/IntIntMap.kt @@ -1,9 +1,9 @@ package com.eignex.util.collections -import com.eignex.util.collections.internals.EmptyBooleanArray -import com.eignex.util.collections.internals.EmptyIntArray -import com.eignex.util.collections.internals.mixIntKey +import com.eignex.util.arrays.emptyBooleanArray +import com.eignex.util.arrays.emptyIntArray import com.eignex.util.collections.internals.openAddressingCapacity +import com.eignex.util.hash.fibonacciHash /** * Read-only primitive Int-to-Int map. [build] selects a dense offset array or sparse @@ -35,7 +35,7 @@ class IntIntMap private constructor( return index >= 0L && index < present.size && present[index.toInt()] } val mask = keys.size - 1 - var index = mixIntKey(key) and mask + var index = fibonacciHash(key) and mask while (present[index]) { if (keys[index] == key) return true index = (index + 1) and mask @@ -49,7 +49,7 @@ class IntIntMap private constructor( return if (index >= 0L && index < values.size && present[index.toInt()]) values[index.toInt()] else default } val mask = keys.size - 1 - var index = mixIntKey(key) and mask + var index = fibonacciHash(key) and mask while (present[index]) { if (keys[index] == key) return values[index] index = (index + 1) and mask @@ -65,7 +65,7 @@ class IntIntMap private constructor( */ fun build(keys: IntArray, values: IntArray, absent: Int = 0, denseThreshold: Int = 4): IntIntMap { require(keys.size == values.size) { "keys/values length mismatch" } - if (keys.isEmpty()) return IntIntMap(0, EmptyIntArray, EmptyIntArray, EmptyBooleanArray, absent, 0) + if (keys.isEmpty()) return IntIntMap(0, emptyIntArray(), emptyIntArray(), emptyBooleanArray(), absent, 0) var lo = keys[0] var hi = keys[0] for (k in keys) { @@ -84,7 +84,7 @@ class IntIntMap private constructor( if (present[index]) size-- present[index] = true } - IntIntMap(lo, EmptyIntArray, arr, present, absent, size) + IntIntMap(lo, emptyIntArray(), arr, present, absent, size) } else { buildSparse(keys, values, absent) } @@ -98,7 +98,7 @@ class IntIntMap private constructor( val mask = capacity - 1 var size = keys.size for (i in keys.indices) { - var index = mixIntKey(keys[i]) and mask + var index = fibonacciHash(keys[i]) and mask while (present[index]) { if (storedKeys[index] == keys[i]) { size-- diff --git a/src/commonMain/kotlin/com/eignex/util/collections/IntLongMap.kt b/src/commonMain/kotlin/com/eignex/util/collections/IntLongMap.kt index 3425009..19088d0 100644 --- a/src/commonMain/kotlin/com/eignex/util/collections/IntLongMap.kt +++ b/src/commonMain/kotlin/com/eignex/util/collections/IntLongMap.kt @@ -1,7 +1,7 @@ package com.eignex.util.collections -import com.eignex.util.collections.internals.mixIntKey import com.eignex.util.collections.internals.openAddressingCapacity +import com.eignex.util.hash.fibonacciHash /** * Read-only primitive Int-to-Long map with the dense/sparse backing choice of [IntIntMap]. @@ -103,7 +103,7 @@ class IntLongMap private constructor(private val backing: Backing, private val a override fun contains(key: Int): Boolean { val mask = keys.size - 1 - var index = mixIntKey(key) and mask + var index = fibonacciHash(key) and mask while (present[index]) { if (keys[index] == key) return true index = (index + 1) and mask @@ -113,7 +113,7 @@ class IntLongMap private constructor(private val backing: Backing, private val a override fun get(key: Int, absent: Long): Long { val mask = keys.size - 1 - var i = mixIntKey(key) and mask + var i = fibonacciHash(key) and mask while (present[i]) { if (keys[i] == key) return values[i] i = (i + 1) and mask @@ -130,7 +130,7 @@ class IntLongMap private constructor(private val backing: Backing, private val a val mask = cap - 1 var size = keys.size for (i in keys.indices) { - var idx = mixIntKey(keys[i]) and mask + var idx = fibonacciHash(keys[i]) and mask while (p[idx]) { if (k[idx] == keys[i]) { size-- diff --git a/src/commonMain/kotlin/com/eignex/util/collections/IntSwapSet.kt b/src/commonMain/kotlin/com/eignex/util/collections/IntSwapSet.kt index 71cb4e6..c371aa3 100644 --- a/src/commonMain/kotlin/com/eignex/util/collections/IntSwapSet.kt +++ b/src/commonMain/kotlin/com/eignex/util/collections/IntSwapSet.kt @@ -7,33 +7,12 @@ import kotlin.random.Random * Backed by a list of present elements and a parallel index map keyed by element id. * Element ids must be in `0 until capacity`. */ -class IntSwapSet private constructor(private val elements: IntArrayList, private val position: IntArray) : +class IntSwapSet internal constructor(private val elements: IntArrayList, private val position: IntArray) : MutableIntSet, IntIndexedCollection { /** Create an empty set for ids in `0 until capacity`. */ constructor(capacity: Int) : this(IntArrayList(capacity.coerceAtLeast(8)), IntArray(capacity) { -1 }) - /** Cooperative construction of a dense membership index. */ - companion object { - /** - * Allocate an empty set, yielding null between allocation and initialization steps. - * Initialization visits at most [batch] positions per step; the final value is the set. - * [capacity] must be non-negative and [batch] positive. - */ - fun preparation(capacity: Int, batch: Int): Sequence = sequence { - require(capacity >= 0 && batch > 0) - val elements = IntArrayList(capacity.coerceAtLeast(8)) - yield(null) - val position = IntArray(capacity) - yield(null) - for (from in 0 until capacity step batch) { - position.fill(-1, from, minOf(from + batch, capacity)) - yield(null) - } - yield(IntSwapSet(elements, position)) - } - } - override val size: Int get() = elements.size override fun isEmpty(): Boolean = elements.size == 0 @@ -55,7 +34,7 @@ class IntSwapSet private constructor(private val elements: IntArrayList, private val last = elements[elements.size - 1] elements[pos] = last position[last] = pos - elements.removeAt(elements.size - 1) + elements.removeAtSwap(elements.size - 1) position[value] = -1 return true } diff --git a/src/commonMain/kotlin/com/eignex/util/collections/LongArrayList.kt b/src/commonMain/kotlin/com/eignex/util/collections/LongArrayList.kt index 2536386..2c89298 100644 --- a/src/commonMain/kotlin/com/eignex/util/collections/LongArrayList.kt +++ b/src/commonMain/kotlin/com/eignex/util/collections/LongArrayList.kt @@ -3,18 +3,17 @@ package com.eignex.util.collections import com.eignex.util.arrays.binarySearchLong /** - * Primitive growable Long list backed by a doubling [LongArray]. [removeAt] and - * [removeValue] swap-remove without preserving order. Not thread-safe. + * Primitive growable Long list backed by a doubling [LongArray]. [removeAtSwap] and + * [removeValueSwap] swap-remove without preserving order. Not thread-safe. */ class LongArrayList(initialCapacity: Int = 8) : LongIndexedCollection { private var data: LongArray = LongArray(initialCapacity.coerceAtLeast(1)) + internal val primitiveCapacityBytesInternal: Long get() = data.size.toLong() * Long.SIZE_BYTES + override var size: Int = 0 private set - /** Bytes in the backing primitive array, excluding its object header. */ - val allocatedBytes: Long get() = data.size.toLong() * Long.SIZE_BYTES - /** Append [value], growing the backing array when needed. */ fun add(value: Long) { if (size == data.size) data = data.copyOf(data.size * 2) @@ -54,13 +53,13 @@ class LongArrayList(initialCapacity: Int = 8) : LongIndexedCollection { * Swap-remove the element at [index] (O(1); does not preserve order). * @throws IndexOutOfBoundsException when [index] is outside the live elements. */ - fun removeAt(index: Int) { + fun removeAtSwap(index: Int) { if (index < 0 || index >= size) throw IndexOutOfBoundsException("Index $index, size $size") data[index] = data[--size] } /** Find the first occurrence of [value] and swap-remove it; returns true if found. */ - fun removeValue(value: Long): Boolean { + fun removeValueSwap(value: Long): Boolean { val d = data val n = size for (i in 0 until n) { @@ -148,4 +147,6 @@ class LongArrayList(initialCapacity: Int = 8) : LongIndexedCollection { inline fun forEach(action: (Long) -> Unit) { for (i in 0 until size) action(this[i]) } + + internal val backingDataInternal: LongArray get() = data } diff --git a/src/commonMain/kotlin/com/eignex/util/collections/LongHashSet.kt b/src/commonMain/kotlin/com/eignex/util/collections/LongHashSet.kt index 492160c..97e155a 100644 --- a/src/commonMain/kotlin/com/eignex/util/collections/LongHashSet.kt +++ b/src/commonMain/kotlin/com/eignex/util/collections/LongHashSet.kt @@ -7,8 +7,8 @@ import com.eignex.util.collections.internals.forEachLongKey import com.eignex.util.collections.internals.growLongKeyTable import com.eignex.util.collections.internals.longKeySlot import com.eignex.util.collections.internals.longKeysToArray -import com.eignex.util.collections.internals.mixLongKey import com.eignex.util.collections.internals.openAddressingCapacity +import com.eignex.util.hash.fibonacciHash /** * Primitive open-addressing Long set with linear probing and load factor at most 0.5. @@ -22,9 +22,11 @@ class LongHashSet(initialCapacity: Int = 8) : MutableLongSet { private var mask: Int = 0 private val initialCap = openAddressingCapacity(initialCapacity) - /** Bytes in allocated primitive arrays, excluding object headers and shared empty storage. */ - val allocatedBytes: Long - get() = if (used === EmptyLongKeyTable.used) 0L else keys.size.toLong() * (Long.SIZE_BYTES + 1L) + internal val primitiveCapacityBytesInternal: Long + get() { + if (used === EmptyLongKeyTable.used) return 0L + return keys.size.toLong() * (Long.SIZE_BYTES + 1L) + } override var size: Int = 0 private set @@ -38,25 +40,6 @@ class LongHashSet(initialCapacity: Int = 8) : MutableLongSet { return false } - /** - * Query membership within [maxWork] slot visits, invoking [charge] for each visit. - * Return null on exhaustion or [cancelled]. No mutation occurs. - */ - fun containsBounded(value: Long, maxWork: Long, cancelled: () -> Boolean, charge: () -> Unit): Boolean? { - require(maxWork >= 0L) - var work = 0L - var slot = mixLongKey(value) and mask - while (true) { - if (work >= maxWork || cancelled()) return null - charge() - work++ - if (cancelled()) return null - if (!used[slot]) return false - if (keys[slot] == value) return true - slot = (slot + 1) and mask - } - } - override fun add(value: Long): Boolean { if (used === EmptyLongKeyTable.used) { keys = LongArray(initialCap) @@ -71,81 +54,6 @@ class LongHashSet(initialCapacity: Int = 8) : MutableLongSet { return true } - /** - * Add within byte, work and scratch limits, charging each work unit through [charge]. - * Return true for insertion, false for an existing value, or null on exhaustion or cancellation. - * An incomplete attempt preserves membership and the published backing arrays. - */ - fun tryAddBounded( - value: Long, - maxBytes: Long, - maxWork: Long, - maxScratchBytes: Long, - cancelled: () -> Boolean, - charge: () -> Unit, - ): Boolean? { - require(maxBytes >= 0L && maxWork >= 0L && maxScratchBytes >= 0L) - var work = 0L - fun step(): Boolean { - if (work >= maxWork || cancelled()) return false - charge() - work++ - return !cancelled() - } - var slot = mixLongKey(value) and mask - while (true) { - if (!step()) return null - if (!used[slot]) break - if (keys[slot] == value) return false - slot = (slot + 1) and mask - } - val capacity = when { - used === EmptyLongKeyTable.used -> initialCap - (size + 1L) * 2L > keys.size -> if (keys.size <= Int.MAX_VALUE / 2) keys.size * 2 else return null - else -> keys.size - } - if (capacity.toLong() * 9L > maxBytes) return null - if (capacity == keys.size && used !== EmptyLongKeyTable.used) { - if (!step()) return null - used[slot] = true - keys[slot] = value - size++ - return true - } - if (capacity.toLong() * 9L > maxScratchBytes || capacity.toLong() * 2L > maxWork - work) return null - repeat(capacity) { if (!step() || !step()) return null } - if (!step()) return null - val nextKeys = LongArray(capacity) - val nextUsed = BooleanArray(capacity) - val nextMask = capacity - 1 - for (index in used.indices) { - if (!step()) return null - if (!used[index]) continue - var target = mixLongKey(keys[index]) and nextMask - while (true) { - if (!step()) return null - if (!nextUsed[target]) break - target = (target + 1) and nextMask - } - nextKeys[target] = keys[index] - nextUsed[target] = true - } - slot = mixLongKey(value) and nextMask - while (true) { - if (!step()) return null - if (!nextUsed[slot]) break - slot = (slot + 1) and nextMask - } - nextKeys[slot] = value - nextUsed[slot] = true - if (!step()) return null - keys = nextKeys - used = nextUsed - mask = nextMask - size++ - return true - } - override fun remove(value: Long): Boolean { findLongKey(keys, used, mask, value) { slot -> deleteLongKeySlot(keys, used, mask, slot, { _, _ -> }, {}) @@ -192,6 +100,21 @@ class LongHashSet(initialCapacity: Int = 8) : MutableLongSet { @PublishedApi internal val usedInternal: BooleanArray get() = used + internal val initialCapacityInternal: Int get() = initialCap + + internal fun insertAtSlot(slot: Int, value: Long) { + used[slot] = true + keys[slot] = value + size++ + } + + internal fun publishInsertion(nextKeys: LongArray, nextUsed: BooleanArray, nextMask: Int) { + keys = nextKeys + used = nextUsed + mask = nextMask + size++ + } + private fun grow() { growLongKeyTable(keys, used, {}, { _, _ -> }, { nextKeys, nextUsed, nextMask -> keys = nextKeys @@ -200,5 +123,5 @@ class LongHashSet(initialCapacity: Int = 8) : MutableLongSet { }) } - private fun mix(x: Long): Int = mixLongKey(x) + private fun mix(x: Long): Int = fibonacciHash(x) } diff --git a/src/commonMain/kotlin/com/eignex/util/collections/MapOperations.kt b/src/commonMain/kotlin/com/eignex/util/collections/MapOperations.kt new file mode 100644 index 0000000..0939804 --- /dev/null +++ b/src/commonMain/kotlin/com/eignex/util/collections/MapOperations.kt @@ -0,0 +1,26 @@ +package com.eignex.util.collections + +/** + * Remove every entry whose key exceeds [threshold]. Keys are collected before any removal, since + * backward-shift deletion moves entries that an in-place iteration would then skip. + */ +fun MutableIntObjectMap.removeKeysAbove(threshold: Int) { + val doomed = IntArrayList() + forEach { key, _ -> if (key > threshold) doomed.add(key) } + doomed.forEach { remove(it) } +} + +/** Value stored under the greatest key, or null when the map is empty. */ +fun MutableIntObjectMap.valueAtMaxKey(): V? { + var bestKey = Int.MIN_VALUE + var best: V? = null + var found = false + forEach { key, value -> + if (!found || key >= bestKey) { + found = true + bestKey = key + best = value + } + } + return best +} diff --git a/src/commonMain/kotlin/com/eignex/util/collections/MutableIntDoubleMap.kt b/src/commonMain/kotlin/com/eignex/util/collections/MutableIntDoubleMap.kt index 26031e4..5165c6c 100644 --- a/src/commonMain/kotlin/com/eignex/util/collections/MutableIntDoubleMap.kt +++ b/src/commonMain/kotlin/com/eignex/util/collections/MutableIntDoubleMap.kt @@ -19,6 +19,8 @@ class MutableIntDoubleMap(initialCapacity: Int = 8) : IntKeyed { private var used: BooleanArray private var mask: Int + internal val primitiveCapacityBytesInternal: Long get() = keys.size.toLong() * 13L + override var size: Int = 0 private set diff --git a/src/commonMain/kotlin/com/eignex/util/collections/MutableIntIntMap.kt b/src/commonMain/kotlin/com/eignex/util/collections/MutableIntIntMap.kt index c0b17a8..33af174 100644 --- a/src/commonMain/kotlin/com/eignex/util/collections/MutableIntIntMap.kt +++ b/src/commonMain/kotlin/com/eignex/util/collections/MutableIntIntMap.kt @@ -19,7 +19,7 @@ class MutableIntIntMap(initialCapacity: Int = 8) : IntIntLookup { private var used: BooleanArray private var mask: Int - internal val primitiveCapacityBytes: Long get() = keys.size.toLong() * 9L + internal val primitiveCapacityBytesInternal: Long get() = keys.size.toLong() * 9L override var size: Int = 0 private set diff --git a/src/commonMain/kotlin/com/eignex/util/collections/MutableIntLongMap.kt b/src/commonMain/kotlin/com/eignex/util/collections/MutableIntLongMap.kt index 42839b7..0198f89 100644 --- a/src/commonMain/kotlin/com/eignex/util/collections/MutableIntLongMap.kt +++ b/src/commonMain/kotlin/com/eignex/util/collections/MutableIntLongMap.kt @@ -19,6 +19,8 @@ class MutableIntLongMap(initialCapacity: Int = 8) : IntLongLookup { private var used: BooleanArray private var mask: Int + internal val primitiveCapacityBytesInternal: Long get() = keys.size.toLong() * 13L + override var size: Int = 0 private set diff --git a/src/commonMain/kotlin/com/eignex/util/collections/MutableIntObjectMap.kt b/src/commonMain/kotlin/com/eignex/util/collections/MutableIntObjectMap.kt index 0313b8d..bfe4f2a 100644 --- a/src/commonMain/kotlin/com/eignex/util/collections/MutableIntObjectMap.kt +++ b/src/commonMain/kotlin/com/eignex/util/collections/MutableIntObjectMap.kt @@ -19,11 +19,7 @@ class MutableIntObjectMap(initialCapacity: Int = 8) : IntKeyed { private var used: BooleanArray private var mask: Int - /** Bytes in the key and occupancy arrays, excluding object headers. */ - val primitiveCapacityBytes: Long get() = keys.size.toLong() * 5L - - /** Number of slots in the value array, including unused slots. */ - val referenceCapacity: Int get() = values.size + internal val primitiveCapacityBytesInternal: Long get() = keys.size.toLong() * 5L override var size: Int = 0 private set @@ -91,31 +87,6 @@ class MutableIntObjectMap(initialCapacity: Int = 8) : IntKeyed { /** Whether there are no live elements. */ fun isEmpty(): Boolean = size == 0 - /** - * Remove every entry whose key exceeds [threshold]. Keys are collected before any removal, since - * backward-shift deletion moves entries that an in-place iteration would then skip. - */ - fun removeKeysAbove(threshold: Int) { - val doomed = IntArrayList() - forEach { key, _ -> if (key > threshold) doomed.add(key) } - doomed.forEach { remove(it) } - } - - /** Value stored under the greatest key, or null when the map is empty. */ - fun valueAtMaxKey(): V? { - var bestKey = Int.MIN_VALUE - var best: V? = null - var found = false - forEach { key, value -> - if (!found || key >= bestKey) { - found = true - bestKey = key - best = value - } - } - return best - } - /** Remove all live elements while retaining the allocated storage. */ fun clear() { if (size == 0) return @@ -137,15 +108,6 @@ class MutableIntObjectMap(initialCapacity: Int = 8) : IntKeyed { override fun keysToIntArray(): IntArray = intKeysToArray(keys, used, size) - /** Identity of the current value array for ownership accounting; growth replaces it. */ - val valueStorageIdentity: Any get() = values - - /** Visit every value slot, including nulls in unused slots. Mutation is unsupported. */ - @Suppress("UNCHECKED_CAST") - inline fun forEachValueSlot(action: (V?) -> Unit) { - for (value in valuesInternal) action(value as V?) - } - @PublishedApi internal val keysInternal: IntArray get() = keys @PublishedApi internal val valuesInternal: Array get() = values diff --git a/src/commonMain/kotlin/com/eignex/util/collections/MutableLongIntMap.kt b/src/commonMain/kotlin/com/eignex/util/collections/MutableLongIntMap.kt index 6e857f5..6723126 100644 --- a/src/commonMain/kotlin/com/eignex/util/collections/MutableLongIntMap.kt +++ b/src/commonMain/kotlin/com/eignex/util/collections/MutableLongIntMap.kt @@ -6,8 +6,6 @@ import com.eignex.util.collections.internals.forEachLongKey import com.eignex.util.collections.internals.growLongKeyTable import com.eignex.util.collections.internals.longKeySlot import com.eignex.util.collections.internals.longKeysToArray -import com.eignex.util.collections.internals.mixLongKey -import com.eignex.util.collections.internals.mustStayDuringShift import com.eignex.util.collections.internals.openAddressingCapacity /** @@ -21,8 +19,7 @@ class MutableLongIntMap(initialCapacity: Int = 8) : LongKeyed { private var used: BooleanArray private var mask: Int - /** Bytes in the primitive backing arrays, excluding object headers. */ - val primitiveCapacityBytes: Long get() = keys.size.toLong() * 13L + internal val primitiveCapacityBytesInternal: Long get() = keys.size.toLong() * 13L override var size: Int = 0 private set @@ -97,62 +94,6 @@ class MutableLongIntMap(initialCapacity: Int = 8) : LongKeyed { return false } - /** - * Remove [key] and update an existing [updateKey] as one funded mutation. - * [fund] charges preparation before [ready] runs; neither callback may mutate this map. - * A missing non-null [updateKey] returns false without mutation or calling [ready]. - * [key] and [updateKey] must differ. A null [updateKey] performs removal only. - */ - fun removeAndUpdate( - key: Long, - updateKey: Long?, - updateValue: Int, - fund: (Long) -> Unit, - ready: () -> Unit, - ): Boolean { - require(key != updateKey) - val removed = fundedSlot(key, fund) - val updated = updateKey?.let { fundedSlot(it, fund) } ?: -1 - if (updateKey != null && updated < 0) return false - val destination = if (removed >= 0) removalDestination(removed, updated, fund) else updated - fund(4L) - ready() - if (removed >= 0) { - deleteSlot(removed) - size-- - } - if (updateKey != null) values[destination] = updateValue - return true - } - - private fun fundedSlot(key: Long, fund: (Long) -> Unit): Int { - fund(1L) - var index = mixLongKey(key) and mask - while (true) { - fund(4L) - if (!used[index]) return -1 - if (keys[index] == key) return index - index = (index + 1) and mask - } - } - - private fun removalDestination(start: Int, updated: Int, fund: (Long) -> Unit): Int { - var hole = start - var cursor = start - var destination = updated - while (true) { - // Fund the probe and its matching backward-shift publication before either mapping changes. - fund(16L) - cursor = (cursor + 1) and mask - if (!used[cursor]) return destination - val home = mixLongKey(keys[cursor]) and mask - if (!mustStayDuringShift(home, hole, cursor)) { - if (cursor == updated) destination = hole - hole = cursor - } - } - } - /** Whether there are no live elements. */ fun isEmpty(): Boolean = size == 0 @@ -180,6 +121,14 @@ class MutableLongIntMap(initialCapacity: Int = 8) : LongKeyed { @PublishedApi internal val usedInternal: BooleanArray get() = used + internal fun commitRemovalAndUpdate(removed: Int, destination: Int, value: Int) { + if (removed >= 0) { + deleteSlot(removed) + size-- + } + if (destination >= 0) values[destination] = value + } + private fun deleteSlot(start: Int) { deleteLongKeySlot(keys, used, mask, start, { from, to -> values[to] = values[from] }, {}) } diff --git a/src/commonMain/kotlin/com/eignex/util/collections/MutableLongObjectMap.kt b/src/commonMain/kotlin/com/eignex/util/collections/MutableLongObjectMap.kt index 931d222..d84f652 100644 --- a/src/commonMain/kotlin/com/eignex/util/collections/MutableLongObjectMap.kt +++ b/src/commonMain/kotlin/com/eignex/util/collections/MutableLongObjectMap.kt @@ -19,6 +19,8 @@ class MutableLongObjectMap(initialCapacity: Int = 8) : LongKeyed { private var used: BooleanArray private var mask: Int + internal val primitiveCapacityBytesInternal: Long get() = keys.size.toLong() * 9L + override var size: Int = 0 private set diff --git a/src/commonMain/kotlin/com/eignex/util/collections/cooperative/BoundedLongHashSet.kt b/src/commonMain/kotlin/com/eignex/util/collections/cooperative/BoundedLongHashSet.kt new file mode 100644 index 0000000..664daf3 --- /dev/null +++ b/src/commonMain/kotlin/com/eignex/util/collections/cooperative/BoundedLongHashSet.kt @@ -0,0 +1,101 @@ +package com.eignex.util.collections.cooperative + +import com.eignex.util.collections.LongHashSet +import com.eignex.util.collections.internals.EmptyLongKeyTable +import com.eignex.util.hash.fibonacciHash + +/** + * Query membership within [maxWork] slot visits, invoking [charge] for each visit. + * Return null on exhaustion or [cancelled]. No mutation occurs. Callbacks must not mutate this set. + */ +fun LongHashSet.containsBounded(value: Long, maxWork: Long, cancelled: () -> Boolean, charge: () -> Unit): Boolean? { + val keys = keysInternal + val used = usedInternal + val mask = keys.size - 1 + require(maxWork >= 0L) + var work = 0L + var slot = fibonacciHash(value) and mask + while (true) { + if (work >= maxWork || cancelled()) return null + charge() + work++ + if (cancelled()) return null + if (!used[slot]) return false + if (keys[slot] == value) return true + slot = (slot + 1) and mask + } +} + +/** + * Add within byte, work and scratch limits, charging each work unit through [charge]. + * Return true for insertion, false for an existing value, or null on exhaustion or cancellation. + * An incomplete attempt preserves membership and the published backing arrays. + * Callbacks must not mutate this set. + */ +fun LongHashSet.tryAddBounded( + value: Long, + maxBytes: Long, + maxWork: Long, + maxScratchBytes: Long, + cancelled: () -> Boolean, + charge: () -> Unit, +): Boolean? { + val keys = keysInternal + val used = usedInternal + val mask = keys.size - 1 + require(maxBytes >= 0L && maxWork >= 0L && maxScratchBytes >= 0L) + var work = 0L + fun step(): Boolean { + if (work >= maxWork || cancelled()) return false + charge() + work++ + return !cancelled() + } + var slot = fibonacciHash(value) and mask + while (true) { + if (!step()) return null + if (!used[slot]) break + if (keys[slot] == value) return false + slot = (slot + 1) and mask + } + val capacity = when { + used === EmptyLongKeyTable.used -> initialCapacityInternal + (size + 1L) * 2L > keys.size -> if (keys.size <= Int.MAX_VALUE / 2) keys.size * 2 else return null + else -> keys.size + } + if (capacity.toLong() * 9L > maxBytes) return null + if (capacity == keys.size && used !== EmptyLongKeyTable.used) { + if (!step()) return null + insertAtSlot(slot, value) + return true + } + if (capacity.toLong() * 9L > maxScratchBytes || capacity.toLong() * 2L > maxWork - work) return null + repeat(capacity) { if (!step() || !step()) return null } + if (!step()) return null + val nextKeys = LongArray(capacity) + val nextUsed = BooleanArray(capacity) + val nextMask = capacity - 1 + for (index in used.indices) { + if (!step()) return null + if (!used[index]) continue + var target = fibonacciHash(keys[index]) and nextMask + while (true) { + if (!step()) return null + if (!nextUsed[target]) break + target = (target + 1) and nextMask + } + nextKeys[target] = keys[index] + nextUsed[target] = true + } + slot = fibonacciHash(value) and nextMask + while (true) { + if (!step()) return null + if (!nextUsed[slot]) break + slot = (slot + 1) and nextMask + } + nextKeys[slot] = value + nextUsed[slot] = true + if (!step()) return null + publishInsertion(nextKeys, nextUsed, nextMask) + return true +} diff --git a/src/commonMain/kotlin/com/eignex/util/collections/cooperative/FundedMapUpdates.kt b/src/commonMain/kotlin/com/eignex/util/collections/cooperative/FundedMapUpdates.kt new file mode 100644 index 0000000..573d6e6 --- /dev/null +++ b/src/commonMain/kotlin/com/eignex/util/collections/cooperative/FundedMapUpdates.kt @@ -0,0 +1,63 @@ +package com.eignex.util.collections.cooperative + +import com.eignex.util.collections.MutableLongIntMap +import com.eignex.util.collections.internals.mustStayDuringShift +import com.eignex.util.hash.fibonacciHash + +/** + * Remove [key] and update an existing [updateKey] as one funded mutation. + * [fund] charges preparation before [ready] runs; neither callback may mutate this map. + * A missing non-null [updateKey] returns false without mutation or calling [ready]. + * [key] and [updateKey] must differ. A null [updateKey] performs removal only. + */ +fun MutableLongIntMap.removeAndUpdate( + key: Long, + updateKey: Long?, + updateValue: Int, + fund: (Long) -> Unit, + ready: () -> Unit, +): Boolean { + require(key != updateKey) + val removed = fundedSlot(key, fund) + val updated = updateKey?.let { fundedSlot(it, fund) } ?: -1 + if (updateKey != null && updated < 0) return false + val destination = if (removed >= 0) removalDestination(removed, updated, fund) else updated + fund(4L) + ready() + commitRemovalAndUpdate(removed, destination, updateValue) + return true +} + +private fun MutableLongIntMap.fundedSlot(key: Long, fund: (Long) -> Unit): Int { + val keys = keysInternal + val used = usedInternal + val mask = keys.size - 1 + fund(1L) + var index = fibonacciHash(key) and mask + while (true) { + fund(4L) + if (!used[index]) return -1 + if (keys[index] == key) return index + index = (index + 1) and mask + } +} + +private fun MutableLongIntMap.removalDestination(start: Int, updated: Int, fund: (Long) -> Unit): Int { + val keys = keysInternal + val used = usedInternal + val mask = keys.size - 1 + var hole = start + var cursor = start + var destination = updated + while (true) { + // Fund the probe and its matching backward-shift publication before either mapping changes. + fund(16L) + cursor = (cursor + 1) and mask + if (!used[cursor]) return destination + val home = fibonacciHash(keys[cursor]) and mask + if (!mustStayDuringShift(home, hole, cursor)) { + if (cursor == updated) destination = hole + hole = cursor + } + } +} diff --git a/src/commonMain/kotlin/com/eignex/util/collections/cooperative/PrepareIntSwapSet.kt b/src/commonMain/kotlin/com/eignex/util/collections/cooperative/PrepareIntSwapSet.kt new file mode 100644 index 0000000..f4bf5b2 --- /dev/null +++ b/src/commonMain/kotlin/com/eignex/util/collections/cooperative/PrepareIntSwapSet.kt @@ -0,0 +1,22 @@ +package com.eignex.util.collections.cooperative + +import com.eignex.util.collections.IntArrayList +import com.eignex.util.collections.IntSwapSet + +/** + * Allocate an empty set, yielding null between allocation and initialization steps. + * Initialization visits at most [batch] positions per step; the final value is the set. + * [capacity] must be non-negative and [batch] positive. + */ +fun prepareIntSwapSet(capacity: Int, batch: Int): Sequence = sequence { + require(capacity >= 0 && batch > 0) + val elements = IntArrayList(capacity.coerceAtLeast(8)) + yield(null) + val position = IntArray(capacity) + yield(null) + for (from in 0 until capacity step batch) { + position.fill(-1, from, minOf(from + batch, capacity)) + yield(null) + } + yield(IntSwapSet(elements, position)) +} diff --git a/src/commonMain/kotlin/com/eignex/util/collections/internals/BitWords.kt b/src/commonMain/kotlin/com/eignex/util/collections/internals/BitWords.kt index f19c3dc..ad79225 100644 --- a/src/commonMain/kotlin/com/eignex/util/collections/internals/BitWords.kt +++ b/src/commonMain/kotlin/com/eignex/util/collections/internals/BitWords.kt @@ -1,5 +1,16 @@ package com.eignex.util.collections.internals +internal fun getPackedBit(words: LongArray, bit: Int): Boolean = ((words[bit ushr 6] ushr (bit and 63)) and 1L) != 0L + +internal fun setPackedBit(words: LongArray, bit: Int) { + words[bit ushr 6] = words[bit ushr 6] or (1L shl (bit and 63)) +} + +internal fun clearPackedBit(words: LongArray, bit: Int) { + val word = bit ushr 6 + words[word] = words[word] and (1L shl (bit and 63)).inv() +} + internal fun bitWordCount(size: Int): Int { require(size >= 0) { "Bit size must be non-negative" } return (size ushr 6) + if (size and 63 == 0) 0 else 1 diff --git a/src/commonMain/kotlin/com/eignex/util/collections/internals/EmptyStorage.kt b/src/commonMain/kotlin/com/eignex/util/collections/internals/EmptyStorage.kt index a3d5a0f..4192842 100644 --- a/src/commonMain/kotlin/com/eignex/util/collections/internals/EmptyStorage.kt +++ b/src/commonMain/kotlin/com/eignex/util/collections/internals/EmptyStorage.kt @@ -1,13 +1,5 @@ package com.eignex.util.collections.internals -internal val EmptyIntArray: IntArray = IntArray(0) - -internal val EmptyLongArray: LongArray = LongArray(0) - -internal val EmptyBooleanArray: BooleanArray = BooleanArray(0) - -internal val EmptyDoubleArray: DoubleArray = DoubleArray(0) - internal object EmptyIntKeyTable { val keys = IntArray(1) val used = BooleanArray(1) diff --git a/src/commonMain/kotlin/com/eignex/util/collections/internals/IntKeyTable.kt b/src/commonMain/kotlin/com/eignex/util/collections/internals/IntKeyTable.kt index b29e063..a214d34 100644 --- a/src/commonMain/kotlin/com/eignex/util/collections/internals/IntKeyTable.kt +++ b/src/commonMain/kotlin/com/eignex/util/collections/internals/IntKeyTable.kt @@ -1,10 +1,11 @@ package com.eignex.util.collections.internals import com.eignex.util.collections.IntConsumer +import com.eignex.util.hash.fibonacciHash // Inline hooks preserve typed value storage without an additional table object. internal inline fun intKeySlot(keys: IntArray, used: BooleanArray, mask: Int, key: Int, existing: (Int) -> Unit): Int { - var index = mixIntKey(key) and mask + var index = fibonacciHash(key) and mask while (used[index]) { if (keys[index] == key) { existing(index) @@ -16,7 +17,7 @@ internal inline fun intKeySlot(keys: IntArray, used: BooleanArray, mask: Int, ke } internal inline fun findIntKey(keys: IntArray, used: BooleanArray, mask: Int, key: Int, found: (Int) -> Unit) { - var index = mixIntKey(key) and mask + var index = fibonacciHash(key) and mask while (used[index]) { if (keys[index] == key) { found(index) @@ -41,7 +42,7 @@ internal inline fun deleteIntKeySlot( while (true) { cursor = (cursor + 1) and mask if (!used[cursor]) return - val home = mixIntKey(keys[cursor]) and mask + val home = fibonacciHash(keys[cursor]) and mask if (mustStayDuringShift(home, hole, cursor)) continue keys[hole] = keys[cursor] move(cursor, hole) @@ -66,7 +67,7 @@ internal inline fun growIntKeyTable( publish(keys, used, mask) for (old in oldUsed.indices) { if (!oldUsed[old]) continue - var destination = mixIntKey(oldKeys[old]) and mask + var destination = fibonacciHash(oldKeys[old]) and mask while (used[destination]) destination = (destination + 1) and mask keys[destination] = oldKeys[old] used[destination] = true diff --git a/src/commonMain/kotlin/com/eignex/util/collections/internals/LongKeyTable.kt b/src/commonMain/kotlin/com/eignex/util/collections/internals/LongKeyTable.kt index 6e44ab5..10686c9 100644 --- a/src/commonMain/kotlin/com/eignex/util/collections/internals/LongKeyTable.kt +++ b/src/commonMain/kotlin/com/eignex/util/collections/internals/LongKeyTable.kt @@ -1,6 +1,7 @@ package com.eignex.util.collections.internals import com.eignex.util.collections.LongConsumer +import com.eignex.util.hash.fibonacciHash // Inline hooks preserve typed value storage without an additional table object. internal inline fun longKeySlot( @@ -10,7 +11,7 @@ internal inline fun longKeySlot( key: Long, existing: (Int) -> Unit, ): Int { - var index = mixLongKey(key) and mask + var index = fibonacciHash(key) and mask while (used[index]) { if (keys[index] == key) { existing(index) @@ -22,7 +23,7 @@ internal inline fun longKeySlot( } internal inline fun findLongKey(keys: LongArray, used: BooleanArray, mask: Int, key: Long, found: (Int) -> Unit) { - var index = mixLongKey(key) and mask + var index = fibonacciHash(key) and mask while (used[index]) { if (keys[index] == key) { found(index) @@ -47,7 +48,7 @@ internal inline fun deleteLongKeySlot( while (true) { cursor = (cursor + 1) and mask if (!used[cursor]) return - val home = mixLongKey(keys[cursor]) and mask + val home = fibonacciHash(keys[cursor]) and mask if (mustStayDuringShift(home, hole, cursor)) continue keys[hole] = keys[cursor] move(cursor, hole) @@ -72,7 +73,7 @@ internal inline fun growLongKeyTable( publish(keys, used, mask) for (old in oldUsed.indices) { if (!oldUsed[old]) continue - var destination = mixLongKey(oldKeys[old]) and mask + var destination = fibonacciHash(oldKeys[old]) and mask while (used[destination]) destination = (destination + 1) and mask keys[destination] = oldKeys[old] used[destination] = true diff --git a/src/commonMain/kotlin/com/eignex/util/collections/internals/OpenAddressing.kt b/src/commonMain/kotlin/com/eignex/util/collections/internals/OpenAddressing.kt index 69b4712..9aa9ab9 100644 --- a/src/commonMain/kotlin/com/eignex/util/collections/internals/OpenAddressing.kt +++ b/src/commonMain/kotlin/com/eignex/util/collections/internals/OpenAddressing.kt @@ -7,21 +7,6 @@ internal fun openAddressingCapacity(initialCapacity: Int): Int { return cap } -/** Fibonacci multiplication with additional mixing for power-of-two hash tables. */ -internal fun mixIntKey(x: Int): Int { - // Fold high bits before multiplying so strided keys do not retain identical low bits. - var h = (x xor (x ushr 16)) * -0x61c88647 - h = (h xor (h ushr 13)) * -0x3d4d51cb - return h xor (h ushr 16) -} - -/** Fibonacci multiplicative mixing of Long keys with a high-to-low xor fold. */ -internal fun mixLongKey(x: Long): Int { - var h = x * -0x61c8864680b583ebL // 2^64 / golden ratio, odd - h = h xor (h ushr 32) - return h.toInt() -} - /** * Whether an entry at `j` remains reachable with a hole at `i`: its home must lie * cyclically within `(i, j]`. Otherwise it must shift into the hole. diff --git a/src/commonMain/kotlin/com/eignex/util/collections/storage/BitsStorage.kt b/src/commonMain/kotlin/com/eignex/util/collections/storage/BitsStorage.kt new file mode 100644 index 0000000..d8f5ce1 --- /dev/null +++ b/src/commonMain/kotlin/com/eignex/util/collections/storage/BitsStorage.kt @@ -0,0 +1,22 @@ +package com.eignex.util.collections.storage + +import com.eignex.util.collections.Bits + +/** Number of packed 64-bit words, including a partial final word. */ +val Bits.wordCount: Int get() = words.size + +/** Packed word at [index], which must lie in `0 until wordCount`. */ +fun Bits.getWord(index: Int): Long = words[index] + +/** Replace packed word [index], clearing padding beyond [Bits.size] in the final word. */ +fun Bits.setWord(index: Int, value: Long) { + val tail = size and 63 + words[index] = if (index == words.lastIndex && tail != 0) value and (-1L ushr (64 - tail)) else value +} + +/** Copy matching word positions `[fromIndex, toIndex)` from equal-sized [other]. */ +fun Bits.copyWordsFrom(other: Bits, fromIndex: Int, toIndex: Int) { + require(size == other.size) + require(fromIndex >= 0 && fromIndex <= toIndex && toIndex <= wordCount) + other.words.copyInto(words, fromIndex, fromIndex, toIndex) +} diff --git a/src/commonMain/kotlin/com/eignex/util/collections/storage/CollectionStorage.kt b/src/commonMain/kotlin/com/eignex/util/collections/storage/CollectionStorage.kt new file mode 100644 index 0000000..0d48c73 --- /dev/null +++ b/src/commonMain/kotlin/com/eignex/util/collections/storage/CollectionStorage.kt @@ -0,0 +1,111 @@ +package com.eignex.util.collections.storage + +import com.eignex.util.collections.* +import com.eignex.util.collections.internals.openAddressingCapacity + +/** Primitive backing payload capacity in bytes, excluding headers, references and shared empty storage. */ +val IntArrayDeque.primitiveCapacityBytes: Long get() = primitiveCapacityBytesInternal + +/** Primitive backing payload capacity in bytes, excluding headers, references and shared empty storage. */ +val IntArrayList.primitiveCapacityBytes: Long get() = primitiveCapacityBytesInternal + +/** Primitive backing payload capacity in bytes, excluding headers, references and shared empty storage. */ +val LongArrayList.primitiveCapacityBytes: Long get() = primitiveCapacityBytesInternal + +/** Primitive backing payload capacity in bytes, excluding headers, references and shared empty storage. */ +val IntHashSet.primitiveCapacityBytes: Long get() = primitiveCapacityBytesInternal + +/** Primitive backing payload capacity in bytes, excluding headers, references and shared empty storage. */ +val LongHashSet.primitiveCapacityBytes: Long get() = primitiveCapacityBytesInternal + +/** Primitive backing payload capacity in bytes, excluding headers, references and shared empty storage. */ +val MutableIntIntMap.primitiveCapacityBytes: Long get() = primitiveCapacityBytesInternal + +/** Primitive backing payload capacity in bytes, excluding headers, references and shared empty storage. */ +val MutableIntLongMap.primitiveCapacityBytes: Long get() = primitiveCapacityBytesInternal + +/** Primitive backing payload capacity in bytes, excluding headers, references and shared empty storage. */ +val MutableIntDoubleMap.primitiveCapacityBytes: Long get() = primitiveCapacityBytesInternal + +/** Primitive backing payload capacity in bytes, excluding headers, references and shared empty storage. */ +val MutableIntObjectMap.primitiveCapacityBytes: Long get() = primitiveCapacityBytesInternal + +/** Primitive backing payload capacity in bytes, excluding headers, references and shared empty storage. */ +val MutableLongIntMap.primitiveCapacityBytes: Long get() = primitiveCapacityBytesInternal + +/** Primitive backing payload capacity in bytes, excluding headers, references and shared empty storage. */ +val MutableLongObjectMap.primitiveCapacityBytes: Long get() = primitiveCapacityBytesInternal + +/** Primitive backing payload capacity in bytes, including unused capacity and the partial final word. */ +val Bits.primitiveCapacityBytes: Long get() = words.size.toLong() * Long.SIZE_BYTES + +/** Primitive backing payload capacity in bytes, including unused capacity and the partial final word. */ +val DynamicBits.primitiveCapacityBytes: Long get() = words.size.toLong() * Long.SIZE_BYTES + +/** Number of reference slots, including unused slots; multiply by the runtime's reference width separately. */ +val MutableIntObjectMap.referenceCapacity: Int get() = valuesInternal.size + +/** + * Borrow the value-array identity for ownership accounting. Compare by reference identity only; + * do not cast or mutate it. Growth replaces this array, so reacquire it after mutation. + */ +val MutableIntObjectMap.valueStorageIdentity: Any get() = valuesInternal + +/** Visit every reference slot, including unused null slots. Mutation during traversal is unsupported. */ +@Suppress("UNCHECKED_CAST") +inline fun MutableIntObjectMap.forEachValueSlot(action: (V?) -> Unit) { + for (value in valuesInternal) action(value as V?) +} + +/** Number of reference slots, including unused slots; multiply by the runtime's reference width separately. */ +val MutableLongObjectMap.referenceCapacity: Int get() = valuesInternal.size + +/** + * Borrow the value-array identity for ownership accounting. Compare by reference identity only; + * do not cast or mutate it. Growth replaces this array, so reacquire it after mutation. + */ +val MutableLongObjectMap.valueStorageIdentity: Any get() = valuesInternal + +/** Visit every reference slot, including unused null slots. Mutation during traversal is unsupported. */ +@Suppress("UNCHECKED_CAST") +inline fun MutableLongObjectMap.forEachValueSlot(action: (V?) -> Unit) { + for (value in valuesInternal) action(value as V?) +} + +/** + * Borrow mutable backing storage without copying. Only `0 until size` contains live elements. + * Writes there change the list. Growth and trimming can replace the array; reacquire after mutation. + */ +fun IntArrayList.borrowBackingArray(): IntArray = backingDataInternal + +/** + * Borrow mutable backing storage without copying. Only `0 until size` contains live elements. + * Writes there change the list. Growth and trimming can replace the array; reacquire after mutation. + */ +fun LongArrayList.borrowBackingArray(): LongArray = backingDataInternal + +/** + * Visit every table slot, including shared empty storage. A key is meaningful only in an occupied slot. + * Mutation during traversal is unsupported; table order is unspecified. + */ +inline fun IntHashSet.forEachSlot(action: (occupied: Boolean, key: Int) -> Unit) { + val keys = keysInternal + val used = usedInternal + for (i in used.indices) action(used[i], keys[i]) +} + +/** + * Visit every table slot, including shared empty storage. A key is meaningful only in an occupied slot. + * Mutation during traversal is unsupported; table order is unspecified. + */ +inline fun LongHashSet.forEachSlot(action: (occupied: Boolean, key: Long) -> Unit) { + val keys = keysInternal + val used = usedInternal + for (i in used.indices) action(used[i], keys[i]) +} + +/** Power-of-two slot capacity, at least 8, for [entries] at a maximum load factor of one half. */ +fun hashTableCapacity(entries: Int): Int { + require(entries in 0..(1 shl 29)) { "Entry count exceeds the supported table range" } + return openAddressingCapacity(entries) +} diff --git a/src/commonMain/kotlin/com/eignex/util/collections/storage/PackedBits.kt b/src/commonMain/kotlin/com/eignex/util/collections/storage/PackedBits.kt new file mode 100644 index 0000000..1db6178 --- /dev/null +++ b/src/commonMain/kotlin/com/eignex/util/collections/storage/PackedBits.kt @@ -0,0 +1,83 @@ +package com.eignex.util.collections.storage + +import com.eignex.util.collections.internals.clearPackedBit +import com.eignex.util.collections.internals.fillBitRange +import com.eignex.util.collections.internals.getPackedBit +import com.eignex.util.collections.internals.setPackedBit + +/** + * Operations on caller-owned packed words, with no separate logical size or padding mask. + * Bit indices must fit the supplied storage; mutating calls modify it in place. + */ +object PackedBits { + /** Return whether [bit] is set in [bits]. */ + fun has(bits: LongArray, bit: Int): Boolean = getPackedBit(bits, bit) + + /** Set [bit] in [bits]. */ + fun set(bits: LongArray, bit: Int) = setPackedBit(bits, bit) + + /** Clear [bit] in [bits]. */ + fun clear(bits: LongArray, bit: Int) = clearPackedBit(bits, bit) + + /** Set bits `[from, to)`. */ + fun fillRange(bits: LongArray, from: Int, to: Int) { + if (from >= to) return + fillBitRange(bits, from, to, true) + } + + /** Clear all bits with index `< exclusiveBit`. */ + fun clearBelow(bits: LongArray, exclusiveBit: Int) { + if (exclusiveBit <= 0) return + val fullWords = exclusiveBit ushr 6 + val rem = exclusiveBit and 63 + val limit = minOf(fullWords, bits.size) + for (w in 0 until limit) bits[w] = 0L + if (fullWords < bits.size && rem > 0) { + bits[fullWords] = bits[fullWords] and ((1L shl rem) - 1L).inv() + } + } + + /** Clear all bits with index `> inclusiveBit`. */ + fun clearAbove(bits: LongArray, inclusiveBit: Int) { + if (inclusiveBit < 0) { + bits.fill(0L) + return + } + val fromWord = (inclusiveBit + 1) ushr 6 + val rem = (inclusiveBit + 1) and 63 + if (fromWord < bits.size && rem > 0) { + bits[fromWord] = bits[fromWord] and ((1L shl rem) - 1L) + for (w in fromWord + 1 until bits.size) bits[w] = 0L + } else { + for (w in fromWord until bits.size) bits[w] = 0L + } + } + + /** XOR [src] into [dst] word-by-word: `dst ^= src`. Both arrays must be the same length. */ + fun xorInto(dst: LongArray, src: LongArray) { + for (i in dst.indices) dst[i] = dst[i] xor src[i] + } + + /** Number of set bits across all words. */ + fun popcount(bits: LongArray): Int { + var c = 0 + for (w in bits) c += w.countOneBits() + return c + } + + /** Return the lowest set-bit index, or `-1` when [bits] is empty. */ + fun firstSet(bits: LongArray): Int { + for (w in bits.indices) { + if (bits[w] != 0L) return (w shl 6) + bits[w].countTrailingZeroBits() + } + return -1 + } + + /** Return the highest set-bit index, or `-1` when [bits] is empty. */ + fun lastSet(bits: LongArray): Int { + for (w in bits.indices.reversed()) { + if (bits[w] != 0L) return (w shl 6) + (63 - bits[w].countLeadingZeroBits()) + } + return -1 + } +} diff --git a/src/commonMain/kotlin/com/eignex/util/concurrent/AdderCounters.kt b/src/commonMain/kotlin/com/eignex/util/concurrent/AdderCounters.kt index e5d960e..df7b534 100644 --- a/src/commonMain/kotlin/com/eignex/util/concurrent/AdderCounters.kt +++ b/src/commonMain/kotlin/com/eignex/util/concurrent/AdderCounters.kt @@ -2,7 +2,7 @@ package com.eignex.util.concurrent /** * Additive counters backed by striped JVM adders and atomic cells on other targets. - * JVM reads and replacements are best-effort; counters expose no compare-and-set operation. + * Reads may be approximate during concurrent additions; use cells for replacement and exact update results. * JVM floating-point totals normalize negative zero to positive zero. */ val AdderCounters: CounterMode get() = platformAdderCounters diff --git a/src/commonMain/kotlin/com/eignex/util/concurrent/AtomicCells.kt b/src/commonMain/kotlin/com/eignex/util/concurrent/AtomicCells.kt index 7f3f890..de4bbc7 100644 --- a/src/commonMain/kotlin/com/eignex/util/concurrent/AtomicCells.kt +++ b/src/commonMain/kotlin/com/eignex/util/concurrent/AtomicCells.kt @@ -51,6 +51,7 @@ internal value class AtomicDouble(val ref: KAtomicLong) : DoubleCell { } override fun addAndGet(delta: Double): Double { + if (delta == 0.0) return load() var currentBits = ref.load() while (true) { val currentVal = Double.fromBits(currentBits) diff --git a/src/commonMain/kotlin/com/eignex/util/concurrent/CellMode.kt b/src/commonMain/kotlin/com/eignex/util/concurrent/CellMode.kt index 296d353..a2946f1 100644 --- a/src/commonMain/kotlin/com/eignex/util/concurrent/CellMode.kt +++ b/src/commonMain/kotlin/com/eignex/util/concurrent/CellMode.kt @@ -1,17 +1,9 @@ package com.eignex.util.concurrent -import kotlin.reflect.KProperty - -/** Creates additive counters whose read and replacement guarantees depend on the implementation. */ -interface CounterMode { - /** Create a floating-point counter initialized to [initial]. */ - fun newDouble(initial: Double = 0.0): DoubleCounter - - /** Create an integer counter initialized to [initial]. */ - fun newLong(initial: Long = 0L): LongCounter -} - -/** Creates scalar and array cells that support compare-and-set operations. */ +/** + * Creates exact scalar and array storage with compare-and-set operations. AtomicCells synchronizes + * each operation; SerialCells requires thread confinement or external synchronization. + */ interface CellMode : CounterMode { override fun newDouble(initial: Double): DoubleCell override fun newLong(initial: Long): LongCell @@ -27,49 +19,28 @@ interface CellMode : CounterMode { } /** - * Additive floating-point storage. Atomic cells provide linearizable operations; striped - * counters provide best-effort totals. Plain cells require external synchronization. + * Exact floating-point cell. Compare-and-set uses raw IEEE-754 bits, including NaN payloads and signed zero. + * Zero additions preserve the stored bits. Atomicity depends on the owning mode. */ -interface DoubleCounter { - /** Read the current value, or a best-effort total for a striped counter. */ - fun load(): Double - - /** - * Replace the value. Striped counters use a relative adjustment and concurrent stores - * are best-effort. Non-finite striped replacements reset storage and can lose racing adds. - */ +interface DoubleCell : DoubleCounter { + /** Replace the stored value exactly, preserving its raw bits. */ fun store(value: Double) - /** Add [delta]. A zero delta preserves the stored value's bits in plain and atomic cells. */ - fun add(delta: Double) - - /** Add [delta] and read the result. Striped totals may include other concurrent additions. */ + /** Add [delta] and return the value produced by that update. */ fun addAndGet(delta: Double): Double -} - -/** Additive integer storage with the owning mode's read and replacement guarantees. */ -interface LongCounter { - /** Read the current value, or a best-effort total for a striped counter. */ - fun load(): Long - - /** Replace the value; striped counters use a best-effort relative adjustment. */ - fun store(value: Long) - /** Add [delta], wrapping on integer overflow. */ - fun add(delta: Long) - - /** Add [delta] and read the result. Striped totals may include other concurrent additions. */ - fun addAndGet(delta: Long): Long -} - -/** Floating-point cell whose comparisons use raw IEEE-754 bits, including NaN payloads and signed zero. */ -interface DoubleCell : DoubleCounter { /** Replace the value only when its raw bits match [expectedValue]. */ fun compareAndSet(expectedValue: Double, newValue: Double): Boolean } -/** Integer cell with compare-and-set support. */ +/** Exact integer cell with compare-and-set support; atomicity depends on the owning mode. */ interface LongCell : LongCounter { + /** Replace the stored value exactly. */ + fun store(value: Long) + + /** Add [delta] and return the value produced by that update, wrapping on overflow. */ + fun addAndGet(delta: Long): Long + /** Replace the value only when it equals [expectedValue]. */ fun compareAndSet(expectedValue: Long, newValue: Long): Boolean } @@ -128,12 +99,6 @@ interface LongCellArray { fun compareAndSet(index: Int, expectedValue: Long, newValue: Long): Boolean } -/** Read a floating-point counter as a delegated property. */ -operator fun DoubleCounter.getValue(thisRef: Any?, property: KProperty<*>): Double = load() - -/** Read an integer counter as a delegated property. */ -operator fun LongCounter.getValue(thisRef: Any?, property: KProperty<*>): Long = load() - internal fun rejectBoxedPrimitive(initial: Any?) { require(initial !is Double && initial !is Long) { "ReferenceCell does not support boxed Double/Long; use newDouble/newLong instead" diff --git a/src/commonMain/kotlin/com/eignex/util/concurrent/Counters.kt b/src/commonMain/kotlin/com/eignex/util/concurrent/Counters.kt new file mode 100644 index 0000000..5694919 --- /dev/null +++ b/src/commonMain/kotlin/com/eignex/util/concurrent/Counters.kt @@ -0,0 +1,39 @@ +package com.eignex.util.concurrent + +import kotlin.reflect.KProperty + +/** Creates additive counters. Concurrent reads may be approximate; no replacement is supported. */ +interface CounterMode { + /** Create a floating-point counter initialized to [initial]. */ + fun newDouble(initial: Double = 0.0): DoubleCounter + + /** Create an integer counter initialized to [initial]. */ + fun newLong(initial: Long = 0L): LongCounter +} + +/** + * Additive floating-point storage. Reads of striped counters are not atomic snapshots. + * Thread safety is determined by the owning mode; serial counters need external synchronization. + */ +interface DoubleCounter { + /** Read the current total, which may be approximate during concurrent additions. */ + fun load(): Double + + /** Add [delta]. Floating-point accumulation order depends on the owning mode. */ + fun add(delta: Double) +} + +/** Additive integer storage with the owning mode's concurrency guarantees. */ +interface LongCounter { + /** Read the current total, which may be approximate during concurrent additions. */ + fun load(): Long + + /** Add [delta], wrapping on integer overflow. */ + fun add(delta: Long) +} + +/** Read a floating-point counter as a delegated property. */ +operator fun DoubleCounter.getValue(thisRef: Any?, property: KProperty<*>): Double = load() + +/** Read an integer counter as a delegated property. */ +operator fun LongCounter.getValue(thisRef: Any?, property: KProperty<*>): Long = load() diff --git a/src/commonMain/kotlin/com/eignex/util/concurrent/SerialCells.kt b/src/commonMain/kotlin/com/eignex/util/concurrent/SerialCells.kt index 27aec59..5a2af1f 100644 --- a/src/commonMain/kotlin/com/eignex/util/concurrent/SerialCells.kt +++ b/src/commonMain/kotlin/com/eignex/util/concurrent/SerialCells.kt @@ -55,7 +55,7 @@ internal class SerialDouble(var ref: Double) : DoubleCell { } override fun addAndGet(delta: Double): Double { - ref += delta + add(delta) return ref } diff --git a/src/commonMain/kotlin/com/eignex/util/hash/Hashes.kt b/src/commonMain/kotlin/com/eignex/util/hash/Hashes.kt index 3986250..db4032c 100644 --- a/src/commonMain/kotlin/com/eignex/util/hash/Hashes.kt +++ b/src/commonMain/kotlin/com/eignex/util/hash/Hashes.kt @@ -1,8 +1,5 @@ package com.eignex.util.hash -import com.eignex.util.collections.internals.mixIntKey -import com.eignex.util.collections.internals.mixLongKey - /** * Deterministic SplitMix64 mixer. Not a cryptographic hash. */ @@ -14,7 +11,7 @@ fun splitmix64(value: Long): Long { } /** - * Deterministic 64-bit hash of [bytes], stable across platforms. + * Deterministic 64-bit hash of [bytes], stable across platforms and library versions. * Mixes the input length, little-endian 8-byte chunks and a final tail. Not a cryptographic hash. */ fun hash64(bytes: ByteArray): Long { @@ -43,7 +40,15 @@ fun hash64(bytes: ByteArray): Long { fun hash64(value: String): Long = hash64(value.encodeToByteArray()) /** Fibonacci multiplication with additional mixing of an Int key for power-of-two hash tables. */ -fun fibonacciHash(value: Int): Int = mixIntKey(value) +fun fibonacciHash(value: Int): Int { + // Fold high bits before multiplying so strided keys do not retain identical low bits. + var h = (value xor (value ushr 16)) * -0x61c88647 + h = (h xor (h ushr 13)) * -0x3d4d51cb + return h xor (h ushr 16) +} /** Folded Fibonacci multiplicative mixing of a Long key into a 32-bit table hash. */ -fun fibonacciHash(value: Long): Int = mixLongKey(value) +fun fibonacciHash(value: Long): Int { + val mixed = value * -0x61c8864680b583ebL + return (mixed xor (mixed ushr 32)).toInt() +} diff --git a/src/commonMain/kotlin/com/eignex/util/io/CharReader.kt b/src/commonMain/kotlin/com/eignex/util/io/CharReader.kt index d46932b..50bd0eb 100644 --- a/src/commonMain/kotlin/com/eignex/util/io/CharReader.kt +++ b/src/commonMain/kotlin/com/eignex/util/io/CharReader.kt @@ -4,6 +4,7 @@ package com.eignex.util.io * A forward-only buffered character reader over a [CharSource]. * [peek] supports lookahead without advancing the cursor; [advance] consumes a character. * Chunks are pulled on demand and consumed prefixes are discarded to bound the live buffer. + * This reader borrows [source]; the caller remains responsible for closing it. */ class CharReader(private val source: CharSource) { private val buf = StringBuilder() diff --git a/src/commonMain/kotlin/com/eignex/util/io/CharSource.kt b/src/commonMain/kotlin/com/eignex/util/io/CharSource.kt index 52b9a14..2da142e 100644 --- a/src/commonMain/kotlin/com/eignex/util/io/CharSource.kt +++ b/src/commonMain/kotlin/com/eignex/util/io/CharSource.kt @@ -3,11 +3,14 @@ package com.eignex.util.io /** * A forward-only text source whose [next] slices have arbitrary boundaries. * Consumers must buffer tokens or lines spanning slices. A source is consumed once. - * File-backed sources can also implement [AutoCloseable]; [useSource] releases those resources. + * The caller owns the source and closes it with [close] or [useSource], including after early termination. */ -interface CharSource { +interface CharSource : AutoCloseable { /** The next nonempty slice of characters, or `null` once the input is exhausted. */ fun next(): String? + + /** Release owned resources. Repeated calls are harmless; subsequent [next] calls return null. */ + override fun close() } /** An in-memory [CharSource] over [text], consumed once. */ @@ -15,6 +18,10 @@ class StringCharSource(text: String) : CharSource { private var remaining: String? = text.ifEmpty { null } override fun next(): String? = remaining.also { remaining = null } + + override fun close() { + remaining = null + } } /** Consume the remaining source into a [String]. */ @@ -27,7 +34,8 @@ fun CharSource.readText(): String { /** * Lazily consume lines across chunk boundaries, stripping `\n` and `\r\n` terminators. - * A final unterminated line is yielded. + * A final unterminated line is yielded. This sequence consumes its source once and does not close it; + * iterate inside [useSource], including when stopping early. */ fun CharSource.lineSequence(): Sequence = sequence { val carry = StringBuilder() @@ -60,4 +68,4 @@ private fun stripCr(line: String): String = if (line.isNotEmpty() && line[line.length - 1] == '\r') line.substring(0, line.length - 1) else line /** Consume this source and close its resources on success, exceptions and early returns. */ -inline fun CharSource.useSource(read: (CharSource) -> T): T = (this as? AutoCloseable).use { read(this) } +inline fun CharSource.useSource(read: (CharSource) -> T): T = use { read(this) } diff --git a/src/commonTest/kotlin/com/eignex/util/collections/BitsTest.kt b/src/commonTest/kotlin/com/eignex/util/collections/BitsTest.kt index de08bfb..fab999e 100644 --- a/src/commonTest/kotlin/com/eignex/util/collections/BitsTest.kt +++ b/src/commonTest/kotlin/com/eignex/util/collections/BitsTest.kt @@ -1,5 +1,10 @@ package com.eignex.util.collections +import com.eignex.util.collections.storage.PackedBits +import com.eignex.util.collections.storage.copyWordsFrom +import com.eignex.util.collections.storage.getWord +import com.eignex.util.collections.storage.setWord +import com.eignex.util.collections.storage.wordCount import kotlin.test.Test import kotlin.test.assertContentEquals import kotlin.test.assertEquals @@ -78,46 +83,46 @@ class BitsTest { @Test fun `companion set has and clear should round-trip across words`() { val bits = LongArray(3) - Bits.set(bits, 0) - Bits.set(bits, 63) - Bits.set(bits, 64) - Bits.set(bits, 129) - assertTrue(Bits.has(bits, 0)) - assertTrue(Bits.has(bits, 63)) - assertTrue(Bits.has(bits, 64)) - assertTrue(Bits.has(bits, 129)) - assertFalse(Bits.has(bits, 1)) - assertFalse(Bits.has(bits, 128)) - Bits.clear(bits, 64) - assertFalse(Bits.has(bits, 64)) - assertTrue(Bits.has(bits, 63)) + PackedBits.set(bits, 0) + PackedBits.set(bits, 63) + PackedBits.set(bits, 64) + PackedBits.set(bits, 129) + assertTrue(PackedBits.has(bits, 0)) + assertTrue(PackedBits.has(bits, 63)) + assertTrue(PackedBits.has(bits, 64)) + assertTrue(PackedBits.has(bits, 129)) + assertFalse(PackedBits.has(bits, 1)) + assertFalse(PackedBits.has(bits, 128)) + PackedBits.clear(bits, 64) + assertFalse(PackedBits.has(bits, 64)) + assertTrue(PackedBits.has(bits, 63)) } @Test fun `fillRange should set a half open range across word boundaries`() { val bits = LongArray(3) - Bits.fillRange(bits, 61, 67) - for (i in 0..60) assertFalse(Bits.has(bits, i), "bit $i") - for (i in 61..66) assertTrue(Bits.has(bits, i), "bit $i") - for (i in 67..140) assertFalse(Bits.has(bits, i), "bit $i") + PackedBits.fillRange(bits, 61, 67) + for (i in 0..60) assertFalse(PackedBits.has(bits, i), "bit $i") + for (i in 61..66) assertTrue(PackedBits.has(bits, i), "bit $i") + for (i in 67..140) assertFalse(PackedBits.has(bits, i), "bit $i") } @Test fun `clearBelow should clear only bits below the exclusive boundary`() { val bits = LongArray(3) - Bits.fillRange(bits, 0, 140) - Bits.clearBelow(bits, 65) - for (i in 0..64) assertFalse(Bits.has(bits, i), "bit $i") - for (i in 65..139) assertTrue(Bits.has(bits, i), "bit $i") + PackedBits.fillRange(bits, 0, 140) + PackedBits.clearBelow(bits, 65) + for (i in 0..64) assertFalse(PackedBits.has(bits, i), "bit $i") + for (i in 65..139) assertTrue(PackedBits.has(bits, i), "bit $i") } @Test fun `clearAbove should clear only bits above the inclusive boundary`() { val bits = LongArray(3) - Bits.fillRange(bits, 0, 140) - Bits.clearAbove(bits, 65) - for (i in 0..65) assertTrue(Bits.has(bits, i), "bit $i") - for (i in 66..139) assertFalse(Bits.has(bits, i), "bit $i") + PackedBits.fillRange(bits, 0, 140) + PackedBits.clearAbove(bits, 65) + for (i in 0..65) assertTrue(PackedBits.has(bits, i), "bit $i") + for (i in 66..139) assertFalse(PackedBits.has(bits, i), "bit $i") } @Test @@ -125,10 +130,10 @@ class BitsTest { for (boundary in intArrayOf(Int.MIN_VALUE, -65, -64, -2, -1)) { val bits = longArrayOf(1L, Long.MIN_VALUE, 0x55L, -1L) - Bits.clearAbove(bits, boundary) + PackedBits.clearAbove(bits, boundary) assertContentEquals(LongArray(bits.size), bits, "boundary $boundary") - Bits.clearAbove(LongArray(0), boundary) + PackedBits.clearAbove(LongArray(0), boundary) } } @@ -137,7 +142,7 @@ class BitsTest { val bits = longArrayOf(1L, Long.MIN_VALUE, 0x55L, -1L) val expected = bits.copyOf() - Bits.clearAbove(bits, Int.MAX_VALUE) + PackedBits.clearAbove(bits, Int.MAX_VALUE) assertContentEquals(expected, bits) } @@ -145,14 +150,14 @@ class BitsTest { @Test fun `firstSet and lastSet should return a sentinel when empty and the extremes otherwise`() { val empty = LongArray(2) - assertEquals(-1, Bits.firstSet(empty)) - assertEquals(-1, Bits.lastSet(empty)) + assertEquals(-1, PackedBits.firstSet(empty)) + assertEquals(-1, PackedBits.lastSet(empty)) val bits = LongArray(3) - Bits.set(bits, 5) - Bits.set(bits, 73) - Bits.set(bits, 130) - assertEquals(5, Bits.firstSet(bits)) - assertEquals(130, Bits.lastSet(bits)) + PackedBits.set(bits, 5) + PackedBits.set(bits, 73) + PackedBits.set(bits, 130) + assertEquals(5, PackedBits.firstSet(bits)) + assertEquals(130, PackedBits.lastSet(bits)) } } diff --git a/src/commonTest/kotlin/com/eignex/util/collections/CollectionExtrasTest.kt b/src/commonTest/kotlin/com/eignex/util/collections/CollectionExtrasTest.kt index 4472c05..9826622 100644 --- a/src/commonTest/kotlin/com/eignex/util/collections/CollectionExtrasTest.kt +++ b/src/commonTest/kotlin/com/eignex/util/collections/CollectionExtrasTest.kt @@ -1,5 +1,6 @@ package com.eignex.util.collections +import com.eignex.util.collections.storage.hashTableCapacity import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith diff --git a/src/commonTest/kotlin/com/eignex/util/collections/CollectionModelTest.kt b/src/commonTest/kotlin/com/eignex/util/collections/CollectionModelTest.kt index 3af01e1..3d9cb24 100644 --- a/src/commonTest/kotlin/com/eignex/util/collections/CollectionModelTest.kt +++ b/src/commonTest/kotlin/com/eignex/util/collections/CollectionModelTest.kt @@ -236,8 +236,8 @@ class CollectionModelTest { val index = random.nextInt(expected.size) expected[index] = expected.last() expected.removeAt(expected.lastIndex) - ints.removeAt(index) - longs.removeAt(index) + ints.removeAtSwap(index) + longs.removeAtSwap(index) } 4 -> { diff --git a/src/commonTest/kotlin/com/eignex/util/collections/IntArrayListTest.kt b/src/commonTest/kotlin/com/eignex/util/collections/IntArrayListTest.kt index d2fd909..de9c69a 100644 --- a/src/commonTest/kotlin/com/eignex/util/collections/IntArrayListTest.kt +++ b/src/commonTest/kotlin/com/eignex/util/collections/IntArrayListTest.kt @@ -15,7 +15,7 @@ class IntArrayListTest { for (index in listOf(-1, values.size, values.size + 1, Int.MAX_VALUE)) { assertFailsWith { list[index] } assertFailsWith { list[index] = 99 } - assertFailsWith { list.removeAt(index) } + assertFailsWith { list.removeAtSwap(index) } assertEquals(values.toList(), list.toIntArray().toList()) assertEquals(values.size, list.size) } @@ -54,22 +54,22 @@ class IntArrayListTest { } @Test - fun `removeAt should swap the tail into the gap`() { + fun `removeAtSwap should swap the tail into the gap`() { val list = IntArrayList() for (v in intArrayOf(10, 20, 30, 40)) list.add(v) - list.removeAt(1) + list.removeAtSwap(1) assertEquals(3, list.size) assertEquals(listOf(10, 40, 30), list.toIntArray().toList()) } @Test - fun `removeValue should swap-remove the first occurrence and report presence`() { + fun `removeValueSwap should swap-remove the first occurrence and report presence`() { val list = IntArrayList() for (v in intArrayOf(5, 7, 5, 9)) list.add(v) - assertTrue(list.removeValue(5)) + assertTrue(list.removeValueSwap(5)) assertEquals(3, list.size) assertEquals(listOf(9, 7, 5), list.toIntArray().toList()) - assertFalse(list.removeValue(42)) + assertFalse(list.removeValueSwap(42)) assertEquals(3, list.size) } diff --git a/src/commonTest/kotlin/com/eignex/util/collections/LongArrayListTest.kt b/src/commonTest/kotlin/com/eignex/util/collections/LongArrayListTest.kt index bd7b4d0..e5734af 100644 --- a/src/commonTest/kotlin/com/eignex/util/collections/LongArrayListTest.kt +++ b/src/commonTest/kotlin/com/eignex/util/collections/LongArrayListTest.kt @@ -15,7 +15,7 @@ class LongArrayListTest { for (index in listOf(-1, values.size, values.size + 1, Int.MAX_VALUE)) { assertFailsWith { list[index] } assertFailsWith { list[index] = 99 } - assertFailsWith { list.removeAt(index) } + assertFailsWith { list.removeAtSwap(index) } assertEquals(values.toList(), list.toLongArray().toList()) assertEquals(values.size, list.size) } @@ -43,22 +43,22 @@ class LongArrayListTest { } @Test - fun `removeAt should swap the tail into the gap`() { + fun `removeAtSwap should swap the tail into the gap`() { val list = LongArrayList() for (v in longArrayOf(10, 20, 30, 40)) list.add(v) - list.removeAt(1) + list.removeAtSwap(1) assertEquals(3, list.size) assertEquals(listOf(10L, 40L, 30L), list.toLongArray().toList()) } @Test - fun `removeValue should remove the first occurrence and report presence`() { + fun `removeValueSwap should remove the first occurrence and report presence`() { val list = LongArrayList() for (v in longArrayOf(5, 7, 5, 9)) list.add(v) - assertTrue(list.removeValue(5)) + assertTrue(list.removeValueSwap(5)) assertEquals(3, list.size) assertEquals(listOf(9L, 7L, 5L), list.toLongArray().toList()) - assertFalse(list.removeValue(42)) + assertFalse(list.removeValueSwap(42)) } @Test diff --git a/src/commonTest/kotlin/com/eignex/util/collections/LongHashSetTest.kt b/src/commonTest/kotlin/com/eignex/util/collections/LongHashSetTest.kt index 9b40bb8..fc47c9b 100644 --- a/src/commonTest/kotlin/com/eignex/util/collections/LongHashSetTest.kt +++ b/src/commonTest/kotlin/com/eignex/util/collections/LongHashSetTest.kt @@ -1,6 +1,9 @@ package com.eignex.util.collections -import com.eignex.util.collections.internals.mixLongKey +import com.eignex.util.collections.cooperative.containsBounded +import com.eignex.util.collections.cooperative.tryAddBounded +import com.eignex.util.collections.storage.primitiveCapacityBytes +import com.eignex.util.hash.fibonacciHash import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse @@ -13,18 +16,18 @@ class LongHashSetTest { for ((existing, additional) in listOf(0 to 0, 0 to 1, 1 to 1, 8 to 1)) { val set = LongHashSet() repeat(existing) { set.add(it.toLong()) } - val bytes = set.allocatedBytes + val bytes = set.primitiveCapacityBytes val fits = set.canAddWithoutGrowing(additional) repeat(additional) { set.add((existing + it).toLong()) } - assertEquals(fits, bytes == set.allocatedBytes) + assertEquals(fits, bytes == set.primitiveCapacityBytes) } } @Test fun `bounded lookup should stop a collision chain without changing retained keys`() { - val keys = (0L..64L).groupBy { mixLongKey(it) and 15 }.values.first { it.size >= 3 }.take(3) + val keys = (0L..64L).groupBy { fibonacciHash(it) and 15 }.values.first { it.size >= 3 }.take(3) val set = LongHashSet() for (key in keys) set.add(key) var charged = 0 @@ -59,7 +62,7 @@ class LongHashSetTest { val added = set.tryAddBounded(4L, 72L, 1000L, 1000L, { false }, {}) assertEquals(null, added) - assertEquals(72L, set.allocatedBytes) + assertEquals(72L, set.primitiveCapacityBytes) assertEquals(4, set.size) repeat(4) { assertTrue(it.toLong() in set) } assertEquals(false, set.tryAddBounded(0L, 0L, 1000L, 0L, { false }, {})) @@ -74,7 +77,7 @@ class LongHashSetTest { val added = set.tryAddBounded(4L, 1000L, 1000L, 1000L, { charged >= 10 }, { charged++ }) assertEquals(null, added) - assertEquals(72L, set.allocatedBytes) + assertEquals(72L, set.primitiveCapacityBytes) assertEquals(4, set.size) repeat(4) { assertTrue(it.toLong() in set) } assertFalse(4L in set) @@ -88,7 +91,7 @@ class LongHashSetTest { val added = set.tryAddBounded(1L, 1000L, work, scratch, { false }, {}) assertEquals(null, added) - assertEquals(0L, set.allocatedBytes) + assertEquals(0L, set.primitiveCapacityBytes) assertEquals(0, set.size) } } @@ -107,7 +110,7 @@ class LongHashSetTest { assertEquals(null, added) assertEquals(required, charged) - assertEquals(72L, set.allocatedBytes) + assertEquals(72L, set.primitiveCapacityBytes) assertEquals(4, set.size) assertFalse(4L in set) } diff --git a/src/commonTest/kotlin/com/eignex/util/collections/MutableLongIntMapTest.kt b/src/commonTest/kotlin/com/eignex/util/collections/MutableLongIntMapTest.kt index ab8a429..a313e3a 100644 --- a/src/commonTest/kotlin/com/eignex/util/collections/MutableLongIntMapTest.kt +++ b/src/commonTest/kotlin/com/eignex/util/collections/MutableLongIntMapTest.kt @@ -1,5 +1,6 @@ package com.eignex.util.collections +import com.eignex.util.collections.cooperative.removeAndUpdate import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith diff --git a/src/commonTest/kotlin/com/eignex/util/collections/cooperative/PrepareIntSwapSetTest.kt b/src/commonTest/kotlin/com/eignex/util/collections/cooperative/PrepareIntSwapSetTest.kt new file mode 100644 index 0000000..ee65762 --- /dev/null +++ b/src/commonTest/kotlin/com/eignex/util/collections/cooperative/PrepareIntSwapSetTest.kt @@ -0,0 +1,22 @@ +package com.eignex.util.collections.cooperative + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class PrepareIntSwapSetTest { + @Test + fun `yielded construction publishes exactly one fully initialized set`() { + val steps = prepareIntSwapSet(7, 3).toList() + assertEquals(6, steps.size) + assertTrue(steps.dropLast(1).all { it == null }) + val set = checkNotNull(steps.last()) + assertTrue(set.isEmpty()) + repeat(7) { assertTrue(set.add(it)) } + repeat(7) { assertTrue(it in set) } + assertFalse(7 in set) + assertFailsWith { set.add(7) } + } +} diff --git a/src/commonTest/kotlin/com/eignex/util/collections/storage/CollectionStorageTest.kt b/src/commonTest/kotlin/com/eignex/util/collections/storage/CollectionStorageTest.kt new file mode 100644 index 0000000..12c4357 --- /dev/null +++ b/src/commonTest/kotlin/com/eignex/util/collections/storage/CollectionStorageTest.kt @@ -0,0 +1,74 @@ +package com.eignex.util.collections.storage + +import com.eignex.util.collections.* +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotSame +import kotlin.test.assertSame +import kotlin.test.assertTrue + +class CollectionStorageTest { + @Test + fun `empty sets exclude shared storage and release drops owned capacity`() { + val ints = IntHashSet() + val longs = LongHashSet() + assertEquals(0L, ints.primitiveCapacityBytes) + assertEquals(0L, longs.primitiveCapacityBytes) + ints.add(1) + longs.add(1L) + val bytes = longs.primitiveCapacityBytes + assertTrue(ints.primitiveCapacityBytes > 0L) + longs.clear() + assertEquals(bytes, longs.primitiveCapacityBytes) + longs.release() + assertEquals(0L, longs.primitiveCapacityBytes) + } + + @Test + fun `borrowed list arrays share live values and must be reacquired after growth`() { + val ints = IntArrayList(1).apply { add(7) } + val longs = LongArrayList(1).apply { add(9L) } + val intStorage = ints.borrowBackingArray() + val longStorage = longs.borrowBackingArray() + intStorage[0] = 8 + longStorage[0] = 10L + assertEquals(8, ints[0]) + assertEquals(10L, longs[0]) + ints.add(11) + longs.add(12L) + assertNotSame(intStorage, ints.borrowBackingArray()) + assertNotSame(longStorage, longs.borrowBackingArray()) + assertEquals(8L, ints.primitiveCapacityBytes) + assertEquals(16L, longs.primitiveCapacityBytes) + } + + @Test + fun `object map accounting separates primitive payload reference slots and owned objects`() { + val value = Any() + val ints = MutableIntObjectMap(0) + val longs = MutableLongObjectMap(0) + assertEquals(40L, ints.primitiveCapacityBytes) + assertEquals(72L, longs.primitiveCapacityBytes) + assertEquals(8, ints.referenceCapacity) + assertEquals(8, longs.referenceCapacity) + val original = ints.valueStorageIdentity + ints.put(0, value) + ints.put(1, null) + assertSame(original, ints.valueStorageIdentity) + val slots = mutableListOf() + ints.forEachValueSlot { slots.add(it) } + assertEquals(ints.referenceCapacity, slots.size) + assertEquals(1, slots.count { it === value }) + assertEquals(7, slots.count { it == null }) + repeat(10) { ints.put(it + 2, value) } + assertNotSame(original, ints.valueStorageIdentity) + ints.clear() + ints.forEachValueSlot { assertEquals(null, it) } + assertFalse(ints.containsKey(0)) + longs.put(0L, value) + val longSlots = mutableListOf() + longs.forEachValueSlot { longSlots.add(it) } + assertEquals(1, longSlots.count { it === value }) + } +} diff --git a/src/commonTest/kotlin/com/eignex/util/concurrent/CellModeTest.kt b/src/commonTest/kotlin/com/eignex/util/concurrent/CellModeTest.kt index 2321fb0..720ac76 100644 --- a/src/commonTest/kotlin/com/eignex/util/concurrent/CellModeTest.kt +++ b/src/commonTest/kotlin/com/eignex/util/concurrent/CellModeTest.kt @@ -6,6 +6,45 @@ import kotlin.test.assertFalse import kotlin.test.assertTrue class CellModeTest { + @Test + fun `only accumulation and observation are required by the counter contract`() { + val counter: LongCounter = object : LongCounter { + private var total = 0L + override fun add(delta: Long) { + total += delta + } + override fun load(): Long = total + } + counter.add(7L) + assertEquals(7L, counter.load()) + } + + @Test + fun `exact cells preserve replacement bits and return their own update result`() { + for (mode in listOf(SerialCells, AtomicCells)) { + val cell = mode.newDouble() + for (value in listOf( + 1e20, + -1e20, + 1.0, + -0.0, + Double.POSITIVE_INFINITY, + Double.fromBits(0x7ff8000000000042L), + )) { + cell.store(value) + assertEquals(value.toRawBits(), cell.load().toRawBits()) + assertEquals(value.toRawBits(), cell.addAndGet(0.0).toRawBits()) + assertEquals(value.toRawBits(), cell.addAndGet(-0.0).toRawBits()) + } + cell.store(1.0) + assertEquals(3.5, cell.addAndGet(2.5)) + val integer = mode.newLong(Long.MAX_VALUE) + assertEquals(Long.MIN_VALUE, integer.addAndGet(1L)) + integer.store(3L) + assertEquals(3L, integer.load()) + } + } + @Test fun `zero additions preserve negative zero in scalars and arrays`() { for (mode in listOf(SerialCells, AtomicCells)) { diff --git a/src/commonTest/kotlin/com/eignex/util/io/CharSourceUseTest.kt b/src/commonTest/kotlin/com/eignex/util/io/CharSourceUseTest.kt index cade863..6ba21d2 100644 --- a/src/commonTest/kotlin/com/eignex/util/io/CharSourceUseTest.kt +++ b/src/commonTest/kotlin/com/eignex/util/io/CharSourceUseTest.kt @@ -3,14 +3,38 @@ package com.eignex.util.io import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith +import kotlin.test.assertNull import kotlin.test.assertTrue class CharSourceUseTest { + @Test + fun `closing an in-memory source is idempotent and discards unread text`() { + val source: CharSource = StringCharSource("unread") + source.close() + source.close() + assertNull(source.next()) + } + + @Test + fun `close failures are suppressed when a read already failed`() { + val source = object : CharSource { + override fun next(): String? = null + override fun close() { + error("close failure") + } + } + val failure = assertFailsWith { + source.useSource { throw IllegalArgumentException("read failure") } + } + assertEquals("read failure", failure.message) + assertEquals("close failure", failure.suppressedExceptions.single().message) + } + @Test fun `stopping a read closes its owned source`() { for (failure in listOf(false, true)) { var closed = false - val source = object : CharSource, AutoCloseable { + val source = object : CharSource { override fun next(): String = "unread input" override fun close() { closed = true diff --git a/src/commonTest/kotlin/com/eignex/util/io/ChunkedCharSource.kt b/src/commonTest/kotlin/com/eignex/util/io/ChunkedCharSource.kt index 132dc2d..6946e3a 100644 --- a/src/commonTest/kotlin/com/eignex/util/io/ChunkedCharSource.kt +++ b/src/commonTest/kotlin/com/eignex/util/io/ChunkedCharSource.kt @@ -3,7 +3,11 @@ package com.eignex.util.io /** A [CharSource] over pre-split [chunks], for exercising a consumer across arbitrary chunk boundaries. */ class ChunkedCharSource(chunks: List) : CharSource { private val chunk = chunks.iterator() - override fun next(): String? = if (chunk.hasNext()) chunk.next() else null + private var closed = false + override fun next(): String? = if (!closed && chunk.hasNext()) chunk.next() else null + override fun close() { + closed = true + } } /** A [CharSource] that hands out [text] one character at a time — the tightest chunking, which lands a diff --git a/src/hostMain/kotlin/com/eignex/util/platform/IdentityHash.kt b/src/hostMain/kotlin/com/eignex/util/runtime/IdentityHash.kt similarity index 88% rename from src/hostMain/kotlin/com/eignex/util/platform/IdentityHash.kt rename to src/hostMain/kotlin/com/eignex/util/runtime/IdentityHash.kt index a773e33..d26d981 100644 --- a/src/hostMain/kotlin/com/eignex/util/platform/IdentityHash.kt +++ b/src/hostMain/kotlin/com/eignex/util/runtime/IdentityHash.kt @@ -1,4 +1,4 @@ -package com.eignex.util.platform +package com.eignex.util.runtime /** * Hash of [value]'s reference identity, independent of its overridden hash code. diff --git a/src/hostMain/kotlin/com/eignex/util/platform/HeapSample.kt b/src/hostMain/kotlin/com/eignex/util/runtime/diagnostics/HeapSample.kt similarity index 89% rename from src/hostMain/kotlin/com/eignex/util/platform/HeapSample.kt rename to src/hostMain/kotlin/com/eignex/util/runtime/diagnostics/HeapSample.kt index d5ec56d..bad788e 100644 --- a/src/hostMain/kotlin/com/eignex/util/platform/HeapSample.kt +++ b/src/hostMain/kotlin/com/eignex/util/runtime/diagnostics/HeapSample.kt @@ -1,4 +1,4 @@ -package com.eignex.util.platform +package com.eignex.util.runtime.diagnostics /** A diagnostic heap reading; collecting a sample may trigger garbage collection. */ class HeapSample( diff --git a/src/hostMain/kotlin/com/eignex/util/platform/RuntimeDiagnostics.kt b/src/hostMain/kotlin/com/eignex/util/runtime/diagnostics/RuntimeDiagnostics.kt similarity index 93% rename from src/hostMain/kotlin/com/eignex/util/platform/RuntimeDiagnostics.kt rename to src/hostMain/kotlin/com/eignex/util/runtime/diagnostics/RuntimeDiagnostics.kt index 97b3e6a..b8911a8 100644 --- a/src/hostMain/kotlin/com/eignex/util/platform/RuntimeDiagnostics.kt +++ b/src/hostMain/kotlin/com/eignex/util/runtime/diagnostics/RuntimeDiagnostics.kt @@ -1,4 +1,4 @@ -package com.eignex.util.platform +package com.eignex.util.runtime.diagnostics /** * Start process-lifetime peak-heap sampling on a daemon JVM thread. Repeated calls are a no-op. diff --git a/src/hostTest/kotlin/com/eignex/util/platform/IdentityHashTest.kt b/src/hostTest/kotlin/com/eignex/util/runtime/IdentityHashTest.kt similarity index 93% rename from src/hostTest/kotlin/com/eignex/util/platform/IdentityHashTest.kt rename to src/hostTest/kotlin/com/eignex/util/runtime/IdentityHashTest.kt index 834cb5c..f30bbef 100644 --- a/src/hostTest/kotlin/com/eignex/util/platform/IdentityHashTest.kt +++ b/src/hostTest/kotlin/com/eignex/util/runtime/IdentityHashTest.kt @@ -1,6 +1,6 @@ @file:Suppress("UndocumentedPublicClass", "UndocumentedPublicFunction", "FunctionNaming") -package com.eignex.util.platform +package com.eignex.util.runtime import kotlin.test.Test import kotlin.test.assertEquals diff --git a/src/jvmMain/kotlin/com/eignex/util/concurrent/AdderCounters.jvm.kt b/src/jvmMain/kotlin/com/eignex/util/concurrent/AdderCounters.jvm.kt index c5e978b..13f6d51 100644 --- a/src/jvmMain/kotlin/com/eignex/util/concurrent/AdderCounters.jvm.kt +++ b/src/jvmMain/kotlin/com/eignex/util/concurrent/AdderCounters.jvm.kt @@ -20,26 +20,10 @@ internal value class DoubleAdder(val ref: JDoubleAdder) : DoubleCounter { override fun load(): Double = ref.sum() - // A relative add preserves racing contributions; non-finite deltas require resetting the stripes. - override fun store(value: Double) { - val delta = value - ref.sum() - if (delta.isFinite()) { - ref.add(delta) - } else { - ref.reset() - ref.add(value) - } - } - override fun add(delta: Double) { if (delta == 0.0) return ref.add(delta) } - - override fun addAndGet(delta: Double): Double { - ref.add(delta) - return ref.sum() - } } @JvmInline @@ -48,18 +32,8 @@ internal value class LongAdder(val ref: JLongAdder) : LongCounter { override fun load(): Long = ref.sum() - // Resetting stripes can discard racing adds; a relative add preserves their contributions. - override fun store(value: Long) { - ref.add(value - ref.sum()) - } - override fun add(delta: Long) { if (delta == 0L) return ref.add(delta) } - - override fun addAndGet(delta: Long): Long { - ref.add(delta) - return ref.sum() - } } diff --git a/src/jvmMain/kotlin/com/eignex/util/io/TextFiles.jvm.kt b/src/jvmMain/kotlin/com/eignex/util/io/TextFiles.jvm.kt index 7846010..a45de2e 100644 --- a/src/jvmMain/kotlin/com/eignex/util/io/TextFiles.jvm.kt +++ b/src/jvmMain/kotlin/com/eignex/util/io/TextFiles.jvm.kt @@ -33,8 +33,7 @@ private class ReaderCharSource( private val reader: Reader, private val onEof: () -> Unit = {}, private val onClose: () -> Unit = {}, -) : CharSource, - AutoCloseable { +) : CharSource { private val buffer = CharArray(64 * 1024) private var done = false diff --git a/src/jvmMain/kotlin/com/eignex/util/platform/IdentityHash.jvm.kt b/src/jvmMain/kotlin/com/eignex/util/runtime/IdentityHash.jvm.kt similarity index 83% rename from src/jvmMain/kotlin/com/eignex/util/platform/IdentityHash.jvm.kt rename to src/jvmMain/kotlin/com/eignex/util/runtime/IdentityHash.jvm.kt index ec03c55..6e5a087 100644 --- a/src/jvmMain/kotlin/com/eignex/util/platform/IdentityHash.jvm.kt +++ b/src/jvmMain/kotlin/com/eignex/util/runtime/IdentityHash.jvm.kt @@ -1,4 +1,4 @@ -package com.eignex.util.platform +package com.eignex.util.runtime /** Hash the reference identity of [value], independently of its overridden hash code. */ actual fun identityHash(value: Any): Int = System.identityHashCode(value) diff --git a/src/jvmMain/kotlin/com/eignex/util/platform/RuntimeDiagnostics.jvm.kt b/src/jvmMain/kotlin/com/eignex/util/runtime/diagnostics/RuntimeDiagnostics.jvm.kt similarity index 97% rename from src/jvmMain/kotlin/com/eignex/util/platform/RuntimeDiagnostics.jvm.kt rename to src/jvmMain/kotlin/com/eignex/util/runtime/diagnostics/RuntimeDiagnostics.jvm.kt index dbf087b..bd293b6 100644 --- a/src/jvmMain/kotlin/com/eignex/util/platform/RuntimeDiagnostics.jvm.kt +++ b/src/jvmMain/kotlin/com/eignex/util/runtime/diagnostics/RuntimeDiagnostics.jvm.kt @@ -1,6 +1,6 @@ @file:Suppress("UndocumentedPublicFunction") -package com.eignex.util.platform +package com.eignex.util.runtime.diagnostics import java.lang.management.ManagementFactory import java.util.concurrent.atomic.AtomicBoolean diff --git a/src/jvmTest/kotlin/com/eignex/util/concurrent/AdderCountersTest.kt b/src/jvmTest/kotlin/com/eignex/util/concurrent/AdderCountersTest.kt index 2e26b7a..f03cac0 100644 --- a/src/jvmTest/kotlin/com/eignex/util/concurrent/AdderCountersTest.kt +++ b/src/jvmTest/kotlin/com/eignex/util/concurrent/AdderCountersTest.kt @@ -14,20 +14,14 @@ class AdderCountersTest { assertEquals(4.0, d.load(), DELTA) } - @Test - fun `DoubleAdder addAndGet returns updated value`() { - val d = AdderCounters.newDouble(1.0) - assertEquals(3.5, d.addAndGet(2.5), DELTA) - assertEquals(3.5, d.load(), DELTA) - } - @Test fun `LongAdder round trips and accumulates`() { val l = AdderCounters.newLong(0L) l.add(3L) l.add(7L) assertEquals(10L, l.load()) - assertEquals(15L, l.addAndGet(5L)) + l.add(5L) + assertEquals(15L, l.load()) } @Test @@ -51,18 +45,4 @@ class AdderCountersTest { } assertEquals((threads * iters).toLong(), l.load()) } - - @Test - fun `DoubleAdder store recovers from an infinite sum`() { - val d = AdderCounters.newDouble(Double.POSITIVE_INFINITY) - d.store(0.0) - assertEquals(0.0, d.load()) - } - - @Test - fun `DoubleAdder store assigns an infinite value`() { - val d = AdderCounters.newDouble(Double.NEGATIVE_INFINITY) - d.store(Double.POSITIVE_INFINITY) - assertEquals(Double.POSITIVE_INFINITY, d.load()) - } } diff --git a/src/jvmTest/kotlin/com/eignex/util/platform/RuntimeDiagnosticsTest.kt b/src/jvmTest/kotlin/com/eignex/util/runtime/diagnostics/RuntimeDiagnosticsTest.kt similarity index 94% rename from src/jvmTest/kotlin/com/eignex/util/platform/RuntimeDiagnosticsTest.kt rename to src/jvmTest/kotlin/com/eignex/util/runtime/diagnostics/RuntimeDiagnosticsTest.kt index 51e15d6..1c65084 100644 --- a/src/jvmTest/kotlin/com/eignex/util/platform/RuntimeDiagnosticsTest.kt +++ b/src/jvmTest/kotlin/com/eignex/util/runtime/diagnostics/RuntimeDiagnosticsTest.kt @@ -1,4 +1,4 @@ -package com.eignex.util.platform +package com.eignex.util.runtime.diagnostics import kotlin.test.Test import kotlin.test.assertNotNull diff --git a/src/nativeMain/kotlin/com/eignex/util/platform/IdentityHash.native.kt b/src/nativeMain/kotlin/com/eignex/util/runtime/IdentityHash.native.kt similarity index 89% rename from src/nativeMain/kotlin/com/eignex/util/platform/IdentityHash.native.kt rename to src/nativeMain/kotlin/com/eignex/util/runtime/IdentityHash.native.kt index 1234e06..bbb4164 100644 --- a/src/nativeMain/kotlin/com/eignex/util/platform/IdentityHash.native.kt +++ b/src/nativeMain/kotlin/com/eignex/util/runtime/IdentityHash.native.kt @@ -1,4 +1,4 @@ -package com.eignex.util.platform +package com.eignex.util.runtime import kotlin.experimental.ExperimentalNativeApi import kotlin.native.identityHashCode diff --git a/src/nativeMain/kotlin/com/eignex/util/platform/RuntimeDiagnostics.native.kt b/src/nativeMain/kotlin/com/eignex/util/runtime/diagnostics/RuntimeDiagnostics.native.kt similarity index 88% rename from src/nativeMain/kotlin/com/eignex/util/platform/RuntimeDiagnostics.native.kt rename to src/nativeMain/kotlin/com/eignex/util/runtime/diagnostics/RuntimeDiagnostics.native.kt index cbd2e7c..5ac8ba7 100644 --- a/src/nativeMain/kotlin/com/eignex/util/platform/RuntimeDiagnostics.native.kt +++ b/src/nativeMain/kotlin/com/eignex/util/runtime/diagnostics/RuntimeDiagnostics.native.kt @@ -1,4 +1,4 @@ -package com.eignex.util.platform +package com.eignex.util.runtime.diagnostics /** Native runtimes have no comparable heap accounting; sampling is unavailable. */ actual fun startHeapPeakSampler() = Unit diff --git a/tests/common-main/src/commonMain/kotlin/com/eignex/util/consumer/CommonConsumer.kt b/tests/common-main/src/commonMain/kotlin/com/eignex/util/consumer/CommonConsumer.kt index 78ecd59..9545e67 100644 --- a/tests/common-main/src/commonMain/kotlin/com/eignex/util/consumer/CommonConsumer.kt +++ b/tests/common-main/src/commonMain/kotlin/com/eignex/util/consumer/CommonConsumer.kt @@ -3,11 +3,20 @@ package com.eignex.util.consumer import com.eignex.util.collections.BitSet import com.eignex.util.collections.Bits import com.eignex.util.collections.DynamicBits +import com.eignex.util.collections.IntArrayList +import com.eignex.util.collections.IntHashSet import com.eignex.util.collections.IntIndexedCollection import com.eignex.util.collections.IntIntLookup import com.eignex.util.collections.IntIntMap import com.eignex.util.collections.MutableIntIntMap +import com.eignex.util.collections.MutableIntObjectMap +import com.eignex.util.collections.cooperative.prepareIntSwapSet import com.eignex.util.collections.sortedKeys +import com.eignex.util.collections.storage.borrowBackingArray +import com.eignex.util.collections.storage.forEachSlot +import com.eignex.util.collections.storage.forEachValueSlot +import com.eignex.util.collections.storage.primitiveCapacityBytes +import com.eignex.util.collections.storage.referenceCapacity import com.eignex.util.collections.toSortedIntArray import com.eignex.util.concurrent.AdderCounters import com.eignex.util.concurrent.AtomicCells @@ -21,21 +30,40 @@ import com.eignex.util.io.openTextFile import com.eignex.util.io.readText import com.eignex.util.io.useSource import com.eignex.util.numbers.* -import com.eignex.util.platform.HeapSample -import com.eignex.util.platform.compilationTimeMillis -import com.eignex.util.platform.identityHash -import com.eignex.util.platform.sampleHeap -import com.eignex.util.platform.startHeapPeakSampler import com.eignex.util.process.exitProcess import com.eignex.util.process.flushStandardOutput import com.eignex.util.process.printErrorLine import com.eignex.util.process.processProperty +import com.eignex.util.runtime.diagnostics.HeapSample +import com.eignex.util.runtime.diagnostics.compilationTimeMillis +import com.eignex.util.runtime.diagnostics.sampleHeap +import com.eignex.util.runtime.diagnostics.startHeapPeakSampler +import com.eignex.util.runtime.identityHash internal class CommonConsumer { private val lock = Mutex() private val counter = AdderCounters.newLong() private val first = AtomicCells.newReference(null) + fun firstStoredKey(): Int { + val set = IntHashSet().apply { add(42) } + set.forEachSlot { occupied, key -> if (occupied) return key } + return -1 + } + + fun inspectStorage(): Long { + val list = IntArrayList(1).apply { add(3) } + list.borrowBackingArray()[0] = 9 + check(list[0] == 9) + val map = MutableIntObjectMap(0).apply { put(1, null) } + var slots = 0 + map.forEachValueSlot { slots++ } + check(slots == map.referenceCapacity) + val prepared = checkNotNull(prepareIntSwapSet(4, 2).last()) + check(prepared.add(3)) + return list.primitiveCapacityBytes + map.primitiveCapacityBytes + } + fun sortedElements(): IntArray { val values = intArrayOf(3, 1, 3) val collection = object : IntIndexedCollection { diff --git a/tests/common-main/src/commonTest/kotlin/com/eignex/util/consumer/CommonConsumerTest.kt b/tests/common-main/src/commonTest/kotlin/com/eignex/util/consumer/CommonConsumerTest.kt index af16d1b..bf57ce4 100644 --- a/tests/common-main/src/commonTest/kotlin/com/eignex/util/consumer/CommonConsumerTest.kt +++ b/tests/common-main/src/commonTest/kotlin/com/eignex/util/consumer/CommonConsumerTest.kt @@ -7,6 +7,13 @@ import kotlin.test.assertFalse import kotlin.test.assertTrue class CommonConsumerTest { + @Test + fun `storage and cooperative extensions are usable across modules`() { + val consumer = CommonConsumer() + assertEquals(42, consumer.firstStoredKey()) + assertEquals(44L, consumer.inspectStorage()) + } + @Test fun `fixed and dynamic bitsets share contracts across modules`() { assertContentEquals(BooleanArray(130) { it == 129 }, CommonConsumer().dynamicHeader()) diff --git a/util-bench/src/main/java/com/eignex/util/bench/Workloads.java b/util-bench/src/main/java/com/eignex/util/bench/Workloads.java index e7c5c34..51eb94b 100644 --- a/util-bench/src/main/java/com/eignex/util/bench/Workloads.java +++ b/util-bench/src/main/java/com/eignex/util/bench/Workloads.java @@ -596,7 +596,7 @@ private static Fixture intList(Data d, String op) { for (int i : d.order) { int old = list.get(i), last = list.last(); sum += old; - list.removeAt(i); + list.removeAtSwap(i); if (i < list.getSize()) list.set(i, old); list.add(last); } @@ -635,7 +635,7 @@ private static Fixture longList(Data d, String op) { for (int i : d.order) { long old = list.get(i), last = list.last(); sum += old; - list.removeAt(i); + list.removeAtSwap(i); if (i < list.getSize()) list.set(i, old); list.add(last); }