From c8a25ce54456135cfb0c5257cdade19da18a6200 Mon Sep 17 00:00:00 2001 From: InsanusMokrassar Date: Fri, 18 Jun 2021 13:05:45 +0600 Subject: [PATCH 1/5] start 0.5.13 --- CHANGELOG.md | 2 ++ gradle.properties | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7cb0d97306a..0fc94989c88 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ # Changelog +## 0.5.13 + ## 0.5.12 * `Common`: diff --git a/gradle.properties b/gradle.properties index f6220a8c7ae..b853266f659 100644 --- a/gradle.properties +++ b/gradle.properties @@ -45,5 +45,5 @@ dokka_version=1.4.32 # Project data group=dev.inmo -version=0.5.12 -android_code_version=53 +version=0.5.13 +android_code_version=54 From 11b0d059bf3bc97838b0fdf3778cfc1f305f7c69 Mon Sep 17 00:00:00 2001 From: InsanusMokrassar Date: Sat, 19 Jun 2021 14:41:29 +0600 Subject: [PATCH 2/5] start add fsm --- fsm/common/build.gradle | 17 ++++ .../dev/inmo/micro_utils/fsm/common/State.kt | 5 + .../fsm/common/StateHandlerHolder.kt | 15 +++ .../micro_utils/fsm/common/StatesHandler.kt | 5 + .../micro_utils/fsm/common/StatesMachine.kt | 46 ++++++++++ .../micro_utils/fsm/common/StatesManager.kt | 92 +++++++++++++++++++ .../micro_utils/fsm/common/dsl/FSMBuilder.kt | 35 +++++++ fsm/common/src/jvmTest/kotlin/PlayableMain.kt | 53 +++++++++++ fsm/common/src/main/AndroidManifest.xml | 1 + fsm/repos/build.gradle | 18 ++++ .../fsm/repos/KeyValueBasedStatesManager.kt | 84 +++++++++++++++++ fsm/repos/src/main/AndroidManifest.xml | 1 + settings.gradle | 3 + 13 files changed, 375 insertions(+) create mode 100644 fsm/common/build.gradle create mode 100644 fsm/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/common/State.kt create mode 100644 fsm/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/common/StateHandlerHolder.kt create mode 100644 fsm/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/common/StatesHandler.kt create mode 100644 fsm/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/common/StatesMachine.kt create mode 100644 fsm/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/common/StatesManager.kt create mode 100644 fsm/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/common/dsl/FSMBuilder.kt create mode 100644 fsm/common/src/jvmTest/kotlin/PlayableMain.kt create mode 100644 fsm/common/src/main/AndroidManifest.xml create mode 100644 fsm/repos/build.gradle create mode 100644 fsm/repos/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/repos/KeyValueBasedStatesManager.kt create mode 100644 fsm/repos/src/main/AndroidManifest.xml diff --git a/fsm/common/build.gradle b/fsm/common/build.gradle new file mode 100644 index 00000000000..854f51c5dfb --- /dev/null +++ b/fsm/common/build.gradle @@ -0,0 +1,17 @@ +plugins { + id "org.jetbrains.kotlin.multiplatform" + id "org.jetbrains.kotlin.plugin.serialization" + id "com.android.library" +} + +apply from: "$mppProjectWithSerializationPresetPath" + +kotlin { + sourceSets { + commonMain { + dependencies { + api project(":micro_utils.coroutines") + } + } + } +} diff --git a/fsm/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/common/State.kt b/fsm/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/common/State.kt new file mode 100644 index 00000000000..818c15f0a35 --- /dev/null +++ b/fsm/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/common/State.kt @@ -0,0 +1,5 @@ +package dev.inmo.micro_utils.fsm.common + +interface State { + val context: Any +} diff --git a/fsm/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/common/StateHandlerHolder.kt b/fsm/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/common/StateHandlerHolder.kt new file mode 100644 index 00000000000..5b06f317c16 --- /dev/null +++ b/fsm/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/common/StateHandlerHolder.kt @@ -0,0 +1,15 @@ +package dev.inmo.micro_utils.fsm.common + +import kotlin.reflect.KClass + +class StateHandlerHolder( + private val inputKlass: KClass, + private val strict: Boolean = false, + private val delegateTo: StatesHandler +) : StatesHandler { + fun checkHandleable(state: State) = state::class == inputKlass || (!strict && inputKlass.isInstance(state)) + + override suspend fun StatesMachine.handleState(state: State): State? { + return delegateTo.run { handleState(state as I) } + } +} diff --git a/fsm/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/common/StatesHandler.kt b/fsm/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/common/StatesHandler.kt new file mode 100644 index 00000000000..b152b38dea6 --- /dev/null +++ b/fsm/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/common/StatesHandler.kt @@ -0,0 +1,5 @@ +package dev.inmo.micro_utils.fsm.common + +fun interface StatesHandler { + suspend fun StatesMachine.handleState(state: I): State? +} diff --git a/fsm/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/common/StatesMachine.kt b/fsm/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/common/StatesMachine.kt new file mode 100644 index 00000000000..5c2ea9592d9 --- /dev/null +++ b/fsm/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/common/StatesMachine.kt @@ -0,0 +1,46 @@ +package dev.inmo.micro_utils.fsm.common + +import dev.inmo.micro_utils.coroutines.* +import kotlinx.coroutines.* +import kotlinx.coroutines.flow.asFlow + +private suspend fun StatesMachine.launchStateHandling( + state: State, + handlers: List> +): State? { + return handlers.firstOrNull { it.checkHandleable(state) } ?.run { + handleState(state) + } +} + +class StatesMachine ( + private val statesManager: StatesManager, + private val handlers: List> +) : StatesHandler { + override suspend fun StatesMachine.handleState(state: State): State? = launchStateHandling(state, handlers) + + fun start(scope: CoroutineScope): Job = scope.launchSafelyWithoutExceptions { + val statePerformer: suspend (State) -> Unit = { state: State -> + val newState = launchStateHandling(state, handlers) + if (newState != null) { + statesManager.update(state, newState) + } else { + statesManager.endChain(state) + } + } + statesManager.onStartChain.subscribeSafelyWithoutExceptions(this) { + launch { statePerformer(it) } + } + statesManager.onChainStateUpdated.subscribeSafelyWithoutExceptions(this) { + launch { statePerformer(it.second) } + } + + statesManager.getActiveStates().forEach { + launch { statePerformer(it) } + } + } + + suspend fun startChain(state: State) { + statesManager.startChain(state) + } +} diff --git a/fsm/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/common/StatesManager.kt b/fsm/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/common/StatesManager.kt new file mode 100644 index 00000000000..ac52d84b6e8 --- /dev/null +++ b/fsm/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/common/StatesManager.kt @@ -0,0 +1,92 @@ +package dev.inmo.micro_utils.fsm.common + +import kotlinx.coroutines.flow.* +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +interface StatesManager { + val onChainStateUpdated: Flow> + val onStartChain: Flow + val onEndChain: Flow + + + /** + * Must set current set using [State.context] + */ + suspend fun update(old: State, new: State) + + /** + * Starts chain with [state] as first [State]. May returns false in case of [State.context] of [state] is already + * busy by the other [State] + */ + suspend fun startChain(state: State) + + /** + * Ends chain with context from [state]. In case when [State.context] of [state] is absent, [state] should be just + * ignored + */ + suspend fun endChain(state: State) + + suspend fun getActiveStates(): List +} + +/** + * @param onContextsConflictResolver Receive old [State], new one and the state currently placed on new [State.context] + * key. In case when this callback will returns true, the state placed on [State.context] of new will be replaced by + * new state by using [endChain] with that state + */ +class InMemoryStatesManager( + private val onContextsConflictResolver: suspend (old: State, new: State, currentNew: State) -> Boolean = { _, _, _ -> true } +) : StatesManager { + private val _onChainStateUpdated = MutableSharedFlow>(0) + override val onChainStateUpdated: Flow> = _onChainStateUpdated.asSharedFlow() + private val _onStartChain = MutableSharedFlow(0) + override val onStartChain: Flow = _onStartChain.asSharedFlow() + private val _onEndChain = MutableSharedFlow(0) + override val onEndChain: Flow = _onEndChain.asSharedFlow() + + private val contextsToStates = mutableMapOf() + private val mapMutex = Mutex() + + override suspend fun update(old: State, new: State) = mapMutex.withLock { + when { + contextsToStates[old.context] != old -> return@withLock + old.context == new.context || !contextsToStates.containsKey(new.context) -> { + contextsToStates[old.context] = new + _onChainStateUpdated.emit(old to new) + } + else -> { + val stateOnNewOneContext = contextsToStates.getValue(new.context) + if (onContextsConflictResolver(old, new, stateOnNewOneContext)) { + endChainWithoutLock(stateOnNewOneContext) + contextsToStates.remove(old.context) + contextsToStates[new.context] = new + _onChainStateUpdated.emit(old to new) + } + } + } + } + + override suspend fun startChain(state: State) = mapMutex.withLock { + if (!contextsToStates.containsKey(state.context)) { + contextsToStates[state.context] = state + _onStartChain.emit(state) + } + } + + private suspend fun endChainWithoutLock(state: State) { + if (contextsToStates[state.context] == state) { + contextsToStates.remove(state.context) + _onEndChain.emit(state) + } + } + + override suspend fun endChain(state: State) { + mapMutex.withLock { + endChainWithoutLock(state) + } + } + + override suspend fun getActiveStates(): List = contextsToStates.values.toList() + +} diff --git a/fsm/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/common/dsl/FSMBuilder.kt b/fsm/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/common/dsl/FSMBuilder.kt new file mode 100644 index 00000000000..f0694f360ef --- /dev/null +++ b/fsm/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/common/dsl/FSMBuilder.kt @@ -0,0 +1,35 @@ +package dev.inmo.micro_utils.fsm.common.dsl + +import dev.inmo.micro_utils.fsm.common.* +import kotlin.reflect.KClass + +class FSMBuilder( + var statesManager: StatesManager = InMemoryStatesManager() +) { + private var states = mutableListOf>() + + fun add(kClass: KClass, handler: StatesHandler) { + states.add(StateHandlerHolder(kClass, false, handler)) + } + + fun addStrict(kClass: KClass, handler: StatesHandler) { + states.add(StateHandlerHolder(kClass, true, handler)) + } + + fun build() = StatesMachine( + statesManager, + states.toList() + ) +} + +inline fun FSMBuilder.onStateOrSubstate(handler: StatesHandler) { + add(I::class, handler) +} + +inline fun FSMBuilder.strictlyOn(handler: StatesHandler) { + addStrict(I::class, handler) +} + +fun buildFSM( + block: FSMBuilder.() -> Unit +): StatesMachine = FSMBuilder().apply(block).build() diff --git a/fsm/common/src/jvmTest/kotlin/PlayableMain.kt b/fsm/common/src/jvmTest/kotlin/PlayableMain.kt new file mode 100644 index 00000000000..a317c2a5f17 --- /dev/null +++ b/fsm/common/src/jvmTest/kotlin/PlayableMain.kt @@ -0,0 +1,53 @@ +import dev.inmo.micro_utils.fsm.common.* +import dev.inmo.micro_utils.fsm.common.dsl.buildFSM +import dev.inmo.micro_utils.fsm.common.dsl.strictlyOn +import kotlinx.coroutines.* + +sealed interface TrafficLightState : State { + val trafficLightNumber: Int + override val context: Int + get() = trafficLightNumber +} +data class GreenCommon(override val trafficLightNumber: Int) : TrafficLightState +data class YellowCommon(override val trafficLightNumber: Int) : TrafficLightState +data class RedCommon(override val trafficLightNumber: Int) : TrafficLightState + +class PlayableMain { +// @Test + fun test() { + runBlocking { + val countOfTrafficLights = 10 + val initialStates = (0 until countOfTrafficLights).map { + when (0/*Random.nextInt(3)*/) { + 0 -> GreenCommon(it) + 1 -> YellowCommon(it) + else -> RedCommon(it) + } + } + + val statesManager = InMemoryStatesManager() + + val machine = buildFSM { + strictlyOn { + delay(1000L) + YellowCommon(it.context).also(::println) + } + strictlyOn { + delay(1000L) + RedCommon(it.context).also(::println) + } + strictlyOn { + delay(1000L) + GreenCommon(it.context).also(::println) + } + this.statesManager = statesManager + } + + initialStates.forEach { machine.startChain(it) } + + val scope = CoroutineScope(Dispatchers.Default) + machine.start(scope).join() + + } + } +} diff --git a/fsm/common/src/main/AndroidManifest.xml b/fsm/common/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..2a1eb7f83d7 --- /dev/null +++ b/fsm/common/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/fsm/repos/build.gradle b/fsm/repos/build.gradle new file mode 100644 index 00000000000..d20bb3f38a4 --- /dev/null +++ b/fsm/repos/build.gradle @@ -0,0 +1,18 @@ +plugins { + id "org.jetbrains.kotlin.multiplatform" + id "org.jetbrains.kotlin.plugin.serialization" + id "com.android.library" +} + +apply from: "$mppProjectWithSerializationPresetPath" + +kotlin { + sourceSets { + commonMain { + dependencies { + api project(":micro_utils.fsm.common") + api project(":micro_utils.repos.common") + } + } + } +} diff --git a/fsm/repos/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/repos/KeyValueBasedStatesManager.kt b/fsm/repos/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/repos/KeyValueBasedStatesManager.kt new file mode 100644 index 00000000000..e53b8cee51d --- /dev/null +++ b/fsm/repos/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/repos/KeyValueBasedStatesManager.kt @@ -0,0 +1,84 @@ +package dev.inmo.micro_utils.fsm.repos + +import dev.inmo.micro_utils.fsm.common.State +import dev.inmo.micro_utils.fsm.common.StatesManager +import dev.inmo.micro_utils.repos.* +import dev.inmo.micro_utils.repos.mappers.withMapper +import dev.inmo.micro_utils.repos.pagination.getAll +import kotlinx.coroutines.flow.* +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlin.reflect.KClass + +class KeyValueBasedStatesManager( + private val keyValueRepo: KeyValueRepo, + private val onContextsConflictResolver: suspend (old: State, new: State, currentNew: State) -> Boolean = { _, _, _ -> true } +) : StatesManager { + private val _onChainStateUpdated = MutableSharedFlow>(0) + override val onChainStateUpdated: Flow> = _onChainStateUpdated.asSharedFlow() + private val _onEndChain = MutableSharedFlow(0) + override val onEndChain: Flow = _onEndChain.asSharedFlow() + + override val onStartChain: Flow = keyValueRepo.onNewValue.map { it.second } + + private val mutex = Mutex() + + override suspend fun update(old: State, new: State) { + mutex.withLock { + when { + keyValueRepo.get(old.context) != old -> return@withLock + old.context == new.context || !keyValueRepo.contains(new.context) -> { + keyValueRepo.set(old.context, new) + _onChainStateUpdated.emit(old to new) + } + else -> { + val stateOnNewOneContext = keyValueRepo.get(new.context)!! + if (onContextsConflictResolver(old, new, stateOnNewOneContext)) { + endChainWithoutLock(stateOnNewOneContext) + keyValueRepo.unset(old.context) + keyValueRepo.set(new.context, new) + _onChainStateUpdated.emit(old to new) + } + } + } + + } + } + + override suspend fun startChain(state: State) { + if (!keyValueRepo.contains(state.context)) { + keyValueRepo.set(state.context, state) + } + } + + private suspend fun endChainWithoutLock(state: State) { + if (keyValueRepo.get(state.context) == state) { + keyValueRepo.unset(state.context) + _onEndChain.emit(state) + } + } + + override suspend fun endChain(state: State) { + mutex.withLock { endChainWithoutLock(state) } + } + + override suspend fun getActiveStates(): List { + return keyValueRepo.getAll { keys(it) }.map { it.second } + } + +} + +inline fun createStatesManager( + targetKeyValueRepo: KeyValueRepo, + noinline contextToOutTransformer: suspend Any.() -> TargetContextType, + noinline stateToOutTransformer: suspend State.() -> TargetStateType, + noinline outToContextTransformer: suspend TargetContextType.() -> Any, + noinline outToStateTransformer: suspend TargetStateType.() -> State, +) = KeyValueBasedStatesManager( + targetKeyValueRepo.withMapper( + contextToOutTransformer, + stateToOutTransformer, + outToContextTransformer, + outToStateTransformer + ) +) diff --git a/fsm/repos/src/main/AndroidManifest.xml b/fsm/repos/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..adc2fba3383 --- /dev/null +++ b/fsm/repos/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/settings.gradle b/settings.gradle index 1cdf43a6d64..805e1437532 100644 --- a/settings.gradle +++ b/settings.gradle @@ -28,6 +28,9 @@ String[] includes = [ ":serialization:encapsulator", ":serialization:typed_serializer", + ":fsm:common", + ":fsm:repos", + ":dokka" ] From 19ea2f340a97c3592b5dc459503e60faddaf363b Mon Sep 17 00:00:00 2001 From: InsanusMokrassar Date: Sun, 20 Jun 2021 17:11:51 +0600 Subject: [PATCH 3/5] replace repos common extension for fsm --- fsm/repos/{ => common}/build.gradle | 0 .../fsm/repos/common}/KeyValueBasedStatesManager.kt | 3 +-- fsm/repos/common/src/main/AndroidManifest.xml | 1 + fsm/repos/src/main/AndroidManifest.xml | 1 - settings.gradle | 2 +- 5 files changed, 3 insertions(+), 4 deletions(-) rename fsm/repos/{ => common}/build.gradle (100%) rename fsm/repos/{src/commonMain/kotlin/dev/inmo/micro_utils/fsm/repos => common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/repos/common}/KeyValueBasedStatesManager.kt (97%) create mode 100644 fsm/repos/common/src/main/AndroidManifest.xml delete mode 100644 fsm/repos/src/main/AndroidManifest.xml diff --git a/fsm/repos/build.gradle b/fsm/repos/common/build.gradle similarity index 100% rename from fsm/repos/build.gradle rename to fsm/repos/common/build.gradle diff --git a/fsm/repos/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/repos/KeyValueBasedStatesManager.kt b/fsm/repos/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/repos/common/KeyValueBasedStatesManager.kt similarity index 97% rename from fsm/repos/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/repos/KeyValueBasedStatesManager.kt rename to fsm/repos/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/repos/common/KeyValueBasedStatesManager.kt index e53b8cee51d..4f6f98d536c 100644 --- a/fsm/repos/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/repos/KeyValueBasedStatesManager.kt +++ b/fsm/repos/common/src/commonMain/kotlin/dev/inmo/micro_utils/fsm/repos/common/KeyValueBasedStatesManager.kt @@ -1,4 +1,4 @@ -package dev.inmo.micro_utils.fsm.repos +package dev.inmo.micro_utils.fsm.repos.common import dev.inmo.micro_utils.fsm.common.State import dev.inmo.micro_utils.fsm.common.StatesManager @@ -8,7 +8,6 @@ import dev.inmo.micro_utils.repos.pagination.getAll import kotlinx.coroutines.flow.* import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock -import kotlin.reflect.KClass class KeyValueBasedStatesManager( private val keyValueRepo: KeyValueRepo, diff --git a/fsm/repos/common/src/main/AndroidManifest.xml b/fsm/repos/common/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..d0773843842 --- /dev/null +++ b/fsm/repos/common/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/fsm/repos/src/main/AndroidManifest.xml b/fsm/repos/src/main/AndroidManifest.xml deleted file mode 100644 index adc2fba3383..00000000000 --- a/fsm/repos/src/main/AndroidManifest.xml +++ /dev/null @@ -1 +0,0 @@ - diff --git a/settings.gradle b/settings.gradle index 805e1437532..7fcae92134f 100644 --- a/settings.gradle +++ b/settings.gradle @@ -29,7 +29,7 @@ String[] includes = [ ":serialization:typed_serializer", ":fsm:common", - ":fsm:repos", + ":fsm:repos:common", ":dokka" ] From b420d85be553896fb465d03acdf99c9ca97a90bf Mon Sep 17 00:00:00 2001 From: InsanusMokrassar Date: Tue, 22 Jun 2021 13:36:23 +0600 Subject: [PATCH 4/5] MPPFile --- CHANGELOG.md | 5 +++ common/build.gradle | 15 +++++++++ .../inmo/micro_utils/common/InputAllocator.kt | 10 +++++- .../dev/inmo/micro_utils/common/MPPFile.kt | 31 ++++++++++++++++++ .../dev/inmo/micro_utils/common/JSMPPFile.kt | 32 +++++++++++++++++++ .../inmo/micro_utils/common/PromiseAwait.kt | 8 +++++ .../dev/inmo/micro_utils/common/JVMMPPFile.kt | 20 ++++++++++++ 7 files changed, 120 insertions(+), 1 deletion(-) create mode 100644 common/src/commonMain/kotlin/dev/inmo/micro_utils/common/MPPFile.kt create mode 100644 common/src/jsMain/kotlin/dev/inmo/micro_utils/common/JSMPPFile.kt create mode 100644 common/src/jsMain/kotlin/dev/inmo/micro_utils/common/PromiseAwait.kt create mode 100644 common/src/jvmMain/kotlin/dev/inmo/micro_utils/common/JVMMPPFile.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 0fc94989c88..3bf3d09ab56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## 0.5.13 +* `Common`: + * Add functionality for multiplatform working with files: + * Main class for files `MPPFile` + * Inline class for filenames work encapsulation `FileName` + ## 0.5.12 * `Common`: diff --git a/common/build.gradle b/common/build.gradle index 7c54502f100..14324f2f227 100644 --- a/common/build.gradle +++ b/common/build.gradle @@ -5,3 +5,18 @@ plugins { } apply from: "$mppProjectWithSerializationPresetPath" + +kotlin { + sourceSets { + jvmMain { + dependencies { + api project(":micro_utils.coroutines") + } + } + androidMain { + dependencies { + api project(":micro_utils.coroutines") + } + } + } +} diff --git a/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/InputAllocator.kt b/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/InputAllocator.kt index 2fd48505694..b33b406805d 100644 --- a/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/InputAllocator.kt +++ b/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/InputAllocator.kt @@ -7,9 +7,17 @@ import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder typealias ByteArrayAllocator = () -> ByteArray +typealias SuspendByteArrayAllocator = suspend () -> ByteArray val ByteArray.asAllocator: ByteArrayAllocator get() = { this } +val ByteArray.asSuspendAllocator: SuspendByteArrayAllocator + get() = { this } +val ByteArrayAllocator.asSuspendAllocator: SuspendByteArrayAllocator + get() = { this() } +suspend fun SuspendByteArrayAllocator.asAllocator(): ByteArrayAllocator { + return invoke().asAllocator +} object ByteArrayAllocatorSerializer : KSerializer { private val realSerializer = ByteArraySerializer() @@ -17,7 +25,7 @@ object ByteArrayAllocatorSerializer : KSerializer { override fun deserialize(decoder: Decoder): ByteArrayAllocator { val bytes = realSerializer.deserialize(decoder) - return { bytes } + return bytes.asAllocator } override fun serialize(encoder: Encoder, value: ByteArrayAllocator) { diff --git a/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/MPPFile.kt b/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/MPPFile.kt new file mode 100644 index 00000000000..c60eb0d6b80 --- /dev/null +++ b/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/MPPFile.kt @@ -0,0 +1,31 @@ +package dev.inmo.micro_utils.common + +import kotlinx.serialization.Serializable +import kotlin.jvm.JvmInline + +@Serializable +@JvmInline +value class FileName(val string: String) { + val name: String + get() = string.takeLastWhile { it != '/' } + val extension: String + get() = name.takeLastWhile { it != '.' } + val nameWithoutExtension: String + get() { + val filename = name + return filename.indexOfLast { it == '.' }.takeIf { it > -1 } ?.let { + filename.substring(0, it) + } ?: filename + } + override fun toString(): String = string +} + + +@PreviewFeature +expect class MPPFile + +expect val MPPFile.filename: FileName +expect val MPPFile.filesize: Long +expect val MPPFile.bytesAllocator: SuspendByteArrayAllocator +suspend fun MPPFile.bytes() = bytesAllocator() + diff --git a/common/src/jsMain/kotlin/dev/inmo/micro_utils/common/JSMPPFile.kt b/common/src/jsMain/kotlin/dev/inmo/micro_utils/common/JSMPPFile.kt new file mode 100644 index 00000000000..b163f489506 --- /dev/null +++ b/common/src/jsMain/kotlin/dev/inmo/micro_utils/common/JSMPPFile.kt @@ -0,0 +1,32 @@ +package dev.inmo.micro_utils.common + +import org.khronos.webgl.ArrayBuffer +import org.w3c.dom.ErrorEvent +import org.w3c.files.File +import org.w3c.files.FileReader +import kotlin.js.Promise + +actual typealias MPPFile = File + +fun MPPFile.readBytesPromise() = Promise { success, failure -> + val reader = FileReader() + reader.onload = { + success((reader.result as ArrayBuffer).toByteArray()) + Unit + } + reader.onerror = { + failure(Exception((it as ErrorEvent).message)) + Unit + } + reader.readAsArrayBuffer(this) +} + +private suspend fun MPPFile.dirtyReadBytes(): ByteArray = readBytesPromise().await() + +actual val MPPFile.filename: FileName + get() = FileName(name) +actual val MPPFile.filesize: Long + get() = size.toLong() +@Warning("That is not optimized version of bytes allocator. Use asyncBytesAllocator everywhere you can") +actual val MPPFile.bytesAllocator: SuspendByteArrayAllocator + get() = ::dirtyReadBytes diff --git a/common/src/jsMain/kotlin/dev/inmo/micro_utils/common/PromiseAwait.kt b/common/src/jsMain/kotlin/dev/inmo/micro_utils/common/PromiseAwait.kt new file mode 100644 index 00000000000..6c2f3bfcd16 --- /dev/null +++ b/common/src/jsMain/kotlin/dev/inmo/micro_utils/common/PromiseAwait.kt @@ -0,0 +1,8 @@ +package dev.inmo.micro_utils.common + +import kotlin.coroutines.* +import kotlin.js.Promise + +suspend fun Promise.await(): T = suspendCoroutine { cont -> + then({ cont.resume(it) }, { cont.resumeWithException(it) }) +} diff --git a/common/src/jvmMain/kotlin/dev/inmo/micro_utils/common/JVMMPPFile.kt b/common/src/jvmMain/kotlin/dev/inmo/micro_utils/common/JVMMPPFile.kt new file mode 100644 index 00000000000..770dfc95f7f --- /dev/null +++ b/common/src/jvmMain/kotlin/dev/inmo/micro_utils/common/JVMMPPFile.kt @@ -0,0 +1,20 @@ +package dev.inmo.micro_utils.common + +import dev.inmo.micro_utils.coroutines.doInIO +import dev.inmo.micro_utils.coroutines.doOutsideOfCoroutine +import java.io.File + +actual typealias MPPFile = File + +actual val MPPFile.filename: FileName + get() = FileName(name) +actual val MPPFile.filesize: Long + get() = length() +actual val MPPFile.bytesAllocator: SuspendByteArrayAllocator + get() = { + doInIO { + doOutsideOfCoroutine { + readBytes() + } + } + } From 39895e58a60432bf769c5a9e6d1561f0ab66c016 Mon Sep 17 00:00:00 2001 From: InsanusMokrassar Date: Wed, 23 Jun 2021 21:29:28 +0600 Subject: [PATCH 5/5] changelog upsert --- CHANGELOG.md | 2 ++ .../serialization/typed_serializer/TypedSerializer.kt | 6 +++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3bf3d09ab56..892f2c75e66 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ * Add functionality for multiplatform working with files: * Main class for files `MPPFile` * Inline class for filenames work encapsulation `FileName` +* `FSM` + * Module inited and in preview state ## 0.5.12 diff --git a/serialization/typed_serializer/src/commonMain/kotlin/dev/inmo/micro_utils/serialization/typed_serializer/TypedSerializer.kt b/serialization/typed_serializer/src/commonMain/kotlin/dev/inmo/micro_utils/serialization/typed_serializer/TypedSerializer.kt index d1f75914f4c..9a54292e629 100644 --- a/serialization/typed_serializer/src/commonMain/kotlin/dev/inmo/micro_utils/serialization/typed_serializer/TypedSerializer.kt +++ b/serialization/typed_serializer/src/commonMain/kotlin/dev/inmo/micro_utils/serialization/typed_serializer/TypedSerializer.kt @@ -12,7 +12,7 @@ open class TypedSerializer( ) : KSerializer { protected val serializers = presetSerializers.toMutableMap() @InternalSerializationApi - override open val descriptor: SerialDescriptor = buildSerialDescriptor( + open override val descriptor: SerialDescriptor = buildSerialDescriptor( "TextSourceSerializer", SerialKind.CONTEXTUAL ) { @@ -21,7 +21,7 @@ open class TypedSerializer( } @InternalSerializationApi - override open fun deserialize(decoder: Decoder): T { + open override fun deserialize(decoder: Decoder): T { return decoder.decodeStructure(descriptor) { var type: String? = null lateinit var result: T @@ -50,7 +50,7 @@ open class TypedSerializer( } @InternalSerializationApi - override open fun serialize(encoder: Encoder, value: T) { + open override fun serialize(encoder: Encoder, value: T) { encoder.encodeStructure(descriptor) { val valueSerializer = value::class.serializer() val type = serializers.keys.first { serializers[it] == valueSerializer }