Compare commits

...

57 Commits

Author SHA1 Message Date
7feac213f6 update android code version 2024-08-11 16:51:09 +06:00
c75a9c0f61 update dependencies 2024-08-11 16:44:08 +06:00
afd0c9784f Update libs.versions.toml 2024-08-11 12:41:30 +06:00
f1ddbea06e update android version 2024-08-09 23:06:50 +06:00
42bf3cd4e3 update kotlin-poet 2024-08-09 22:21:53 +06:00
27f5549f56 improve tests of repos 2024-08-09 21:58:09 +06:00
b0569f8421 add tests for cruds 2024-08-09 19:22:32 +06:00
8d86f29325 Revert "small change in FullKeyValuesCacheRepoTests and FullKeyValueCacheRepoTests"
This reverts commit 3db8d2291e.
2024-08-07 16:50:13 +06:00
aeca32498a Revert "Update build.yml"
This reverts commit ab0b3a8f0d.
2024-08-07 16:50:13 +06:00
e8232664f3 update delay on creating tests in cache 2024-08-07 16:50:13 +06:00
efa869f91a Update build.yml 2024-08-07 16:50:13 +06:00
dbff3d7cf1 small change in FullKeyValuesCacheRepoTests and FullKeyValueCacheRepoTests 2024-08-07 16:50:13 +06:00
9e70f73684 upgrade kotlin 2024-08-07 16:50:13 +06:00
9f2f0de0c4 add check of emptiness in map reslozations of KV/KVs repos 2024-08-07 16:50:13 +06:00
bf293a8f8f fix of tests 2024-08-07 16:50:13 +06:00
5fbc1a132f improvements in SmartRWLocker and breaking of FullKeyValueCacheRepo tests 2024-08-07 16:50:13 +06:00
36093b9741 fix of full caches initial actualization and realize MapKeyValuesRepo methods getAll 2024-08-07 16:50:13 +06:00
8713fb04c5 small change in MapWriteKeyValuesRepo.set and remove duration of FullKeyValuesCacheRepoTests.creatingWorksProperly 2024-08-07 16:50:13 +06:00
ea82a59f31 update gradle wrapper version 2024-08-07 16:50:13 +06:00
18f67cd4f2 small improvement of test data in Full Cache tests 2024-08-07 16:50:13 +06:00
120e7228c7 add FullKeyValuesCacheRepoTests and small rewrite of MapWriteKeyValuesRepo.set(Map<Key, List<Value>>) function 2024-08-07 16:50:13 +06:00
892fa90c37 start add cache repos tests 2024-08-07 16:50:13 +06:00
491dac5bf0 update exposed 2024-08-07 16:50:13 +06:00
2ab06fbafd change version 2024-08-07 16:50:11 +06:00
e68735d061 Revert "migrations onto new libraries"
This reverts commit 647cd7d7b4.
2024-08-07 16:46:49 +06:00
9ba4d98c30 migrations onto new libraries 2024-08-07 16:46:49 +06:00
19bbfd4916 downgrade kotlin and fix build 2024-08-07 16:46:49 +06:00
d94cd7ea94 some fixes 2024-08-07 16:46:49 +06:00
0dd8f41eb0 update dependencies 2024-08-07 16:46:49 +06:00
f1ab5ab51f update kotlinx serialization 2024-08-07 16:46:49 +06:00
a8056f3120 update dependencies 2024-08-07 16:46:49 +06:00
09c0cdebb5 update dependencies 2024-08-07 16:46:49 +06:00
629d7c7a82 temporal project in upgrade 2024-08-07 16:46:49 +06:00
a0dd1aec3d trying to update to new compose 2024-08-07 16:46:49 +06:00
17d6377902 Merge pull request #466 from InsanusMokrassar/0.21.6
0.21.6
2024-07-26 19:16:13 +06:00
ad401105a1 fixes in ksp sealed generator 2024-07-26 17:17:11 +06:00
4913e99c2e start 0.21.6 2024-07-26 16:40:30 +06:00
16b97029cf Merge pull request #465 from InsanusMokrassar/0.21.5
0.21.5
2024-07-25 02:48:27 +06:00
481130c9bb fill changelog 2024-07-25 02:30:10 +06:00
698ed6718d improve sealed workaround generation 2024-07-25 02:27:33 +06:00
d164813bb4 Revert "start moving to kotlinx-io"
This reverts commit 52157ee0e7.
2024-07-25 01:20:32 +06:00
52157ee0e7 start moving to kotlinx-io 2024-07-24 00:34:49 +06:00
877b62fe5d start 0.21.5 2024-07-24 00:06:18 +06:00
d823a02971 Merge pull request #464 from InsanusMokrassar/0.21.4
add additional targets with natives support
2024-07-16 17:58:02 +06:00
e950056e3b add additional targets with natives support 2024-07-16 17:18:26 +06:00
70014ba233 Merge pull request #463 from InsanusMokrassar/0.21.4
0.21.4
2024-07-16 14:23:41 +06:00
4425f24a20 add support of native platforms in common compose and coroutines compose 2024-07-16 14:16:08 +06:00
410964a44b start 0.21.4 2024-07-16 14:02:36 +06:00
30389e8536 Merge pull request #462 from InsanusMokrassar/0.21.3
0.21.3
2024-07-15 16:33:28 +06:00
5314833041 fix of #374 2024-07-15 08:43:23 +06:00
40f7cf7678 Color as a module 2024-07-15 08:13:23 +06:00
83a0b07062 start 0.21.3 2024-07-15 08:05:08 +06:00
1b4900d691 Merge pull request #461 from InsanusMokrassar/0.21.2
0.21.2
2024-06-30 22:56:52 +06:00
f9795d53a0 improve classcasts 2024-06-30 22:55:28 +06:00
2b9bb4f141 add ClassCasts generator 2024-06-30 20:56:54 +06:00
9196e4c367 start 0.21.2 2024-06-30 20:40:12 +06:00
374a5a1a37 Merge pull request #460 from InsanusMokrassar/0.21.1
0.21.1
2024-06-25 22:11:26 +06:00
89 changed files with 6697 additions and 2996 deletions

2
.gitignore vendored
View File

@@ -1,4 +1,5 @@
.idea
.kotlin
out/*
*.iml
target
@@ -17,5 +18,6 @@ publishing.sh
local.*
local/
**/*.local.*
.kotlin/

View File

@@ -1,5 +1,62 @@
# Changelog
## 0.22.0
**THIS UPDATE CONTAINS BREAKING CHANGES ACCORDING TO UPDATE UP TO KOTLIN 2.0**
* `Versions`:
* `Kotlin`: `1.9.23` -> `2.0.10`
* `Serialization`: `1.6.3` -> `1.7.1`
* `KSLog`: `1.3.4` -> `1.3.5`
* `Compose`: `1.6.2` -> `1.7.0-alpha02`
* `Exposed`: `0.50.1` -> `0.53.0`
* `AndroidAppCompat`: `1.6.1` -> `1.7.0`
* `AndroidFragment`: `1.7.1` -> `1.8.2`
## 0.21.6
* `KSP`:
* `Sealed`:
* Fixes in generation
## 0.21.5
* `KSP`:
* Add utility functions `KSClassDeclaration.findSubClasses`
* `Sealed`:
* Improve generation
## 0.21.4
* `Common`:
* `Compose`:
* Add support of mingw, linux, arm64 targets
* `Coroutines`:
* `Compose`:
* Add support of mingw, linux, arm64 targets
* `Koin`:
* Add support of mingw, linux, arm64 targets
* `KSP`:
* `ClassCasts`:
* Add support of mingw, linux, arm64 targets
* `Sealed`:
* Add support of mingw, linux, arm64 targets
## 0.21.3
* `Colors`:
* Added as a module. It should be used by default in case you wish all the API currently realized for `HEXAColor`
* `Coroutines`:
* Fix of [#374](https://github.com/InsanusMokrassar/MicroUtils/issues/374):
* Add vararg variants of `awaitFirst`
* Add `joinFirst`
## 0.21.2
* `KSP`:
* `ClassCasts`:
* Module has been initialized
## 0.21.1
* `KSP`:

View File

@@ -3,6 +3,7 @@ plugins {
id "org.jetbrains.kotlin.plugin.serialization"
id "com.android.library"
alias(libs.plugins.jb.compose)
alias(libs.plugins.kt.jb.compose)
}
apply from: "$mppProjectWithSerializationAndComposePresetPath"

View File

@@ -3,6 +3,7 @@ plugins {
id "org.jetbrains.kotlin.plugin.serialization"
id "com.android.library"
alias(libs.plugins.jb.compose)
alias(libs.plugins.kt.jb.compose)
}
apply from: "$mppProjectWithSerializationAndComposePresetPath"

View File

@@ -29,15 +29,6 @@ allprojects {
maven { url "https://maven.pkg.jetbrains.space/public/p/compose/dev" }
maven { url "https://nexus.inmo.dev/repository/maven-releases/" }
}
// temporal crutch until legacy tests will be stabled or legacy target will be removed
if (it != rootProject.findProject("docs")) {
tasks.whenTaskAdded { task ->
if(task.name == "jsLegacyBrowserTest" || task.name == "jsLegacyNodeTest") {
task.enabled = false
}
}
}
}
apply from: "./extensions.gradle"

17
colors/build.gradle Normal file
View File

@@ -0,0 +1,17 @@
plugins {
id "org.jetbrains.kotlin.multiplatform"
id "org.jetbrains.kotlin.plugin.serialization"
id "com.android.library"
}
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
kotlin {
sourceSets {
commonMain {
dependencies {
api project(":micro_utils.colors.common")
}
}
}
}

View File

@@ -0,0 +1,298 @@
package dev.inmo.micro_utils.colors
import dev.inmo.micro_utils.colors.common.HEXAColor
val HEXAColor.Companion.aliceblue
get() = HEXAColor(0xF0F8FFFFu)
val HEXAColor.Companion.antiquewhite
get() = HEXAColor(0xFAEBD7FFu)
val HEXAColor.Companion.aqua
get() = HEXAColor(0x00FFFFFFu)
val HEXAColor.Companion.aquamarine
get() = HEXAColor(0x7FFFD4FFu)
val HEXAColor.Companion.azure
get() = HEXAColor(0xF0FFFFFFu)
val HEXAColor.Companion.beige
get() = HEXAColor(0xF5F5DCFFu)
val HEXAColor.Companion.bisque
get() = HEXAColor(0xFFE4C4FFu)
val HEXAColor.Companion.black
get() = HEXAColor(0x000000FFu)
val HEXAColor.Companion.blanchedalmond
get() = HEXAColor(0xFFEBCDFFu)
val HEXAColor.Companion.blue
get() = HEXAColor(0x0000FFFFu)
val HEXAColor.Companion.blueviolet
get() = HEXAColor(0x8A2BE2FFu)
val HEXAColor.Companion.brown
get() = HEXAColor(0xA52A2AFFu)
val HEXAColor.Companion.burlywood
get() = HEXAColor(0xDEB887FFu)
val HEXAColor.Companion.cadetblue
get() = HEXAColor(0x5F9EA0FFu)
val HEXAColor.Companion.chartreuse
get() = HEXAColor(0x7FFF00FFu)
val HEXAColor.Companion.chocolate
get() = HEXAColor(0xD2691EFFu)
val HEXAColor.Companion.coral
get() = HEXAColor(0xFF7F50FFu)
val HEXAColor.Companion.cornflowerblue
get() = HEXAColor(0x6495EDFFu)
val HEXAColor.Companion.cornsilk
get() = HEXAColor(0xFFF8DCFFu)
val HEXAColor.Companion.crimson
get() = HEXAColor(0xDC143CFFu)
val HEXAColor.Companion.cyan
get() = HEXAColor(0x00FFFFFFu)
val HEXAColor.Companion.darkblue
get() = HEXAColor(0x00008BFFu)
val HEXAColor.Companion.darkcyan
get() = HEXAColor(0x008B8BFFu)
val HEXAColor.Companion.darkgoldenrod
get() = HEXAColor(0xB8860BFFu)
val HEXAColor.Companion.darkgray
get() = HEXAColor(0xA9A9A9FFu)
val HEXAColor.Companion.darkgreen
get() = HEXAColor(0x006400FFu)
val HEXAColor.Companion.darkgrey
get() = HEXAColor(0xA9A9A9FFu)
val HEXAColor.Companion.darkkhaki
get() = HEXAColor(0xBDB76BFFu)
val HEXAColor.Companion.darkmagenta
get() = HEXAColor(0x8B008BFFu)
val HEXAColor.Companion.darkolivegreen
get() = HEXAColor(0x556B2FFFu)
val HEXAColor.Companion.darkorange
get() = HEXAColor(0xFF8C00FFu)
val HEXAColor.Companion.darkorchid
get() = HEXAColor(0x9932CCFFu)
val HEXAColor.Companion.darkred
get() = HEXAColor(0x8B0000FFu)
val HEXAColor.Companion.darksalmon
get() = HEXAColor(0xE9967AFFu)
val HEXAColor.Companion.darkseagreen
get() = HEXAColor(0x8FBC8FFFu)
val HEXAColor.Companion.darkslateblue
get() = HEXAColor(0x483D8BFFu)
val HEXAColor.Companion.darkslategray
get() = HEXAColor(0x2F4F4FFFu)
val HEXAColor.Companion.darkslategrey
get() = HEXAColor(0x2F4F4FFFu)
val HEXAColor.Companion.darkturquoise
get() = HEXAColor(0x00CED1FFu)
val HEXAColor.Companion.darkviolet
get() = HEXAColor(0x9400D3FFu)
val HEXAColor.Companion.deeppink
get() = HEXAColor(0xFF1493FFu)
val HEXAColor.Companion.deepskyblue
get() = HEXAColor(0x00BFFFFFu)
val HEXAColor.Companion.dimgray
get() = HEXAColor(0x696969FFu)
val HEXAColor.Companion.dimgrey
get() = HEXAColor(0x696969FFu)
val HEXAColor.Companion.dodgerblue
get() = HEXAColor(0x1E90FFFFu)
val HEXAColor.Companion.firebrick
get() = HEXAColor(0xB22222FFu)
val HEXAColor.Companion.floralwhite
get() = HEXAColor(0xFFFAF0FFu)
val HEXAColor.Companion.forestgreen
get() = HEXAColor(0x228B22FFu)
val HEXAColor.Companion.fuchsia
get() = HEXAColor(0xFF00FFFFu)
val HEXAColor.Companion.gainsboro
get() = HEXAColor(0xDCDCDCFFu)
val HEXAColor.Companion.ghostwhite
get() = HEXAColor(0xF8F8FFFFu)
val HEXAColor.Companion.gold
get() = HEXAColor(0xFFD700FFu)
val HEXAColor.Companion.goldenrod
get() = HEXAColor(0xDAA520FFu)
val HEXAColor.Companion.gray
get() = HEXAColor(0x808080FFu)
val HEXAColor.Companion.green
get() = HEXAColor(0x008000FFu)
val HEXAColor.Companion.greenyellow
get() = HEXAColor(0xADFF2FFFu)
val HEXAColor.Companion.grey
get() = HEXAColor(0x808080FFu)
val HEXAColor.Companion.honeydew
get() = HEXAColor(0xF0FFF0FFu)
val HEXAColor.Companion.hotpink
get() = HEXAColor(0xFF69B4FFu)
val HEXAColor.Companion.indianred
get() = HEXAColor(0xCD5C5CFFu)
val HEXAColor.Companion.indigo
get() = HEXAColor(0x4B0082FFu)
val HEXAColor.Companion.ivory
get() = HEXAColor(0xFFFFF0FFu)
val HEXAColor.Companion.khaki
get() = HEXAColor(0xF0E68CFFu)
val HEXAColor.Companion.lavender
get() = HEXAColor(0xE6E6FAFFu)
val HEXAColor.Companion.lavenderblush
get() = HEXAColor(0xFFF0F5FFu)
val HEXAColor.Companion.lawngreen
get() = HEXAColor(0x7CFC00FFu)
val HEXAColor.Companion.lemonchiffon
get() = HEXAColor(0xFFFACDFFu)
val HEXAColor.Companion.lightblue
get() = HEXAColor(0xADD8E6FFu)
val HEXAColor.Companion.lightcoral
get() = HEXAColor(0xF08080FFu)
val HEXAColor.Companion.lightcyan
get() = HEXAColor(0xE0FFFFFFu)
val HEXAColor.Companion.lightgoldenrodyellow
get() = HEXAColor(0xFAFAD2FFu)
val HEXAColor.Companion.lightgray
get() = HEXAColor(0xD3D3D3FFu)
val HEXAColor.Companion.lightgreen
get() = HEXAColor(0x90EE90FFu)
val HEXAColor.Companion.lightgrey
get() = HEXAColor(0xD3D3D3FFu)
val HEXAColor.Companion.lightpink
get() = HEXAColor(0xFFB6C1FFu)
val HEXAColor.Companion.lightsalmon
get() = HEXAColor(0xFFA07AFFu)
val HEXAColor.Companion.lightseagreen
get() = HEXAColor(0x20B2AAFFu)
val HEXAColor.Companion.lightskyblue
get() = HEXAColor(0x87CEFAFFu)
val HEXAColor.Companion.lightslategray
get() = HEXAColor(0x778899FFu)
val HEXAColor.Companion.lightslategrey
get() = HEXAColor(0x778899FFu)
val HEXAColor.Companion.lightsteelblue
get() = HEXAColor(0xB0C4DEFFu)
val HEXAColor.Companion.lightyellow
get() = HEXAColor(0xFFFFE0FFu)
val HEXAColor.Companion.lime
get() = HEXAColor(0x00FF00FFu)
val HEXAColor.Companion.limegreen
get() = HEXAColor(0x32CD32FFu)
val HEXAColor.Companion.linen
get() = HEXAColor(0xFAF0E6FFu)
val HEXAColor.Companion.magenta
get() = HEXAColor(0xFF00FFFFu)
val HEXAColor.Companion.maroon
get() = HEXAColor(0x800000FFu)
val HEXAColor.Companion.mediumaquamarine
get() = HEXAColor(0x66CDAAFFu)
val HEXAColor.Companion.mediumblue
get() = HEXAColor(0x0000CDFFu)
val HEXAColor.Companion.mediumorchid
get() = HEXAColor(0xBA55D3FFu)
val HEXAColor.Companion.mediumpurple
get() = HEXAColor(0x9370DBFFu)
val HEXAColor.Companion.mediumseagreen
get() = HEXAColor(0x3CB371FFu)
val HEXAColor.Companion.mediumslateblue
get() = HEXAColor(0x7B68EEFFu)
val HEXAColor.Companion.mediumspringgreen
get() = HEXAColor(0x00FA9AFFu)
val HEXAColor.Companion.mediumturquoise
get() = HEXAColor(0x48D1CCFFu)
val HEXAColor.Companion.mediumvioletred
get() = HEXAColor(0xC71585FFu)
val HEXAColor.Companion.midnightblue
get() = HEXAColor(0x191970FFu)
val HEXAColor.Companion.mintcream
get() = HEXAColor(0xF5FFFAFFu)
val HEXAColor.Companion.mistyrose
get() = HEXAColor(0xFFE4E1FFu)
val HEXAColor.Companion.moccasin
get() = HEXAColor(0xFFE4B5FFu)
val HEXAColor.Companion.navajowhite
get() = HEXAColor(0xFFDEADFFu)
val HEXAColor.Companion.navy
get() = HEXAColor(0x000080FFu)
val HEXAColor.Companion.oldlace
get() = HEXAColor(0xFDF5E6FFu)
val HEXAColor.Companion.olive
get() = HEXAColor(0x808000FFu)
val HEXAColor.Companion.olivedrab
get() = HEXAColor(0x6B8E23FFu)
val HEXAColor.Companion.orange
get() = HEXAColor(0xFFA500FFu)
val HEXAColor.Companion.orangered
get() = HEXAColor(0xFF4500FFu)
val HEXAColor.Companion.orchid
get() = HEXAColor(0xDA70D6FFu)
val HEXAColor.Companion.palegoldenrod
get() = HEXAColor(0xEEE8AAFFu)
val HEXAColor.Companion.palegreen
get() = HEXAColor(0x98FB98FFu)
val HEXAColor.Companion.paleturquoise
get() = HEXAColor(0xAFEEEEFFu)
val HEXAColor.Companion.palevioletred
get() = HEXAColor(0xDB7093FFu)
val HEXAColor.Companion.papayawhip
get() = HEXAColor(0xFFEFD5FFu)
val HEXAColor.Companion.peachpuff
get() = HEXAColor(0xFFDAB9FFu)
val HEXAColor.Companion.peru
get() = HEXAColor(0xCD853FFFu)
val HEXAColor.Companion.pink
get() = HEXAColor(0xFFC0CBFFu)
val HEXAColor.Companion.plum
get() = HEXAColor(0xDDA0DDFFu)
val HEXAColor.Companion.powderblue
get() = HEXAColor(0xB0E0E6FFu)
val HEXAColor.Companion.purple
get() = HEXAColor(0x800080FFu)
val HEXAColor.Companion.red
get() = HEXAColor(0xFF0000FFu)
val HEXAColor.Companion.rosybrown
get() = HEXAColor(0xBC8F8FFFu)
val HEXAColor.Companion.royalblue
get() = HEXAColor(0x4169E1FFu)
val HEXAColor.Companion.saddlebrown
get() = HEXAColor(0x8B4513FFu)
val HEXAColor.Companion.salmon
get() = HEXAColor(0xFA8072FFu)
val HEXAColor.Companion.sandybrown
get() = HEXAColor(0xF4A460FFu)
val HEXAColor.Companion.seagreen
get() = HEXAColor(0x2E8B57FFu)
val HEXAColor.Companion.seashell
get() = HEXAColor(0xFFF5EEFFu)
val HEXAColor.Companion.sienna
get() = HEXAColor(0xA0522DFFu)
val HEXAColor.Companion.silver
get() = HEXAColor(0xC0C0C0FFu)
val HEXAColor.Companion.skyblue
get() = HEXAColor(0x87CEEBFFu)
val HEXAColor.Companion.slateblue
get() = HEXAColor(0x6A5ACDFFu)
val HEXAColor.Companion.slategray
get() = HEXAColor(0x708090FFu)
val HEXAColor.Companion.slategrey
get() = HEXAColor(0x708090FFu)
val HEXAColor.Companion.snow
get() = HEXAColor(0xFFFAFAFFu)
val HEXAColor.Companion.springgreen
get() = HEXAColor(0x00FF7FFFu)
val HEXAColor.Companion.steelblue
get() = HEXAColor(0x4682B4FFu)
val HEXAColor.Companion.tan
get() = HEXAColor(0xD2B48CFFu)
val HEXAColor.Companion.teal
get() = HEXAColor(0x008080FFu)
val HEXAColor.Companion.thistle
get() = HEXAColor(0xD8BFD8FFu)
val HEXAColor.Companion.tomato
get() = HEXAColor(0xFF6347FFu)
val HEXAColor.Companion.turquoise
get() = HEXAColor(0x40E0D0FFu)
val HEXAColor.Companion.violet
get() = HEXAColor(0xEE82EEFFu)
val HEXAColor.Companion.wheat
get() = HEXAColor(0xF5DEB3FFu)
val HEXAColor.Companion.white
get() = HEXAColor(0xFFFFFFFFu)
val HEXAColor.Companion.whitesmoke
get() = HEXAColor(0xF5F5F5FFu)
val HEXAColor.Companion.yellow
get() = HEXAColor(0xFFFF00FFu)
val HEXAColor.Companion.yellowgreen
get() = HEXAColor(0x9ACD32FFu)

View File

@@ -3,9 +3,10 @@ plugins {
id "org.jetbrains.kotlin.plugin.serialization"
id "com.android.library"
alias(libs.plugins.jb.compose)
alias(libs.plugins.kt.jb.compose)
}
apply from: "$mppProjectWithSerializationAndComposePresetPath"
apply from: "$mppComposeJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
kotlin {
sourceSets {

View File

@@ -8,7 +8,7 @@ private inline fun <T> getObject(
additional: MutableList<T>,
iterator: Iterator<T>
): T? = when {
additional.isNotEmpty() -> additional.removeFirst()
additional.isNotEmpty() -> additional.removeAt(0)
iterator.hasNext() -> iterator.next()
else -> null
}

View File

@@ -3,9 +3,10 @@ plugins {
id "org.jetbrains.kotlin.plugin.serialization"
id "com.android.library"
alias(libs.plugins.jb.compose)
alias(libs.plugins.kt.jb.compose)
}
apply from: "$mppProjectWithSerializationAndComposePresetPath"
apply from: "$mppComposeJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
kotlin {
sourceSets {

View File

@@ -3,6 +3,12 @@ package dev.inmo.micro_utils.coroutines
import kotlinx.coroutines.*
import kotlin.coroutines.*
/**
* Trying to [Deferred.await] on all [this] [Deferred]s. The first [Deferred] completed its work will interrupt all
* others awaits and, if [cancelOnResult] passed as true (**by default**), will also cancel all the others [Deferred]s
*
* @param scope Will be used to create [CoroutineScope.LinkedSupervisorScope] and launch joining of all [Job]s in it
*/
suspend fun <T> Iterable<Deferred<T>>.awaitFirstWithDeferred(
scope: CoroutineScope,
cancelOnResult: Boolean = true
@@ -24,10 +30,45 @@ suspend fun <T> Iterable<Deferred<T>>.awaitFirstWithDeferred(
}
}
/**
* Trying to [Deferred.await] on all [this] [Deferred]s. The first [Deferred] completed its work will interrupt all
* others awaits and, if [cancelOnResult] passed as true (**by default**), will also cancel all the others [Deferred]s
*
* @param scope Will be used to create [CoroutineScope.LinkedSupervisorScope] and launch joining of all [Job]s in it
*/
suspend fun <T> Iterable<Deferred<T>>.awaitFirst(
scope: CoroutineScope,
cancelOnResult: Boolean = true
): T = awaitFirstWithDeferred(scope, cancelOnResult).second
/**
* Trying to [Deferred.await] on all [this] [Deferred]s. The first [Deferred] completed its work will interrupt all
* others awaits and, if [cancelOthers] passed as true (**by default**), will also cancel all the others [Deferred]s
*
* Creates [CoroutineScope] using [coroutineContext] for internal purposes
*/
suspend fun <T> Iterable<Deferred<T>>.awaitFirst(
cancelOthers: Boolean = true
): T = awaitFirst(CoroutineScope(coroutineContext), cancelOthers)
/**
* Trying to [Deferred.await] on all [deferreds]. The first [Deferred] completed its work will interrupt all
* others awaits and, if [cancelOnResult] passed as true (**by default**), will also cancel all the others [deferreds]
*
* @param scope Will be used to create [CoroutineScope.LinkedSupervisorScope] and launch joining of all [Job]s in it
*/
suspend fun <T> awaitFirst(
vararg deferreds: Deferred<T>,
scope: CoroutineScope,
cancelOnResult: Boolean = true
): T = deferreds.toList().awaitFirstWithDeferred(scope, cancelOnResult).second
/**
* Trying to [Deferred.await] on all [deferreds]. The first [Deferred] completed its work will interrupt all
* others awaits and, if [cancelOthers] passed as true (**by default**), will also cancel all the others [deferreds]
*
* Creates [CoroutineScope] using [coroutineContext] for internal purposes
*/
suspend fun <T> awaitFirst(
vararg deferreds: Deferred<T>,
cancelOthers: Boolean = true
): T = awaitFirst(*deferreds, scope = CoroutineScope(coroutineContext), cancelOnResult = cancelOthers)

View File

@@ -0,0 +1,64 @@
package dev.inmo.micro_utils.coroutines
import kotlinx.coroutines.*
import kotlin.coroutines.*
/**
* Trying to [Job.join] on all [this] [Job]s. The first [Job] completed its work will interrupt all others joins
* and, if [cancelOthers] passed as true (**by default**), will also cancel all the others [Job]s
*
* @param scope Will be used to create [CoroutineScope.LinkedSupervisorScope] and launch joining of all [Job]s in it
*/
suspend fun Iterable<Job>.joinFirst(
scope: CoroutineScope,
cancelOthers: Boolean = true
): Job {
val resultDeferred = CompletableDeferred<Job>()
val scope = scope.LinkedSupervisorScope()
forEach {
scope.launch {
it.join()
resultDeferred.complete(it)
scope.cancel()
}
}
return resultDeferred.await().also {
if (cancelOthers) {
forEach {
runCatchingSafely { it.cancel() }
}
}
}
}
/**
* Trying to [Job.join] on all [this] [Job]s. The first [Job] completed its work will interrupt all others joins
* and, if [cancelOthers] passed as true (**by default**), will also cancel all the others [Job]s
*
* Creates [CoroutineScope] using [coroutineContext] for internal purposes
*/
suspend fun Iterable<Job>.joinFirst(
cancelOthers: Boolean = true
): Job = joinFirst(CoroutineScope(coroutineContext), cancelOthers)
/**
* Trying to [Job.join] on all [jobs]. The first [Job] completed its work will interrupt all others joins
* and, if [cancelOthers] passed as true (**by default**), will also cancel all the others [Job]s
*
* @param scope Will be used to create [CoroutineScope.LinkedSupervisorScope] and launch joining of all [Job]s in it
*/
suspend fun joinFirst(
vararg jobs: Job,
scope: CoroutineScope,
cancelOthers: Boolean = true
): Job = jobs.toList().joinFirst(scope, cancelOthers)
/**
* Trying to [Job.join] on all [jobs]. The first [Job] completed its work will interrupt all others joins
* and, if [cancelOthers] passed as true (**by default**), will also cancel all the others [Job]s
*
* Creates [CoroutineScope] using [coroutineContext] for internal purposes
*/
suspend fun joinFirst(
vararg jobs: Job,
cancelOthers: Boolean = true
): Job = joinFirst(*jobs, scope = CoroutineScope(coroutineContext), cancelOthers = cancelOthers)

View File

@@ -13,7 +13,7 @@ import kotlin.contracts.contract
* * [unlockWrite] will just unlock [writeMutex]
*/
class SmartRWLocker(private val readPermits: Int = Int.MAX_VALUE, writeIsLocked: Boolean = false) {
private val _readSemaphore = SmartSemaphore.Mutable(permits = readPermits, acquiredPermits = 0)
private val _readSemaphore = SmartSemaphore.Mutable(permits = readPermits, acquiredPermits = if (writeIsLocked) readPermits else 0)
private val _writeMutex = SmartMutex.Mutable(locked = writeIsLocked)
val readSemaphore: SmartSemaphore.Immutable = _readSemaphore.immutable()

View File

@@ -6,6 +6,7 @@ android {
defaultConfig {
minSdkVersion libs.versions.android.props.minSdk.get().toInteger()
compileSdkVersion libs.versions.android.props.compileSdk.get().toInteger()
targetSdkVersion libs.versions.android.props.compileSdk.get().toInteger()
versionCode "${android_code_version}".toInteger()
versionName "$version"

View File

@@ -32,6 +32,7 @@ allprojects {
mppJvmJsLinuxMingwProjectPresetPath = "${rootProject.projectDir.absolutePath}/mppJvmJsLinuxMingwProject.gradle"
mppJvmJsLinuxMingwLinuxArm64ProjectPresetPath = "${rootProject.projectDir.absolutePath}/mppJvmJsLinuxMingwLinuxArm64Project.gradle"
mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath = "${rootProject.projectDir.absolutePath}/mppJvmJsAndroidLinuxMingwLinuxArm64Project.gradle"
mppComposeJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath = "${rootProject.projectDir.absolutePath}/mppComposeJvmJsAndroidLinuxMingwLinuxArm64Project.gradle"
mppAndroidProjectPresetPath = "${rootProject.projectDir.absolutePath}/mppAndroidProject.gradle"
defaultAndroidSettingsPresetPath = "${rootProject.projectDir.absolutePath}/defaultAndroidSettings.gradle"

View File

@@ -15,5 +15,5 @@ crypto_js_version=4.1.1
# Project data
group=dev.inmo
version=0.21.1
android_code_version=260
version=0.22.0
android_code_version=266

View File

@@ -1,15 +1,17 @@
[versions]
kt = "1.9.23"
kt-serialization = "1.6.3"
kt = "2.0.10"
kt-serialization = "1.7.1"
kt-coroutines = "1.8.1"
kslog = "1.3.4"
kslog = "1.3.5"
jb-compose = "1.6.2"
jb-exposed = "0.50.1"
jb-compose = "1.7.0-alpha02"
jb-exposed = "0.53.0"
jb-dokka = "1.9.20"
sqlite = "3.46.0.1"
korlibs = "5.4.0"
uuid = "0.8.4"
@@ -21,25 +23,25 @@ koin = "3.5.6"
okio = "3.9.0"
ksp = "1.9.23-1.0.20"
kotlin-poet = "1.16.0"
ksp = "2.0.10-1.0.24"
kotlin-poet = "1.18.1"
versions = "0.51.0"
android-gradle = "8.2.0"
android-gradle = "8.2.2"
dexcount = "4.0.0"
android-coreKtx = "1.13.1"
android-recyclerView = "1.3.2"
android-appCompat = "1.6.1"
android-fragment = "1.7.1"
android-espresso = "3.5.1"
android-test = "1.1.5"
android-appCompat = "1.7.0"
android-fragment = "1.8.2"
android-espresso = "3.6.1"
android-test = "1.2.1"
android-compose-material3 = "1.2.1"
android-props-minSdk = "21"
android-props-compileSdk = "34"
android-props-buildTools = "34.0.0"
android-props-compileSdk = "35"
android-props-buildTools = "35.0.0"
[libraries]
@@ -52,6 +54,7 @@ kt-serialization-cbor = { module = "org.jetbrains.kotlinx:kotlinx-serialization-
kt-coroutines = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kt-coroutines" }
kt-coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "kt-coroutines" }
kt-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kt-coroutines" }
kt-coroutines-debug = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-debug", version.ref = "kt-coroutines" }
ktor-io = { module = "io.ktor:ktor-io", version.ref = "ktor" }
@@ -79,6 +82,8 @@ koin = { module = "io.insert-koin:koin-core", version.ref = "koin" }
jb-exposed = { module = "org.jetbrains.exposed:exposed-core", version.ref = "jb-exposed" }
jb-exposed-jdbc = { module = "org.jetbrains.exposed:exposed-jdbc", version.ref = "jb-exposed" }
sqlite = { module = "org.xerial:sqlite-jdbc", version.ref = "sqlite" }
android-coreKtx = { module = "androidx.core:core-ktx", version.ref = "android-coreKtx" }
@@ -113,5 +118,6 @@ buildscript-android-dexcount = { module = "com.getkeepsafe.dexcount:dexcount-gra
[plugins]
jb-compose = { id = "org.jetbrains.compose", version.ref = "jb-compose" }
kt-jb-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kt" }
versions = { id = "com.github.ben-manes.versions", version.ref = "versions" }

View File

@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@@ -4,7 +4,7 @@ plugins {
id "com.android.library"
}
apply from: "$mppProjectWithSerializationPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
kotlin {
sourceSets {

View File

@@ -5,7 +5,7 @@ plugins {
id "com.google.devtools.ksp"
}
apply from: "$mppProjectWithSerializationPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
kotlin {

View File

@@ -0,0 +1,7 @@
plugins {
id "org.jetbrains.kotlin.multiplatform"
id "org.jetbrains.kotlin.plugin.serialization"
id "com.android.library"
}
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"

View File

@@ -0,0 +1,21 @@
plugins {
id "org.jetbrains.kotlin.jvm"
}
apply from: "$publishJvmOnlyPath"
repositories {
mavenCentral()
}
dependencies {
api project(":micro_utils.ksp.generator")
api project(":micro_utils.ksp.classcasts")
api libs.kotlin.poet
api libs.ksp
}
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}

View File

@@ -0,0 +1,90 @@
package dev.inmo.micro_utils.ksp.classcasts.generator
import com.google.devtools.ksp.symbol.ClassKind
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.squareup.kotlinpoet.*
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.ksp.toClassName
import com.squareup.kotlinpoet.ksp.toTypeName
private fun FileSpec.Builder.addTopLevelImport(className: ClassName) {
className.topLevelClassName().let {
addImport(it.packageName, it.simpleNames)
}
}
private fun FileSpec.Builder.createTypeDefinition(ksClassDeclaration: KSClassDeclaration): TypeName {
val className = ksClassDeclaration.toClassName()
return if (ksClassDeclaration.typeParameters.isNotEmpty()) {
className.parameterizedBy(
ksClassDeclaration.typeParameters.map {
it.bounds.first().resolve().also {
val typeClassName = it.toClassName()
addTopLevelImport(typeClassName)
}.toTypeName()
}
)
} else {
className
}
}
internal fun FileSpec.Builder.fill(
sourceKSClassDeclaration: KSClassDeclaration,
subtypes: Set<KSClassDeclaration>
) {
subtypes.forEach { targetClassDeclaration ->
val sourceClassName = sourceKSClassDeclaration.toClassName()
val targetClassClassName = targetClassDeclaration.toClassName()
val targetClassTypeDefinition = createTypeDefinition(targetClassDeclaration)
val simpleName = targetClassDeclaration.simpleName.asString()
val withFirstLowerCase = simpleName.replaceFirstChar { it.lowercase() }
val castedOrNullName = "${withFirstLowerCase}OrNull"
addTopLevelImport(targetClassClassName)
addFunction(
FunSpec.builder(castedOrNullName).apply {
receiver(sourceClassName)
addCode(
"return this as? %L",
targetClassTypeDefinition
)
returns(targetClassTypeDefinition.copy(nullable = true))
addModifiers(KModifier.INLINE)
}.build()
)
addFunction(
FunSpec.builder("${withFirstLowerCase}OrThrow").apply {
receiver(sourceClassName)
addCode(
"return this as %L",
targetClassTypeDefinition
)
returns(targetClassTypeDefinition)
addModifiers(KModifier.INLINE)
}.build()
)
addFunction(
FunSpec.builder("if$simpleName").apply {
val genericType = TypeVariableName("T", null)
addTypeVariable(genericType)
receiver(sourceClassName)
addParameter(
"block",
LambdaTypeName.get(
null,
targetClassTypeDefinition,
returnType = genericType
)
)
addCode(
"return ${castedOrNullName}() ?.let(block)",
targetClassTypeDefinition
)
returns(genericType.copy(nullable = true))
addModifiers(KModifier.INLINE)
}.build()
)
}
}

View File

@@ -0,0 +1,119 @@
package dev.inmo.micro_utils.ksp.classcasts.generator
import com.google.devtools.ksp.KspExperimental
import com.google.devtools.ksp.getAllSuperTypes
import com.google.devtools.ksp.getAnnotationsByType
import com.google.devtools.ksp.isAnnotationPresent
import com.google.devtools.ksp.processing.CodeGenerator
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.processing.SymbolProcessor
import com.google.devtools.ksp.symbol.*
import com.squareup.kotlinpoet.*
import com.squareup.kotlinpoet.ksp.toClassName
import dev.inmo.micro_ksp.generator.writeFile
import dev.inmo.micro_utils.ksp.classcasts.ClassCastsExcluded
import dev.inmo.micro_utils.ksp.classcasts.ClassCastsIncluded
import java.io.File
class Processor(
private val codeGenerator: CodeGenerator
) : SymbolProcessor {
@OptIn(KspExperimental::class)
private fun FileSpec.Builder.generateClassCasts(
ksClassDeclaration: KSClassDeclaration,
resolver: Resolver
) {
val rootAnnotation = ksClassDeclaration.getAnnotationsByType(ClassCastsIncluded::class).first()
val (includeRegex: Regex?, excludeRegex: Regex?) = rootAnnotation.let {
it.typesRegex.takeIf { it.isNotEmpty() } ?.let(::Regex) to it.excludeRegex.takeIf { it.isNotEmpty() } ?.let(::Regex)
}
val classesSubtypes = mutableMapOf<KSClassDeclaration, MutableSet<KSClassDeclaration>>()
fun KSClassDeclaration.checkSupertypeLevel(levelsAllowed: Int?): Boolean {
val supertypes by lazy {
superTypes.map { it.resolve().declaration }
}
return when {
levelsAllowed == null -> true
levelsAllowed <= 0 -> false
supertypes.any { it == ksClassDeclaration } -> true
else -> supertypes.any {
(it as? KSClassDeclaration) ?.checkSupertypeLevel(levelsAllowed - 1) == true
}
}
}
fun handleDeclaration(ksDeclarationContainer: KSDeclarationContainer) {
ksDeclarationContainer.declarations.forEach { potentialSubtype ->
val simpleName = potentialSubtype.simpleName.getShortName()
when {
potentialSubtype === ksClassDeclaration -> {}
potentialSubtype.isAnnotationPresent(ClassCastsExcluded::class) -> return@forEach
potentialSubtype !is KSClassDeclaration || !potentialSubtype.checkSupertypeLevel(rootAnnotation.levelsToInclude.takeIf { it >= 0 }) -> return@forEach
excludeRegex ?.matches(simpleName) == true -> return@forEach
includeRegex ?.matches(simpleName) == false -> {}
else -> classesSubtypes.getOrPut(ksClassDeclaration) { mutableSetOf() }.add(potentialSubtype)
}
handleDeclaration(potentialSubtype as? KSDeclarationContainer ?: return@forEach)
}
}
resolver.getAllFiles().forEach {
handleDeclaration(it)
}
fun fillWithSealeds(current: KSClassDeclaration) {
current.getSealedSubclasses().forEach {
val simpleName = it.simpleName.getShortName()
if (
includeRegex ?.matches(simpleName) == false
|| excludeRegex ?.matches(simpleName) == true
|| it.isAnnotationPresent(ClassCastsExcluded::class)
) {
return@forEach
}
classesSubtypes.getOrPut(ksClassDeclaration) { mutableSetOf() }.add(it)
fillWithSealeds(it)
}
}
fillWithSealeds(ksClassDeclaration)
addAnnotation(
AnnotationSpec.builder(Suppress::class).apply {
addMember("\"unused\"")
addMember("\"RemoveRedundantQualifierName\"")
addMember("\"RedundantVisibilityModifier\"")
addMember("\"NOTHING_TO_INLINE\"")
addMember("\"UNCHECKED_CAST\"")
addMember("\"OPT_IN_USAGE\"")
useSiteTarget(AnnotationSpec.UseSiteTarget.FILE)
}.build()
)
fill(
ksClassDeclaration,
classesSubtypes.values.flatten().toSet()
)
}
@OptIn(KspExperimental::class)
override fun process(resolver: Resolver): List<KSAnnotated> {
(resolver.getSymbolsWithAnnotation(ClassCastsIncluded::class.qualifiedName!!)).filterIsInstance<KSClassDeclaration>().forEach {
val prefix = it.getAnnotationsByType(ClassCastsIncluded::class).first().outputFilePrefix
it.writeFile(prefix = prefix, suffix = "ClassCasts") {
FileSpec.builder(
it.packageName.asString(),
"${it.simpleName.getShortName()}ClassCasts"
).apply {
addFileComment(
"""
THIS CODE HAVE BEEN GENERATED AUTOMATICALLY
TO REGENERATE IT JUST DELETE FILE
ORIGINAL FILE: ${it.containingFile ?.fileName}
""".trimIndent()
)
generateClassCasts(it, resolver)
}.build()
}
}
return emptyList()
}
}

View File

@@ -0,0 +1,11 @@
package dev.inmo.micro_utils.ksp.classcasts.generator
import com.google.devtools.ksp.processing.SymbolProcessor
import com.google.devtools.ksp.processing.SymbolProcessorEnvironment
import com.google.devtools.ksp.processing.SymbolProcessorProvider
class Provider : SymbolProcessorProvider {
override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor = Processor(
environment.codeGenerator
)
}

View File

@@ -0,0 +1 @@
dev.inmo.micro_utils.ksp.classcasts.generator.Provider

View File

@@ -0,0 +1,27 @@
plugins {
id "org.jetbrains.kotlin.multiplatform"
id "org.jetbrains.kotlin.plugin.serialization"
id "com.android.library"
id "com.google.devtools.ksp"
}
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
kotlin {
sourceSets {
commonMain {
dependencies {
api project(":micro_utils.ksp.classcasts")
}
}
}
}
dependencies {
add("kspCommonMainMetadata", project(":micro_utils.ksp.classcasts.generator"))
}
ksp {
}

View File

@@ -0,0 +1,15 @@
package dev.inmo.micro_utils.ksp.classcasts.generator.test
import dev.inmo.micro_utils.ksp.classcasts.ClassCastsExcluded
import dev.inmo.micro_utils.ksp.classcasts.ClassCastsIncluded
@ClassCastsIncluded(levelsToInclude = 1)
sealed interface Test {
object A : Test
@ClassCastsExcluded
object B : Test // Will not be included in class casts due to annotation ClassCastsExcluded
object C : Test
interface D : Test {
object DD : D // Will not be included in class casts due to levelsToInclude
}
}

View File

@@ -0,0 +1,40 @@
// THIS CODE HAVE BEEN GENERATED AUTOMATICALLY
// TO REGENERATE IT JUST DELETE FILE
// ORIGINAL FILE: Test.kt
@file:Suppress(
"unused",
"RemoveRedundantQualifierName",
"RedundantVisibilityModifier",
"NOTHING_TO_INLINE",
"UNCHECKED_CAST",
"OPT_IN_USAGE",
)
package dev.inmo.micro_utils.ksp.classcasts.generator.test
import dev.inmo.micro_utils.ksp.classcasts.generator.test.Test
import kotlin.Suppress
public inline fun Test.aOrNull(): Test.A? = this as?
dev.inmo.micro_utils.ksp.classcasts.generator.test.Test.A
public inline fun Test.aOrThrow(): Test.A = this as
dev.inmo.micro_utils.ksp.classcasts.generator.test.Test.A
public inline fun <T> Test.ifA(block: (Test.A) -> T): T? = aOrNull() ?.let(block)
public inline fun Test.cOrNull(): Test.C? = this as?
dev.inmo.micro_utils.ksp.classcasts.generator.test.Test.C
public inline fun Test.cOrThrow(): Test.C = this as
dev.inmo.micro_utils.ksp.classcasts.generator.test.Test.C
public inline fun <T> Test.ifC(block: (Test.C) -> T): T? = cOrNull() ?.let(block)
public inline fun Test.dOrNull(): Test.D? = this as?
dev.inmo.micro_utils.ksp.classcasts.generator.test.Test.D
public inline fun Test.dOrThrow(): Test.D = this as
dev.inmo.micro_utils.ksp.classcasts.generator.test.Test.D
public inline fun <T> Test.ifD(block: (Test.D) -> T): T? = dOrNull() ?.let(block)

View File

@@ -0,0 +1,5 @@
package dev.inmo.micro_utils.ksp.classcasts
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.SOURCE)
annotation class ClassCastsExcluded

View File

@@ -0,0 +1,10 @@
package dev.inmo.micro_utils.ksp.classcasts
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.SOURCE)
annotation class ClassCastsIncluded(
val typesRegex: String = "",
val excludeRegex: String = "",
val outputFilePrefix: String = "",
val levelsToInclude: Int = -1
)

View File

@@ -0,0 +1,30 @@
package dev.inmo.micro_ksp.generator
import com.google.devtools.ksp.getAllSuperTypes
import com.google.devtools.ksp.symbol.KSAnnotated
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.google.devtools.ksp.symbol.KSDeclarationContainer
import com.google.devtools.ksp.symbol.KSFile
fun KSClassDeclaration.findSubClasses(subSymbol: KSAnnotated): Sequence<KSClassDeclaration> {
return when (subSymbol) {
is KSClassDeclaration -> if (subSymbol.getAllSuperTypes().map { it.declaration }.contains(this)) {
sequenceOf(subSymbol)
} else {
sequenceOf()
}
else -> sequenceOf()
} + if (subSymbol is KSDeclarationContainer) {
subSymbol.declarations.flatMap {
findSubClasses(it)
}
} else {
sequenceOf()
}
}
fun KSClassDeclaration.findSubClasses(files: Sequence<KSAnnotated>): Sequence<KSClassDeclaration> {
return files.flatMap {
findSubClasses(it)
}
}

View File

@@ -6,7 +6,6 @@ import com.google.devtools.ksp.processing.CodeGenerator
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.processing.SymbolProcessor
import com.google.devtools.ksp.symbol.*
import com.squareup.kotlinpoet.AnnotationSpec
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.FileSpec
@@ -16,18 +15,35 @@ import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.asTypeName
import com.squareup.kotlinpoet.ksp.toClassName
import dev.inmo.micro_ksp.generator.findSubClasses
import dev.inmo.micro_ksp.generator.writeFile
import dev.inmo.microutils.kps.sealed.GenerateSealedWorkaround
import java.io.File
class Processor(
private val codeGenerator: CodeGenerator
) : SymbolProcessor {
private fun KSClassDeclaration.resolveSubclasses(): List<KSClassDeclaration> {
return (getSealedSubclasses().flatMap {
it.resolveSubclasses()
}.ifEmpty {
sequenceOf(this)
}).toList()
private fun KSClassDeclaration.findSealedConnection(potentialSealedParent: KSClassDeclaration): Boolean {
val targetClassname = potentialSealedParent.qualifiedName ?.asString()
return superTypes.any {
val itAsDeclaration = it.resolve().declaration as? KSClassDeclaration ?: return@any false
targetClassname == (itAsDeclaration.qualifiedName ?.asString()) || (itAsDeclaration.getSealedSubclasses().any() && itAsDeclaration.findSealedConnection(potentialSealedParent))
}
}
private fun KSClassDeclaration.resolveSubclasses(
searchIn: Sequence<KSAnnotated>,
allowNonSealed: Boolean
): Sequence<KSClassDeclaration> {
return findSubClasses(searchIn).let {
if (allowNonSealed) {
it
} else {
it.filter {
it.findSealedConnection(this)
}
}
}
}
@OptIn(KspExperimental::class)
@@ -35,7 +51,11 @@ class Processor(
ksClassDeclaration: KSClassDeclaration,
resolver: Resolver
) {
val subClasses = ksClassDeclaration.resolveSubclasses().distinct()
val annotation = ksClassDeclaration.getAnnotationsByType(GenerateSealedWorkaround::class).first()
val subClasses = ksClassDeclaration.resolveSubclasses(
searchIn = resolver.getAllFiles(),
allowNonSealed = annotation.includeNonSealedSubTypes
).distinct()
val subClassesNames = subClasses.filter {
when (it.classKind) {
ClassKind.ENUM_ENTRY,
@@ -51,7 +71,7 @@ class Processor(
(it.getAnnotationsByType(GenerateSealedWorkaround.Order::class).firstOrNull()) ?.order ?: 0
}.map {
it.toClassName()
}
}.toList()
val className = ksClassDeclaration.toClassName()
val setType = Set::class.asTypeName().parameterizedBy(
ksClassDeclaration.toClassName()

View File

@@ -5,7 +5,7 @@ plugins {
id "com.google.devtools.ksp"
}
apply from: "$mppProjectWithSerializationPresetPath"
apply from: "$mppJvmJsAndroidLinuxMingwLinuxArm64ProjectPresetPath"
kotlin {

View File

@@ -3,7 +3,8 @@ package dev.inmo.microutils.kps.sealed
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS)
annotation class GenerateSealedWorkaround(
val prefix: String = ""
val prefix: String = "",
val includeNonSealedSubTypes: Boolean = false
) {
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS)

File diff suppressed because one or more lines are too long

View File

@@ -22,17 +22,24 @@ private const val baseClassSerializerAnnotationName = "@Serializable(${baseClass
@Serializable
private data class LanguageCode(
@SerialName("alpha2")
val tag: String,
@SerialName("English")
val title: String
)
val title: String,
@SerialName("alpha2")
val alpha: String? = null,
@SerialName("alpha3-b")
val alpha2: String? = null,
@SerialName("alpha3-t")
val alpha3: String? = null,
) {
val tag: String
get() = alpha ?: alpha2 ?: alpha3!!
}
fun String.adaptAsTitle() = if (first().isDigit()) {
fun String.adaptAsTitle() = (if (first().isDigit()) {
"L$this"
} else {
this
}
}).replace(".", "_").replace("'", "_")
fun String.normalized() = Normalizer.normalize(this, Normalizer.Form.NFD).replace(Regex("[^\\p{ASCII}]"), "")
@@ -73,7 +80,10 @@ data class Tag(
val title: String,
val tag: String,
val subtags: List<Tag>
)
) {
val adaptedTitle
get() = title.adaptAsTitle()
}
private fun printLanguageCodeAndTags(
tag: Tag,
@@ -81,17 +91,19 @@ private fun printLanguageCodeAndTags(
indents: String = " "
): String = if (tag.subtags.isEmpty()) {
"""${indents}${baseClassSerializerAnnotationName}
${indents}object ${tag.title} : ${parent ?.title ?: baseClassName}() { override val code: String = "${tag.tag}"${parent ?.let { parent -> "; override val parentLang: ${parent.title} get() = ${parent.title};" } ?: ""} }"""
${indents}object ${tag.adaptedTitle} : ${parent ?.adaptedTitle ?: baseClassName} { override val code: String = "${tag.tag}"${parent ?.let { parent -> "; override val parentLang: ${parent.adaptedTitle} get() = ${parent.adaptedTitle}" } ?: ""}; override fun toString() = code }"""
} else {
"""
${indents}${baseClassSerializerAnnotationName}
${indents}sealed class ${tag.title} : ${parent ?.title ?: baseClassName}() {
${indents} override val code: String = "${tag.tag}"${parent ?.let { parent -> "\n${indents} override val parentLang: ${parent.title} get() = ${parent.title};" } ?: ""}
${indents}sealed interface ${tag.adaptedTitle} : ${parent ?.adaptedTitle ?: baseClassName} {
${tag.subtags.joinToString("\n") { printLanguageCodeAndTags(it, tag, "${indents} ") }}
${indents} ${baseClassSerializerAnnotationName}
${indents} companion object : ${tag.title}()
${indents} companion object : ${tag.adaptedTitle} {
${indents} override val code: String = "${tag.tag}"${parent ?.let { parent -> "\n${indents} override val parentLang: ${parent.adaptedTitle} get() = ${parent.adaptedTitle};" } ?: ""}
${indents} override fun toString() = code
${indents} }
${indents}}
"""
}
@@ -105,23 +117,22 @@ import kotlinx.serialization.Serializable
* https://datahub.io/core/language-codes/ files (base and tags) and create the whole hierarchy using it.
*/
${baseClassSerializerAnnotationName}
sealed class $baseClassName {
abstract val code: String
open val parentLang: $baseClassName?
get() = null
open val withoutDialect: String
sealed interface $baseClassName {
val code: String
val parentLang: $baseClassName?
get() = code.split("-").takeIf { it.size > 1 } ?.first() ?.let(::$unknownBaseClassName)
val withoutDialect: String
get() = parentLang ?.code ?: code
${tags.joinToString("\n") { printLanguageCodeAndTags(it, indents = " ") } }
$baseClassSerializerAnnotationName
data class $unknownBaseClassName (override val code: String) : $baseClassName() {
data class $unknownBaseClassName (override val code: String) : $baseClassName {
override val parentLang = code.dropLastWhile { it != '-' }.removeSuffix("-").takeIf { it.length > 0 } ?.let(::$unknownBaseClassName)
}
@Deprecated("Renamed", ReplaceWith("$baseClassName.$unknownBaseClassName", "${if (prePackage.isNotEmpty()) "$prePackage." else ""}$baseClassName.$unknownBaseClassName"))
val $oldUnknownBaseClassName = $unknownBaseClassName
override fun toString() = code
val $oldUnknownBaseClassName
get() = $unknownBaseClassName
}
@Deprecated("Renamed", ReplaceWith("$baseClassName", "${if (prePackage.isNotEmpty()) "$prePackage." else ""}$baseClassName"))
typealias $oldBaseClassName = $baseClassName
@@ -133,7 +144,7 @@ fun createStringConverterCode(tags: List<Tag>, prePackage: String): String {
pretitle: String = baseClassName,
indents: String = " "
): String {
val currentTitle = "$pretitle.${tag.title}"
val currentTitle = "$pretitle.${tag.adaptedTitle}"
return """${indents}$currentTitle.code -> $currentTitle${if (tag.subtags.isNotEmpty()) tag.subtags.joinToString("\n", "\n") { createDeserializeVariantForTag(it, currentTitle, indents) } else ""}"""
}
fun createInheritorVariantForTag(
@@ -141,7 +152,7 @@ fun createStringConverterCode(tags: List<Tag>, prePackage: String): String {
pretitle: String = baseClassName,
indents: String = " "
): String {
val currentTitle = "$pretitle.${tag.title}"
val currentTitle = "$pretitle.${tag.adaptedTitle}"
val subtags = if (tag.subtags.isNotEmpty()) {
tag.subtags.joinToString(",\n", ",\n") { createInheritorVariantForTag(it, currentTitle, "$indents ") }
} else {
@@ -155,7 +166,7 @@ fun createStringConverterCode(tags: List<Tag>, prePackage: String): String {
indents: String = " ",
codeSuffix: String = ""
): String {
val currentTitle = "$pretitle.${tag.title}"
val currentTitle = "$pretitle.${tag.adaptedTitle}"
val subtags = if (tag.subtags.isNotEmpty()) {
tag.subtags.joinToString(",\n", ",\n") { createInheritorVariantForMapForTag(it, currentTitle, "$indents ", codeSuffix) }
} else {
@@ -266,7 +277,7 @@ suspend fun main(vararg args: String) {
File(outputFolder, "LanguageCodes.kt").apply {
delete()
createNewFile()
writeText(targetPackagePrefix + buildKtFileContent(tags, targetPackage ?: ""))
writeText("@file:Suppress(\"SERIALIZER_TYPE_INCOMPATIBLE\")\n\n" + targetPackagePrefix + buildKtFileContent(tags, targetPackage ?: ""))
}
File(outputFolder, "StringToLanguageCodes.kt").apply {

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,108 @@
project.version = "$version"
project.group = "$group"
apply from: "$publishGradlePath"
kotlin {
jvm {
compilations.main {
kotlinOptions {
jvmTarget = "17"
}
}
}
js (IR) {
browser {
testTask {
useMocha {
timeout = "60000"
}
}
}
nodejs {
testTask {
useMocha {
timeout = "60000"
}
}
}
}
androidTarget {
publishAllLibraryVariants()
compilations.all {
kotlinOptions {
jvmTarget = "17"
}
}
}
linuxX64()
mingwX64()
linuxArm64()
sourceSets {
commonMain {
dependencies {
implementation kotlin('stdlib')
implementation compose.runtime
api libs.kt.serialization
}
}
commonTest {
dependencies {
implementation kotlin('test-common')
implementation kotlin('test-annotations-common')
implementation libs.kt.coroutines.test
}
}
androidUnitTest {
dependencies {
implementation kotlin('test-junit')
implementation libs.android.test.junit
implementation libs.android.espresso
implementation compose.uiTest
}
}
androidInstrumentedTest {
dependencies {
implementation kotlin('test-junit')
implementation libs.android.test.junit
implementation libs.android.espresso
}
}
jvmMain {
dependencies {
implementation compose.desktop.currentOs
}
}
jvmTest {
dependencies {
implementation kotlin('test-junit')
implementation compose.uiTest
}
}
jsMain {
dependencies {
implementation compose.web.core
}
}
jsTest {
dependencies {
implementation kotlin('test-js')
}
}
nativeMain.dependsOn commonMain
linuxX64Main.dependsOn nativeMain
mingwX64Main.dependsOn nativeMain
linuxArm64Main.dependsOn nativeMain
androidMain.dependsOn jvmMain
}
}
apply from: "$defaultAndroidSettingsPresetPath"
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}

View File

@@ -12,8 +12,20 @@ kotlin {
}
}
js (IR) {
browser()
nodejs()
browser {
testTask {
useMocha {
timeout = "60000"
}
}
}
nodejs {
testTask {
useMocha {
timeout = "60000"
}
}
}
}
androidTarget {
publishAllLibraryVariants()
@@ -36,7 +48,7 @@ kotlin {
}
commonTest {
dependencies {
implementation kotlin('test-common')
implementation kotlin('test')
implementation kotlin('test-annotations-common')
implementation libs.kt.coroutines.test
}
@@ -57,7 +69,6 @@ kotlin {
jsTest {
dependencies {
implementation kotlin('test-js')
implementation kotlin('test-junit')
}
}
nativeMain.dependsOn commonMain

View File

@@ -12,8 +12,20 @@ kotlin {
}
}
js (IR) {
browser()
nodejs()
browser {
testTask {
useMocha {
timeout = "60000"
}
}
}
nodejs {
testTask {
useMocha {
timeout = "60000"
}
}
}
}
androidTarget {
publishAllLibraryVariants()
@@ -48,7 +60,6 @@ kotlin {
jsTest {
dependencies {
implementation kotlin('test-js')
implementation kotlin('test-junit')
}
}
androidUnitTest {
@@ -58,16 +69,6 @@ kotlin {
implementation libs.android.espresso
}
}
mingwX64Test {
dependencies {
implementation kotlin('test-junit')
}
}
linuxX64Test {
dependencies {
implementation kotlin('test-junit')
}
}
androidMain.dependsOn jvmMain
}

View File

@@ -12,8 +12,20 @@ kotlin {
}
}
js (IR) {
browser()
nodejs()
browser {
testTask {
useMocha {
timeout = "60000"
}
}
}
nodejs {
testTask {
useMocha {
timeout = "60000"
}
}
}
}
linuxX64()
mingwX64()
@@ -42,7 +54,6 @@ kotlin {
jsTest {
dependencies {
implementation kotlin('test-js')
implementation kotlin('test-junit')
}
}

View File

@@ -12,8 +12,20 @@ kotlin {
}
}
js (IR) {
browser()
nodejs()
browser {
testTask {
useMocha {
timeout = "60000"
}
}
}
nodejs {
testTask {
useMocha {
timeout = "60000"
}
}
}
}
linuxX64()
mingwX64()
@@ -41,17 +53,6 @@ kotlin {
jsTest {
dependencies {
implementation kotlin('test-js')
implementation kotlin('test-junit')
}
}
mingwX64Test {
dependencies {
implementation kotlin('test-junit')
}
}
linuxX64Test {
dependencies {
implementation kotlin('test-junit')
}
}

View File

@@ -12,8 +12,20 @@ kotlin {
}
}
js (IR) {
browser()
nodejs()
browser {
testTask {
useMocha {
timeout = "60000"
}
}
}
nodejs {
testTask {
useMocha {
timeout = "60000"
}
}
}
}
androidTarget {
publishAllLibraryVariants()
@@ -58,7 +70,6 @@ kotlin {
jsTest {
dependencies {
implementation kotlin('test-js')
implementation kotlin('test-junit')
}
}
androidUnitTest {
@@ -69,13 +80,6 @@ kotlin {
implementation compose.uiTest
}
}
androidInstrumentedTest {
dependencies {
implementation kotlin('test-junit')
implementation libs.android.test.junit
implementation libs.android.espresso
}
}
}
}

View File

@@ -98,7 +98,7 @@ open class FullCRUDCacheRepo<ObjectType, IdType, InputValueType>(
kvCache: KeyValueRepo<IdType, ObjectType>,
scope: CoroutineScope = CoroutineScope(Dispatchers.Default),
skipStartInvalidate: Boolean = false,
locker: SmartRWLocker = SmartRWLocker(),
locker: SmartRWLocker = SmartRWLocker(writeIsLocked = !skipStartInvalidate),
idGetter: (ObjectType) -> IdType
) : FullReadCRUDCacheRepo<ObjectType, IdType>(
parentRepo,
@@ -116,10 +116,23 @@ open class FullCRUDCacheRepo<ObjectType, IdType, InputValueType>(
CRUDRepo<ObjectType, IdType, InputValueType> {
init {
if (!skipStartInvalidate) {
scope.launchSafelyWithoutExceptions { invalidate() }
scope.launchSafelyWithoutExceptions {
if (locker.writeMutex.isLocked) {
initialInvalidate()
} else {
invalidate()
}
}
}
}
protected open suspend fun initialInvalidate() {
try {
kvCache.actualizeAll(parentRepo, locker = null)
} finally {
locker.unlockWrite()
}
}
override suspend fun invalidate() {
actualizeAll()
}

View File

@@ -126,26 +126,40 @@ fun <Key, Value> WriteKeyValueRepo<Key, Value>.caching(
) = FullWriteKeyValueCacheRepo(this, kvCache, scope)
open class FullKeyValueCacheRepo<Key,Value>(
protected open val parentRepo: KeyValueRepo<Key, Value>,
override val parentRepo: KeyValueRepo<Key, Value>,
kvCache: KeyValueRepo<Key, Value>,
scope: CoroutineScope = CoroutineScope(Dispatchers.Default),
skipStartInvalidate: Boolean = false,
locker: SmartRWLocker = SmartRWLocker()
) : FullWriteKeyValueCacheRepo<Key,Value>(parentRepo, kvCache, scope),
locker: SmartRWLocker = SmartRWLocker(writeIsLocked = !skipStartInvalidate),
) : //FullWriteKeyValueCacheRepo<Key,Value>(parentRepo, kvCache, scope),
KeyValueRepo<Key,Value>,
ReadKeyValueRepo<Key, Value> by FullReadKeyValueCacheRepo(
WriteKeyValueRepo<Key,Value> by parentRepo,
FullReadKeyValueCacheRepo<Key, Value>(
parentRepo,
kvCache,
locker
) {
init {
if (!skipStartInvalidate) {
scope.launchSafelyWithoutExceptions { invalidate() }
scope.launchSafelyWithoutExceptions {
if (locker.writeMutex.isLocked) {
initialInvalidate()
} else {
invalidate()
}
}
}
}
override suspend fun unsetWithValues(toUnset: List<Value>) = parentRepo.unsetWithValues(toUnset)
protected open suspend fun initialInvalidate() {
try {
kvCache.actualizeAll(parentRepo, locker = null)
} finally {
locker.unlockWrite()
}
}
override suspend fun invalidate() {
kvCache.actualizeAll(parentRepo, locker)
}
@@ -154,6 +168,28 @@ open class FullKeyValueCacheRepo<Key,Value>(
parentRepo.clear()
kvCache.clear()
}
override suspend fun set(toSet: Map<Key, Value>) {
locker.withWriteLock {
parentRepo.set(toSet)
kvCache.set(
toSet.filter {
parentRepo.contains(it.key)
}
)
}
}
override suspend fun unset(toUnset: List<Key>) {
locker.withWriteLock {
parentRepo.unset(toUnset)
kvCache.unset(
toUnset.filter {
!parentRepo.contains(it)
}
)
}
}
}
fun <Key, Value> KeyValueRepo<Key, Value>.fullyCached(

View File

@@ -10,6 +10,7 @@ import dev.inmo.micro_utils.pagination.utils.*
import dev.inmo.micro_utils.repos.*
import dev.inmo.micro_utils.repos.cache.util.ActualizeAllClearMode
import dev.inmo.micro_utils.repos.cache.util.actualizeAll
import dev.inmo.micro_utils.repos.pagination.maxPagePagination
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
@@ -65,6 +66,42 @@ open class FullReadKeyValuesCacheRepo<Key,Value>(
)
}
override suspend fun getAll(k: Key, reversed: Boolean): List<Value> {
return doOrTakeAndActualizeWithWriteLock(
{
get(k) ?.optionallyReverse(reversed).optionalOrAbsentIfNull
},
{ getAll(k, reversed) },
{ kvCache.set(k, it.optionallyReverse(reversed)) }
)
}
override suspend fun getAll(reverseLists: Boolean): Map<Key, List<Value>> {
return doOrTakeAndActualizeWithWriteLock(
{
getAll().takeIf { it.isNotEmpty() } ?.let {
if (reverseLists) {
it.mapValues { it.value.reversed() }
} else {
it
}
}.optionalOrAbsentIfNull
},
{ getAll(reverseLists) },
{
kvCache.set(
it.let {
if (reverseLists) {
it.mapValues { it.value.reversed() }
} else {
it
}
}
)
}
)
}
override suspend fun keys(pagination: Pagination, reversed: Boolean): PaginationResult<Key> {
return doOrTakeAndActualize(
{
@@ -163,17 +200,23 @@ fun <Key, Value> WriteKeyValuesRepo<Key, Value>.caching(
) = FullWriteKeyValuesCacheRepo(this, kvCache, scope, locker)
open class FullKeyValuesCacheRepo<Key,Value>(
protected open val parentRepo: KeyValuesRepo<Key, Value>,
override val parentRepo: KeyValuesRepo<Key, Value>,
kvCache: KeyValueRepo<Key, List<Value>>,
scope: CoroutineScope = CoroutineScope(Dispatchers.Default),
skipStartInvalidate: Boolean = false,
locker: SmartRWLocker = SmartRWLocker(),
) : FullWriteKeyValuesCacheRepo<Key, Value>(parentRepo, kvCache, scope, locker),
KeyValuesRepo<Key, Value>,
ReadKeyValuesRepo<Key, Value> by FullReadKeyValuesCacheRepo(parentRepo, kvCache, locker) {
locker: SmartRWLocker = SmartRWLocker(writeIsLocked = !skipStartInvalidate),
) : KeyValuesRepo<Key, Value>,
FullReadKeyValuesCacheRepo<Key, Value>(parentRepo, kvCache, locker),
WriteKeyValuesRepo<Key, Value> by parentRepo {
init {
if (!skipStartInvalidate) {
scope.launchSafelyWithoutExceptions { invalidate() }
scope.launchSafelyWithoutExceptions {
if (locker.writeMutex.isLocked) {
initialInvalidate()
} else {
invalidate()
}
}
}
}
@@ -185,16 +228,75 @@ open class FullKeyValuesCacheRepo<Key,Value>(
}
}
protected open suspend fun initialInvalidate() {
try {
kvCache.actualizeAll(parentRepo, locker = null)
} finally {
locker.unlockWrite()
}
}
override suspend fun invalidate() {
kvCache.actualizeAll(parentRepo, locker = locker)
}
override suspend fun set(toSet: Map<Key, List<Value>>) {
super<KeyValuesRepo>.set(toSet)
locker.withWriteLock {
parentRepo.set(toSet)
kvCache.set(
toSet.filter {
parentRepo.contains(it.key)
}
)
}
}
override suspend fun removeWithValue(v: Value) {
super<FullWriteKeyValuesCacheRepo>.removeWithValue(v)
override suspend fun add(toAdd: Map<Key, List<Value>>) {
locker.withWriteLock {
parentRepo.add(toAdd)
toAdd.forEach {
val filtered = it.value.filter { v ->
parentRepo.contains(it.key, v)
}.ifEmpty {
return@forEach
}
kvCache.set(
it.key,
(kvCache.get(it.key) ?: emptyList()) + filtered
)
}
}
}
override suspend fun remove(toRemove: Map<Key, List<Value>>) {
locker.withWriteLock {
parentRepo.remove(toRemove)
toRemove.forEach {
val filtered = it.value.filter { v ->
!parentRepo.contains(it.key, v)
}.ifEmpty {
return@forEach
}.toSet()
val resultList = (kvCache.get(it.key) ?: emptyList()) - filtered
if (resultList.isEmpty()) {
kvCache.unset(it.key)
} else {
kvCache.set(
it.key,
resultList
)
}
}
}
}
override suspend fun clear(k: Key) {
locker.withWriteLock {
parentRepo.clear(k)
if (parentRepo.contains(k)) {
return@withWriteLock
}
kvCache.unset(k)
}
}
}

View File

@@ -0,0 +1,142 @@
package full
import com.benasher44.uuid.uuid4
import dev.inmo.micro_utils.repos.MapCRUDRepo
import dev.inmo.micro_utils.repos.MapKeyValueRepo
import dev.inmo.micro_utils.repos.cache.full.FullCRUDCacheRepo
import dev.inmo.micro_utils.repos.create
import dev.inmo.micro_utils.repos.deleteById
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class FullCRUDCacheRepoTests {
data class New(
val data: String
)
data class Registered(
val id: String,
val data: String
)
@Test
fun creatingWorksProperly() = runTest {
val testData = (0 until 1000).map {
("$it-" + uuid4().toString())
}
val updatedTestData = (0 until 1000).map {
("$it-" + uuid4().toString())
}
val kvCache = MapKeyValueRepo<String, Registered>()
val crudRepo = MapCRUDRepo<Registered, String, New>(
{ new, id, old ->
Registered(id, new.data)
}
) {
val id = uuid4().toString()
id to Registered(id, it.data)
}
val cacheRepo = FullCRUDCacheRepo(
crudRepo,
kvCache,
idGetter = { it.id }
)
val registereds = testData.map {
val created = cacheRepo.create(New(it)).first()
assertEquals(it, created.data)
assertEquals(kvCache.get(created.id), created)
assertEquals(crudRepo.getById(created.id), created)
created
}
cacheRepo.getAll().forEach { (id, value) ->
assertTrue {
registereds.first {
it.id == id
} == value
}
}
val updatedRegistereds = registereds.mapIndexed { i, it ->
val updated = cacheRepo.update(it.id, New(updatedTestData[i])) ?: error("Unable to update data for $it")
assertEquals(updatedTestData[i], updated.data)
assertEquals(kvCache.get(updated.id), updated)
assertEquals(crudRepo.getById(updated.id), updated)
updated
}
cacheRepo.getAll().forEach { (id, value) ->
assertTrue {
updatedRegistereds.first {
it.id == id
} == value
}
}
}
@Test
fun precachingWorksProperly() = runTest {
val testData = (0 until 1000).map {
(it.toString() + uuid4().toString())
}
val kvCache = MapKeyValueRepo<String, Registered>()
val crudRepo = MapCRUDRepo<Registered, String, New>(
{ new, id, old ->
Registered(id, new.data)
}
) {
val id = uuid4().toString()
id to Registered(id, it.data)
}
val registereds = crudRepo.create(testData.map { New(it) })
val cacheRepo = FullCRUDCacheRepo(
crudRepo,
kvCache,
idGetter = { it.id }
)
cacheRepo.getAll().forEach { (id, value) ->
assertTrue {
registereds.first {
it.id == id
} == value
}
}
}
@Test
fun removingWorksProperly() = runTest {
val testData = (0 until 1000).map {
(it.toString() + uuid4().toString())
}
val kvCache = MapKeyValueRepo<String, Registered>()
val crudRepo = MapCRUDRepo<Registered, String, New>(
{ new, id, old ->
Registered(id, new.data)
}
) {
val id = uuid4().toString()
id to Registered(id, it.data)
}
val registereds = crudRepo.create(testData.map { New(it) })
val cacheRepo = FullCRUDCacheRepo(
crudRepo,
kvCache,
idGetter = { it.id }
)
registereds.forEach {
val id = it.id
assertTrue {
cacheRepo.getAll()[id] == it
}
cacheRepo.deleteById(id)
assertFalse {
cacheRepo.contains(id)
}
}
assertEquals(0, cacheRepo.count())
}
}

View File

@@ -0,0 +1,92 @@
package full
import com.benasher44.uuid.uuid4
import dev.inmo.micro_utils.repos.*
import dev.inmo.micro_utils.repos.cache.full.FullKeyValueCacheRepo
import korlibs.time.seconds
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class FullKeyValueCacheRepoTests {
@Test
fun creatingWorksProperly() = runTest(timeout = 120.seconds) {
val testData = (0 until 1000).associate {
("$it-" + uuid4().toString()) to "$it-" + uuid4().toString()
}
val updatedTestData = testData.keys.associateWith {
"$it-" + uuid4().toString()
}
val kvCache = MapKeyValueRepo<String, String>()
val kvRepo = MapKeyValueRepo<String, String>()
val cacheRepo = FullKeyValueCacheRepo(
kvRepo,
kvCache
)
testData.forEach {
cacheRepo.set(it.key, it.value)
assertEquals(it.value, cacheRepo.get(it.key))
assertEquals(it.value, kvRepo.get(it.key))
assertEquals(it.value, kvCache.get(it.key))
}
updatedTestData.forEach {
cacheRepo.set(it.key, it.value)
assertEquals(cacheRepo.get(it.key), it.value)
assertEquals(kvRepo.get(it.key), it.value)
assertEquals(kvCache.get(it.key), it.value)
}
}
@Test
fun precachingWorksProperly() = runTest {
val testData = (0 until 1000).associate {
(it.toString() + uuid4().toString()) to uuid4().toString()
}
val kvCache = MapKeyValueRepo<String, String>()
val kvRepo = MapKeyValueRepo<String, String>()
kvRepo.set(testData)
val cacheRepo = FullKeyValueCacheRepo(
kvRepo,
kvCache
)
cacheRepo.getAll().forEach { (id, value) ->
assertTrue {
testData[id] == value
}
}
}
@Test
fun unsettingWorksProperly() = runTest {
val testData = (0 until 1000).associate {
(it.toString() + uuid4().toString()) to uuid4().toString()
}
val kvCache = MapKeyValueRepo<String, String>()
val kvRepo = MapKeyValueRepo<String, String>()
kvRepo.set(testData)
val cacheRepo = FullKeyValueCacheRepo(
kvRepo,
kvCache
)
testData.forEach {
val id = it.key
assertTrue {
cacheRepo.getAll()[id] == it.value
}
cacheRepo.unset(id)
assertFalse {
cacheRepo.contains(id)
}
}
assertEquals(0, cacheRepo.count())
}
}

View File

@@ -0,0 +1,58 @@
package full
import com.benasher44.uuid.uuid4
import dev.inmo.micro_utils.repos.*
import dev.inmo.micro_utils.repos.cache.full.FullKeyValuesCacheRepo
import dev.inmo.micro_utils.repos.pagination.maxPagePagination
import korlibs.time.days
import korlibs.time.seconds
import korlibs.time.years
import kotlinx.coroutines.test.runTest
import kotlin.test.*
class FullKeyValuesCacheRepoTests {
@Test
fun creatingWorksProperly() = runTest(timeout = 120.seconds) {
val testData = (0 until 1000).associate {
("$it-" + uuid4().toString()) to (0 until 1000).map {
"$it-" + uuid4().toString()
}.sorted()
}
val updatedTestData = testData.keys.associateWith {
(0 until 1000).map {
"$it-" + uuid4().toString()
}.sorted()
}
val addedData = testData.keys.associateWith {
"$it-" + uuid4().toString()
}
val kvCache = MapKeyValueRepo<String, List<String>>()
val kvRepo = MapKeyValuesRepo<String, String>()
val cacheRepo = FullKeyValuesCacheRepo(
kvRepo,
kvCache
)
testData.forEach {
cacheRepo.set(it.key, it.value)
assertContentEquals(it.value, cacheRepo.getAll(it.key))
assertContentEquals(it.value, kvRepo.getAll(it.key))
assertContentEquals(it.value, kvCache.get(it.key) ?.sorted())
}
updatedTestData.forEach {
cacheRepo.set(it.key, it.value)
assertContentEquals(it.value, cacheRepo.getAll(it.key))
assertContentEquals(it.value, kvRepo.getAll(it.key))
assertContentEquals(it.value, kvCache.get(it.key) ?.sorted())
}
addedData.forEach {
cacheRepo.add(it.key, it.value)
assertTrue(cacheRepo.contains(it.key, it.value))
assertTrue(kvRepo.contains(it.key, it.value))
assertTrue(kvCache.get(it.key) !!.contains(it.value))
}
}
}

View File

@@ -0,0 +1,69 @@
plugins {
id "org.jetbrains.kotlin.multiplatform"
id "org.jetbrains.kotlin.plugin.serialization"
id "com.android.library"
}
project.version = "$version"
project.group = "$group"
kotlin {
jvm {
compilations.main {
kotlinOptions {
jvmTarget = "17"
}
}
}
js (IR) {
browser()
nodejs()
}
androidTarget {
compilations.all {
kotlinOptions {
jvmTarget = "17"
}
}
}
linuxX64()
mingwX64()
linuxArm64()
sourceSets {
commonMain {
dependencies {
implementation kotlin('stdlib')
api libs.kt.serialization
api kotlin('test')
api kotlin('test-annotations-common')
api libs.kt.coroutines.test
api project(":micro_utils.repos.common")
}
}
jvmMain {
dependencies {
implementation kotlin('test-junit')
}
}
jsMain {
dependencies {
implementation kotlin('test-js')
}
}
nativeMain.dependsOn commonMain
linuxX64Main.dependsOn nativeMain
mingwX64Main.dependsOn nativeMain
linuxArm64Main.dependsOn nativeMain
androidMain.dependsOn jvmMain
}
}
apply from: "$defaultAndroidSettingsPresetPath"
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}

View File

@@ -0,0 +1,82 @@
package dev.inmo.micro_utils.repos.common.tests
import com.benasher44.uuid.uuid4
import dev.inmo.micro_utils.repos.CRUDRepo
import dev.inmo.micro_utils.repos.create
import dev.inmo.micro_utils.repos.deleteById
import korlibs.time.seconds
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.Serializable
import kotlin.test.*
abstract class CommonCRUDRepoTests : CommonRepoTests<CRUDRepo<CommonCRUDRepoTests.Registered, String, CommonCRUDRepoTests.New>>() {
@Serializable
data class New(
val data: String
)
@Serializable
data class Registered(
val id: String,
val data: String
)
@Test
fun creatingWorksProperly() = runTest(timeout = 120.seconds) {
val crudRepo = repoCreator()
val testData = (0 until testSequencesSize).map {
("$it-" + uuid4().toString())
}
val updatedTestData = (0 until 1000).map {
("$it-" + uuid4().toString())
}
val registereds = testData.map {
val created = crudRepo.create(New(it)).first()
assertEquals(it, created.data)
assertEquals(crudRepo.getById(created.id), created)
created
}
crudRepo.getAll().forEach { (id, value) ->
assertTrue {
registereds.first {
it.id == id
} == value
}
}
val updatedRegistereds = registereds.mapIndexed { i, it ->
val updated = crudRepo.update(it.id, New(updatedTestData[i])) ?: error("Unable to update data for $it")
assertEquals(updatedTestData[i], updated.data)
assertEquals(crudRepo.getById(updated.id), updated)
updated
}
crudRepo.getAll().forEach { (id, value) ->
assertTrue {
updatedRegistereds.first {
it.id == id
} == value
}
}
}
@Test
fun removingWorksProperly() = runTest {
val crudRepo = repoCreator()
val testData = (0 until testSequencesSize).map {
(it.toString() + uuid4().toString())
}
val registereds = crudRepo.create(testData.map { New(it) })
registereds.forEach {
val id = it.id
assertTrue {
crudRepo.getAll()[id] == it
}
crudRepo.deleteById(id)
assertFalse {
crudRepo.contains(id)
}
}
assertEquals(0, crudRepo.count())
}
}

View File

@@ -0,0 +1,55 @@
package dev.inmo.micro_utils.repos.common.tests
import com.benasher44.uuid.uuid4
import dev.inmo.micro_utils.repos.*
import korlibs.time.seconds
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
abstract class CommonKeyValueRepoTests : CommonRepoTests<KeyValueRepo<String, String>>() {
@Test
fun creatingWorksProperly() = runTest(timeout = 120.seconds) {
val repo = repoCreator()
val testData = (0 until testSequencesSize).associate {
("$it-" + uuid4().toString()) to "$it-" + uuid4().toString()
}
val updatedTestData = testData.keys.associateWith {
"$it-" + uuid4().toString()
}
testData.forEach {
repo.set(it.key, it.value)
assertEquals(it.value, repo.get(it.key))
}
updatedTestData.forEach {
repo.set(it.key, it.value)
assertEquals(repo.get(it.key), it.value)
}
}
@Test
fun unsettingWorksProperly() = runTest {
val repo = repoCreator()
val testData = (0 until testSequencesSize).associate {
(it.toString() + uuid4().toString()) to uuid4().toString()
}
repo.set(testData)
testData.forEach {
val id = it.key
assertTrue {
repo.getAll()[id] == it.value
}
repo.unset(id)
assertFalse {
repo.contains(id)
}
}
assertEquals(0, repo.count())
}
}

View File

@@ -0,0 +1,49 @@
package dev.inmo.micro_utils.repos.common.tests
import com.benasher44.uuid.uuid4
import dev.inmo.micro_utils.repos.*
import korlibs.time.seconds
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runTest
import kotlin.test.*
abstract class CommonKeyValuesRepoTests : CommonRepoTests<KeyValuesRepo<String, String>>() {
@Test
fun creatingWorksProperly() = runTest(timeout = 120.seconds) {
val repo = repoCreator()
val testData = (0 until testSequencesSize).associate {
("$it-" + uuid4().toString()) to (0 until 1000).map {
"$it-" + uuid4().toString()
}.sorted()
}
val updatedTestData = testData.keys.associateWith {
(0 until 1000).map {
"$it-" + uuid4().toString()
}.sorted()
}
val addedData = testData.keys.associateWith {
"$it-" + uuid4().toString()
}
updatedTestData.map {
launch {
repo.set(it.key, it.value)
assertContentEquals(it.value.sorted(), repo.getAll(it.key).sorted())
}
}.joinAll()
updatedTestData.map {
launch {
repo.set(it.key, it.value)
val all = repo.getAll(it.key)
assertContentEquals(it.value.sorted(), all.sorted())
}
}.joinAll()
addedData.forEach {
repo.add(it.key, it.value)
assertTrue(repo.contains(it.key, it.value))
}
}
}

View File

@@ -0,0 +1,6 @@
package dev.inmo.micro_utils.repos.common.tests
abstract class CommonRepoTests<T> {
protected open val testSequencesSize = 1000
protected abstract val repoCreator: suspend () -> T
}

View File

@@ -14,5 +14,12 @@ kotlin {
api internalProject("micro_utils.pagination.exposed")
}
}
jvmTest {
dependencies {
api libs.sqlite
api libs.jb.exposed.jdbc
api project(":micro_utils.repos.common.tests")
}
}
}
}

View File

@@ -52,9 +52,9 @@ abstract class AbstractExposedWriteCRUDRepo<ObjectType, IdType, InputValueType>(
*
* @return In case when id for the model has been created new [IdType] should be returned
*/
protected open fun createAndInsertId(value: InputValueType, it: InsertStatement<Number>): IdType? = null
protected open fun createAndInsertId(value: InputValueType, it: UpdateBuilder<Int>): IdType? = null
protected open fun insert(value: InputValueType, it: InsertStatement<Number>) {
protected open fun insert(value: InputValueType, it: UpdateBuilder<Int>) {
val id = createAndInsertId(value, it)
update(id, value, it as UpdateBuilder<Int>)
}

View File

@@ -23,11 +23,11 @@ abstract class AbstractExposedKeyValueRepo<Key, Value>(
override val onValueRemoved: Flow<Key> = _onValueRemoved.asSharedFlow()
protected abstract fun update(k: Key, v: Value, it: UpdateBuilder<Int>)
protected abstract fun insertKey(k: Key, v: Value, it: InsertStatement<Number>)
protected abstract fun insertKey(k: Key, v: Value, it: UpdateBuilder<Int>)
protected open fun insert(k: Key, v: Value, it: InsertStatement<Number>) {
protected open fun insert(k: Key, v: Value, it: UpdateBuilder<Int>) {
insertKey(k, v, it)
update(k, v, it as UpdateBuilder<Int>)
update(k, v, it)
}
override suspend fun set(toSet: Map<Key, Value>) {

View File

@@ -5,6 +5,7 @@ import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.*
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.statements.InsertStatement
import org.jetbrains.exposed.sql.statements.UpdateBuilder
import org.jetbrains.exposed.sql.transactions.transaction
abstract class AbstractExposedKeyValuesRepo<Key, Value>(
@@ -26,7 +27,7 @@ abstract class AbstractExposedKeyValuesRepo<Key, Value>(
override val onDataCleared: Flow<Key>
get() = _onDataCleared.asSharedFlow()
protected abstract fun insert(k: Key, v: Value, it: InsertStatement<Number>)
protected abstract fun insert(k: Key, v: Value, it: UpdateBuilder<Int>)
override suspend fun add(toAdd: Map<Key, List<Value>>) {
transaction(database) {
@@ -48,6 +49,28 @@ abstract class AbstractExposedKeyValuesRepo<Key, Value>(
}.forEach { _onNewValue.emit(it) }
}
override suspend fun set(toSet: Map<Key, List<Value>>) {
if (toSet.isEmpty()) return
val prepreparedData = toSet.flatMap { (k, vs) ->
vs.map { v ->
k to v
}
}
transaction(database) {
deleteWhere {
selectByIds(it, toSet.keys.toList())
}
batchInsert(
prepreparedData,
) { (k, v) ->
insert(k, v, this)
}.map {
it.asKey to it.asObject
}
}.forEach { _onNewValue.emit(it) }
}
override suspend fun remove(toRemove: Map<Key, List<Value>>) {
transaction(database) {
toRemove.keys.flatMap { k ->

View File

@@ -83,8 +83,8 @@ abstract class AbstractExposedReadKeyValuesRepo<Key, Value>(
}
}
override suspend fun getAll(k: Key, reverseLists: Boolean): List<Value> = transaction(database) {
val query = if (reverseLists) {
override suspend fun getAll(k: Key, reversed: Boolean): List<Value> = transaction(database) {
val query = if (reversed) {
selectAll().where { selectById(k) }.orderBy(keyColumn, SortOrder.DESC)
} else {
selectAll().where { selectById(k) }

View File

@@ -0,0 +1,21 @@
package full
import com.benasher44.uuid.uuid4
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.transactions.transactionManager
import org.sqlite.JDBC
import java.io.File
import java.sql.Connection
fun filename() = "${uuid4()}.local.sql".also {
val file = File(it)
file.createNewFile()
file.deleteOnExit()
}
fun createDatabase(filename: String) = Database.connect(
url = "jdbc:sqlite:$filename",
driver = JDBC::class.qualifiedName!!
).also {
it.transactionManager.defaultIsolationLevel = Connection.TRANSACTION_SERIALIZABLE
it.connector().close()
}

View File

@@ -0,0 +1,62 @@
package full
import com.benasher44.uuid.uuid4
import dev.inmo.micro_utils.repos.CRUDRepo
import dev.inmo.micro_utils.repos.common.tests.CommonCRUDRepoTests
import dev.inmo.micro_utils.repos.exposed.AbstractExposedCRUDRepo
import dev.inmo.micro_utils.repos.exposed.initTable
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.ISqlExpressionBuilder
import org.jetbrains.exposed.sql.Op
import org.jetbrains.exposed.sql.ResultRow
import org.jetbrains.exposed.sql.statements.InsertStatement
import org.jetbrains.exposed.sql.statements.UpdateBuilder
import java.io.File
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
class ExposedCRUDRepoTests : CommonCRUDRepoTests() {
class Repo(override val database: Database) : AbstractExposedCRUDRepo<Registered, String, New>() {
val idColumn = text("_id")
val dataColumn = text("data")
override val primaryKey: PrimaryKey = PrimaryKey(idColumn)
override val ResultRow.asId: String
get() = get(idColumn)
override val ResultRow.asObject: Registered
get() = Registered(
asId,
get(dataColumn)
)
override val selectById: ISqlExpressionBuilder.(String) -> Op<Boolean> = { idColumn.eq(it) }
init {
initTable()
}
override fun update(id: String?, value: New, it: UpdateBuilder<Int>) {
it[idColumn] = id ?: uuid4().toString()
it[dataColumn] = value.data
}
override fun InsertStatement<Number>.asObject(value: New): Registered {
return Registered(
get(idColumn),
get(dataColumn)
)
}
}
val filename = filename()
var database: Database? = null
override val repoCreator: suspend () -> CRUDRepo<Registered, String, New> = { Repo(database!!) }
@BeforeTest
fun beforeTest() {
database = createDatabase(filename)
}
@AfterTest
fun afterTest() {
database = null
File(filename).delete()
}
}

View File

@@ -0,0 +1,56 @@
package full
import dev.inmo.micro_utils.repos.KeyValueRepo
import dev.inmo.micro_utils.repos.common.tests.CommonKeyValueRepoTests
import dev.inmo.micro_utils.repos.exposed.initTable
import dev.inmo.micro_utils.repos.exposed.keyvalue.AbstractExposedKeyValueRepo
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.ISqlExpressionBuilder
import org.jetbrains.exposed.sql.Op
import org.jetbrains.exposed.sql.ResultRow
import org.jetbrains.exposed.sql.statements.UpdateBuilder
import java.io.File
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
class ExposedKeyValueRepoTests : CommonKeyValueRepoTests() {
class Repo(override val database: Database) : AbstractExposedKeyValueRepo<String, String>(database) {
override val keyColumn = text("_id")
val dataColumn = text("data")
override val primaryKey: PrimaryKey = PrimaryKey(keyColumn)
override val ResultRow.asKey: String
get() = get(keyColumn)
override val selectByValue: ISqlExpressionBuilder.(String) -> Op<Boolean> = { dataColumn.eq(it) }
override val ResultRow.asObject: String
get() = get(dataColumn)
override val selectById: ISqlExpressionBuilder.(String) -> Op<Boolean> = { keyColumn.eq(it) }
init {
initTable()
}
override fun update(k: String, v: String, it: UpdateBuilder<Int>) {
it[keyColumn] = k
it[dataColumn] = v
}
override fun insertKey(k: String, v: String, it: UpdateBuilder<Int>) {
it[keyColumn] = k
}
}
val filename = filename()
var database: Database? = null
@BeforeTest
fun beforeTest() {
database = createDatabase(filename)
}
@AfterTest
fun afterTest() {
database = null
File(filename).delete()
}
override val repoCreator: suspend () -> KeyValueRepo<String, String> = { Repo(database!!) }
}

View File

@@ -0,0 +1,52 @@
package full
import dev.inmo.micro_utils.repos.KeyValuesRepo
import dev.inmo.micro_utils.repos.common.tests.CommonKeyValuesRepoTests
import dev.inmo.micro_utils.repos.exposed.initTable
import dev.inmo.micro_utils.repos.exposed.onetomany.AbstractExposedKeyValuesRepo
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.ISqlExpressionBuilder
import org.jetbrains.exposed.sql.Op
import org.jetbrains.exposed.sql.ResultRow
import org.jetbrains.exposed.sql.statements.UpdateBuilder
import java.io.File
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
class ExposedKeyValuesRepoTests : CommonKeyValuesRepoTests() {
override val testSequencesSize: Int = 100
class Repo(override val database: Database) : AbstractExposedKeyValuesRepo<String, String>(database) {
override val keyColumn = text("_id")
val dataColumn = text("data")
override val ResultRow.asKey: String
get() = get(keyColumn)
override val selectByValue: ISqlExpressionBuilder.(String) -> Op<Boolean> = { dataColumn.eq(it) }
override val ResultRow.asObject: String
get() = get(dataColumn)
override val selectById: ISqlExpressionBuilder.(String) -> Op<Boolean> = { keyColumn.eq(it) }
init {
initTable()
}
override fun insert(k: String, v: String, it: UpdateBuilder<Int>) {
it[keyColumn] = k
it[dataColumn] = v
}
}
val filename = filename()
var database: Database? = null
@BeforeTest
fun beforeTest() {
database = createDatabase(filename)
}
@AfterTest
fun afterTest() {
database = null
File(filename).delete()
}
override val repoCreator: suspend () -> KeyValuesRepo<String, String> = { Repo(database!!) }
}

View File

@@ -14,5 +14,10 @@ kotlin {
api internalProject("micro_utils.coroutines")
}
}
commonTest {
dependencies {
api project(":micro_utils.repos.common.tests")
}
}
}
}

View File

@@ -24,7 +24,9 @@ class ReadMapKeyValueRepo<Key, Value>(
) : ReadKeyValueRepo<Key, Value> {
constructor(map: Map<Key, Value> = emptyMap()) : this(map, SmartRWLocker())
override suspend fun get(k: Key): Value? = locker.withReadAcquire { map[k] }
override suspend fun get(k: Key): Value? = locker.withReadAcquire {
map[k]
}
override suspend fun values(
pagination: Pagination,
@@ -100,11 +102,13 @@ class WriteMapKeyValueRepo<Key, Value>(
constructor(map: MutableMap<Key, Value> = mutableMapOf()) : this(map, SmartRWLocker())
override suspend fun set(toSet: Map<Key, Value>) {
if (toSet.isEmpty()) return
locker.withWriteLock { map.putAll(toSet) }
toSet.forEach { (k, v) -> _onNewValue.emit(k to v) }
}
override suspend fun unset(toUnset: List<Key>) {
if (toUnset.isEmpty()) return
locker.withWriteLock {
toUnset.mapNotNull { k ->
map.remove(k) ?.let { _ -> k }

View File

@@ -4,6 +4,7 @@ import dev.inmo.micro_utils.coroutines.SmartRWLocker
import dev.inmo.micro_utils.coroutines.withReadAcquire
import dev.inmo.micro_utils.coroutines.withWriteLock
import dev.inmo.micro_utils.pagination.*
import dev.inmo.micro_utils.pagination.utils.optionallyReverse
import dev.inmo.micro_utils.pagination.utils.paginate
import dev.inmo.micro_utils.pagination.utils.reverse
import kotlinx.coroutines.flow.*
@@ -33,6 +34,20 @@ class MapReadKeyValuesRepo<Key, Value>(
)
}
override suspend fun getAll(k: Key, reversed: Boolean): List<Value> {
return locker.withReadAcquire { map[k] ?.optionallyReverse(reversed) ?: return emptyList() }
}
override suspend fun getAll(reverseLists: Boolean): Map<Key, List<Value>> {
return locker.withReadAcquire {
if (reverseLists) {
map.mapValues { it.value.reversed() }
} else {
map.toMap()
}
}
}
override suspend fun keys(pagination: Pagination, reversed: Boolean): PaginationResult<Key> {
val keys = locker.withReadAcquire {
map.keys
@@ -108,7 +123,24 @@ class MapWriteKeyValuesRepo<Key, Value>(
}
}
override suspend fun set(toSet: Map<Key, List<Value>>) {
if (toSet.isEmpty()) return
locker.withWriteLock {
map.putAll(
toSet.mapValues { it.value.toMutableList() }
)
}
toSet.forEach { (k, v) ->
v.forEach {
_onNewValue.emit(k to it)
}
}
}
override suspend fun remove(toRemove: Map<Key, List<Value>>) {
if (toRemove.isEmpty()) return
val removed = mutableListOf<Pair<Key, Value>>()
val cleared = mutableListOf<Key>()
locker.withWriteLock {

View File

@@ -0,0 +1,19 @@
package full
import com.benasher44.uuid.uuid4
import dev.inmo.micro_utils.repos.CRUDRepo
import dev.inmo.micro_utils.repos.MapCRUDRepo
import dev.inmo.micro_utils.repos.common.tests.CommonCRUDRepoTests
class InMemoryCRUDRepoTests : CommonCRUDRepoTests() {
override val repoCreator: suspend () -> CRUDRepo<Registered, String, New> = {
MapCRUDRepo(
{ new, id, old ->
Registered(id, new.data)
}
) {
val id = uuid4().toString()
id to Registered(id, it.data)
}
}
}

View File

@@ -0,0 +1,9 @@
package full
import dev.inmo.micro_utils.repos.KeyValueRepo
import dev.inmo.micro_utils.repos.MapKeyValueRepo
import dev.inmo.micro_utils.repos.common.tests.CommonKeyValueRepoTests
class InMemoryKeyValueRepoTests : CommonKeyValueRepoTests() {
override val repoCreator: suspend () -> KeyValueRepo<String, String> = { MapKeyValueRepo() }
}

View File

@@ -0,0 +1,9 @@
package full
import dev.inmo.micro_utils.repos.KeyValuesRepo
import dev.inmo.micro_utils.repos.MapKeyValuesRepo
import dev.inmo.micro_utils.repos.common.tests.CommonKeyValuesRepoTests
class InMemoryKeyValuesRepoTests : CommonKeyValuesRepoTests() {
override val repoCreator: suspend () -> KeyValuesRepo<String, String> = { MapKeyValuesRepo() }
}

View File

@@ -16,6 +16,7 @@ kotlin {
jvmTest {
dependencies {
implementation internalProject("micro_utils.repos.common")
implementation internalProject("micro_utils.repos.common.tests")
implementation internalProject("micro_utils.repos.ktor.client")
implementation internalProject("micro_utils.repos.ktor.server")
implementation internalProject("micro_utils.repos.inmemory")

View File

@@ -1,3 +1,5 @@
package dev.inmo.micro_utils.repos.ktor
import com.benasher44.uuid.uuid4
import kotlinx.serialization.Serializable

View File

@@ -1,4 +1,8 @@
package dev.inmo.micro_utils.repos.ktor
import com.benasher44.uuid.uuid4
import dev.inmo.micro_utils.repos.*
import dev.inmo.micro_utils.repos.common.tests.CommonCRUDRepoTests
import dev.inmo.micro_utils.repos.ktor.client.crud.KtorCRUDRepoClient
import dev.inmo.micro_utils.repos.ktor.server.crud.configureCRUDRepoRoutes
import io.ktor.client.HttpClient
@@ -8,17 +12,53 @@ import io.ktor.serialization.kotlinx.KotlinxWebsocketSerializationConverter
import io.ktor.serialization.kotlinx.json.json
import io.ktor.server.application.install
import io.ktor.server.cio.CIO
import io.ktor.server.engine.*
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
import io.ktor.server.routing.routing
import io.ktor.server.websocket.WebSockets
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestResult
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
class CRUDTests {
@OptIn(ExperimentalCoroutinesApi::class)
class KtorCRUDRepoTests : CommonCRUDRepoTests() {
private var engine: ApplicationEngine? = null
@BeforeTest
fun beforeTest() {
engine = KtorRepoTestsHelper.beforeTest {
configureCRUDRepoRoutes(
MapCRUDRepo<Registered, String, New>(
{ new, id, old ->
Registered(id, new.data)
}
) {
val id = uuid4().toString()
id to Registered(id, it.data)
}
) {
it
}
}
}
@AfterTest
fun afterTest() {
engine ?.let(KtorRepoTestsHelper::afterTest)
}
override val repoCreator: suspend () -> CRUDRepo<Registered, String, New> = {
KtorCRUDRepoClient<Registered, String, New>(
"http://127.0.0.1:23456",
KtorRepoTestsHelper.client(),
ContentType.Application.Json
) {
it
}
}
@Test
fun testCRUDFunctions() {
runTest {
@@ -33,7 +73,7 @@ class CRUDTests {
}
val server = io.ktor.server.engine.embeddedServer(
CIO,
23456,
34567,
"127.0.0.1"
) {
install(ContentNegotiation) {
@@ -60,7 +100,7 @@ class CRUDTests {
}
}
val crudClient = KtorCRUDRepoClient<ComplexData, Int, SimpleData>(
"http://127.0.0.1:23456",
"http://127.0.0.1:34567",
client,
ContentType.Application.Json
) {

View File

@@ -1,8 +1,13 @@
package dev.inmo.micro_utils.repos.ktor
import dev.inmo.micro_utils.pagination.firstPageWithOneElementPagination
import dev.inmo.micro_utils.pagination.utils.getAllWithNextPaging
import dev.inmo.micro_utils.repos.*
import dev.inmo.micro_utils.repos.common.tests.CommonKeyValueRepoTests
import dev.inmo.micro_utils.repos.ktor.client.key.value.KtorKeyValueRepoClient
import dev.inmo.micro_utils.repos.ktor.client.key.values.KtorKeyValuesRepoClient
import dev.inmo.micro_utils.repos.ktor.server.key.value.configureKeyValueRepoRoutes
import dev.inmo.micro_utils.repos.ktor.server.key.values.configureKeyValuesRepoRoutes
import io.ktor.client.HttpClient
import io.ktor.client.plugins.logging.Logging
import io.ktor.http.ContentType
@@ -10,17 +15,47 @@ import io.ktor.serialization.kotlinx.KotlinxWebsocketSerializationConverter
import io.ktor.serialization.kotlinx.json.json
import io.ktor.server.application.install
import io.ktor.server.cio.CIO
import io.ktor.server.engine.*
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
import io.ktor.server.routing.routing
import io.ktor.server.websocket.WebSockets
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestResult
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.json.Json
import kotlin.test.*
class KVTests {
@OptIn(ExperimentalCoroutinesApi::class)
class KtorKeyValueRepoTests : CommonKeyValueRepoTests() {
private var engine: ApplicationEngine? = null
override val repoCreator: suspend () -> KeyValueRepo<String, String> = {
KtorKeyValueRepoClient(
"http://127.0.0.1:23456",
KtorRepoTestsHelper.client(),
ContentType.Application.Json,
String.serializer(),
String.serializer(),
Json
)
}
@BeforeTest
fun beforeTest() {
engine = KtorRepoTestsHelper.beforeTest {
configureKeyValueRepoRoutes(
MapKeyValueRepo(),
String.serializer(),
String.serializer(),
Json
)
}
}
@AfterTest
fun afterTest() {
engine ?.let(KtorRepoTestsHelper::afterTest)
}
@Test
fun testKVFunctions() {
runTest {
@@ -28,7 +63,7 @@ class KVTests {
val repo = MapKeyValueRepo<Int, ComplexData>(map)
val server = io.ktor.server.engine.embeddedServer(
CIO,
23456,
34567,
"127.0.0.1"
) {
install(ContentNegotiation) {
@@ -56,7 +91,7 @@ class KVTests {
}
}
val crudClient = KtorKeyValueRepoClient<Int, ComplexData>(
"http://127.0.0.1:23456",
"http://127.0.0.1:34567",
client,
ContentType.Application.Json,
Int.serializer(),

View File

@@ -1,26 +1,59 @@
package dev.inmo.micro_utils.repos.ktor
import dev.inmo.micro_utils.pagination.firstPageWithOneElementPagination
import dev.inmo.micro_utils.pagination.utils.getAllWithNextPaging
import dev.inmo.micro_utils.repos.*
import dev.inmo.micro_utils.repos.common.tests.CommonKeyValuesRepoTests
import dev.inmo.micro_utils.repos.ktor.client.key.values.KtorKeyValuesRepoClient
import dev.inmo.micro_utils.repos.ktor.server.key.values.configureKeyValuesRepoRoutes
import io.ktor.client.HttpClient
import io.ktor.client.plugins.logging.Logging
import io.ktor.client.*
import io.ktor.client.plugins.logging.*
import io.ktor.http.ContentType
import io.ktor.serialization.kotlinx.KotlinxWebsocketSerializationConverter
import io.ktor.serialization.kotlinx.json.json
import io.ktor.server.application.install
import io.ktor.server.cio.CIO
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
import io.ktor.server.routing.routing
import io.ktor.server.websocket.WebSockets
import kotlinx.coroutines.ExperimentalCoroutinesApi
import io.ktor.serialization.kotlinx.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.cio.*
import io.ktor.server.engine.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.routing.*
import io.ktor.server.websocket.*
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.json.Json
import kotlin.test.*
class KVsTests {
@OptIn(ExperimentalCoroutinesApi::class)
class KtorKeyValuesRepoTests : CommonKeyValuesRepoTests() {
private var engine: ApplicationEngine? = null
override val testSequencesSize: Int
get() = 100
override val repoCreator: suspend () -> KeyValuesRepo<String, String> = {
KtorKeyValuesRepoClient(
"http://127.0.0.1:23456",
KtorRepoTestsHelper.client(),
ContentType.Application.Json,
String.serializer(),
String.serializer(),
Json
)
}
@BeforeTest
fun beforeTest() {
engine = KtorRepoTestsHelper.beforeTest {
configureKeyValuesRepoRoutes(
MapKeyValuesRepo(),
String.serializer(),
String.serializer(),
Json
)
}
}
@AfterTest
fun afterTest() {
engine ?.let(KtorRepoTestsHelper::afterTest)
}
@Test
fun testKVsFunctions() {
runTest {
@@ -28,7 +61,7 @@ class KVsTests {
val repo = MapKeyValuesRepo(map)
val server = io.ktor.server.engine.embeddedServer(
CIO,
23456,
34567,
"127.0.0.1"
) {
install(ContentNegotiation) {
@@ -42,7 +75,7 @@ class KVsTests {
repo,
Int.serializer(),
ComplexData.serializer(),
Json {}
Json
)
}
}.start(false)
@@ -56,7 +89,7 @@ class KVsTests {
}
}
val crudClient = KtorKeyValuesRepoClient(
"http://127.0.0.1:23456",
"http://127.0.0.1:34567",
client,
ContentType.Application.Json,
Int.serializer(),

View File

@@ -0,0 +1,44 @@
package dev.inmo.micro_utils.repos.ktor
import io.ktor.client.*
import io.ktor.client.plugins.logging.*
import io.ktor.serialization.kotlinx.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.cio.*
import io.ktor.server.engine.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.routing.*
import io.ktor.server.websocket.*
import kotlinx.serialization.json.Json
object KtorRepoTestsHelper {
fun beforeTest(routingConfigurator: Routing.() -> Unit): ApplicationEngine {
return embeddedServer(
CIO,
23456,
"127.0.0.1"
) {
install(ContentNegotiation) {
json()
}
install(WebSockets) {
contentConverter = KotlinxWebsocketSerializationConverter(Json)
}
routing(routingConfigurator)
}.start(false)
}
fun afterTest(engine: ApplicationEngine) {
engine.stop()
}
fun client(): HttpClient = HttpClient {
install(io.ktor.client.plugins.contentnegotiation.ContentNegotiation) {
json()
}
install(Logging)
install(io.ktor.client.plugins.websocket.WebSockets) {
contentConverter = KotlinxWebsocketSerializationConverter(Json)
}
}
}

View File

@@ -1,3 +1,5 @@
package dev.inmo.micro_utils.repos.ktor
import com.benasher44.uuid.uuid4
import kotlinx.serialization.Serializable

View File

@@ -18,6 +18,7 @@ String[] includes = [
":language_codes",
":language_codes:generator",
":repos:common",
":repos:common:tests",
":repos:generator",
":repos:generator:test",
":repos:cache",
@@ -42,6 +43,8 @@ String[] includes = [
":serialization:mapper",
":startup:plugin",
":startup:launcher",
":colors",
":colors:common",
":resources",
@@ -55,6 +58,10 @@ String[] includes = [
":ksp:sealed:generator",
":ksp:sealed:generator:test",
":ksp:classcasts",
":ksp:classcasts:generator",
":ksp:classcasts:generator:test",
":dokka"
]

View File

@@ -13,6 +13,7 @@ kotlin {
api libs.kslog
api libs.kt.reflect
api project(":micro_utils.coroutines")
api libs.uuid
}
}
jsMain {

View File

@@ -1,5 +1,42 @@
package dev.inmo.micro_utils.startup.plugin
import com.benasher44.uuid.uuid4
import kotlinx.serialization.KSerializer
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
expect object StartPluginSerializer : KSerializer<StartPlugin>
object StartPluginSerializer : KSerializer<StartPlugin> {
private val registeredPlugins = mutableMapOf<String, StartPlugin>()
private val registeredPluginsByPlugin = mutableMapOf<StartPlugin, String>()
override val descriptor: SerialDescriptor = String.serializer().descriptor
override fun deserialize(decoder: Decoder): StartPlugin {
alternativeDeserialize(decoder) ?.let { return it }
val name = decoder.decodeString()
return registeredPlugins[name] ?: error("Unable to find startup plugin for $name")
}
override fun serialize(encoder: Encoder, value: StartPlugin) {
if (alternativeSerialize(encoder, value)) {
return
}
val name = registeredPluginsByPlugin[value] ?: uuid4().toString().also {
registeredPlugins[it] = value
registeredPluginsByPlugin[value] = it
}
encoder.encodeString(name)
}
/**
* Register plugin inside of this [KSerializer]. Since plugin has been registered, you may use its [name] in any
* serialized [dev.inmo.micro_utils.startup.launcher.Config] to retrieve [plugin] you passed here
*/
fun registerPlugin(name: String, plugin: StartPlugin) {
registeredPlugins[name] = plugin
}
}
internal expect fun alternativeDeserialize(decoder: Decoder): StartPlugin?
internal expect fun alternativeSerialize(encoder: Encoder, value: StartPlugin): Boolean

View File

@@ -0,0 +1,13 @@
package dev.inmo.micro_utils.startup.plugin
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
internal actual fun alternativeDeserialize(decoder: Decoder): StartPlugin? {
return null
}
internal actual fun alternativeSerialize(
encoder: Encoder,
value: StartPlugin
): Boolean = false

View File

@@ -1,35 +0,0 @@
package dev.inmo.micro_utils.startup.plugin
import com.benasher44.uuid.uuid4
import kotlinx.serialization.KSerializer
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
actual object StartPluginSerializer : KSerializer<StartPlugin> {
private val registeredPlugins = mutableMapOf<String, StartPlugin>()
private val registeredPluginsByPlugin = mutableMapOf<StartPlugin, String>()
override val descriptor: SerialDescriptor = String.serializer().descriptor
override fun deserialize(decoder: Decoder): StartPlugin {
val name = decoder.decodeString()
return registeredPlugins[name] ?: error("Unable to find startup plugin for $name")
}
override fun serialize(encoder: Encoder, value: StartPlugin) {
val name = registeredPluginsByPlugin[value] ?: uuid4().toString().also {
registeredPlugins[it] = value
registeredPluginsByPlugin[value] = it
}
encoder.encodeString(name)
}
/**
* Register plugin inside of this [KSerializer]. Since plugin has been registered, you may use its [name] in any
* serialized [dev.inmo.micro_utils.startup.launcher.Config] to retrieve [plugin] you passed here
*/
fun registerPlugin(name: String, plugin: StartPlugin) {
registeredPlugins[name] = plugin
}
}

View File

@@ -0,0 +1,17 @@
package dev.inmo.micro_utils.startup.plugin
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
internal actual fun alternativeDeserialize(decoder: Decoder): StartPlugin? {
val kclass = Class.forName(decoder.decodeString()).kotlin
return (kclass.objectInstance ?: kclass.constructors.first { it.parameters.isEmpty() }.call()) as StartPlugin
}
internal actual fun alternativeSerialize(
encoder: Encoder,
value: StartPlugin
): Boolean {
encoder.encodeString(value::class.java.canonicalName ?: return false)
return true
}

View File

@@ -1,23 +0,0 @@
package dev.inmo.micro_utils.startup.plugin
import kotlinx.serialization.KSerializer
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
actual object StartPluginSerializer : KSerializer<StartPlugin> {
override val descriptor: SerialDescriptor
get() = String.serializer().descriptor
override fun deserialize(decoder: Decoder): StartPlugin {
val kclass = Class.forName(decoder.decodeString()).kotlin
return (kclass.objectInstance ?: kclass.constructors.first { it.parameters.isEmpty() }.call()) as StartPlugin
}
override fun serialize(encoder: Encoder, value: StartPlugin) {
encoder.encodeString(
value::class.java.canonicalName
)
}
}

View File

@@ -1,36 +0,0 @@
package dev.inmo.micro_utils.startup.plugin
import com.benasher44.uuid.uuid4
import kotlinx.serialization.KSerializer
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlin.reflect.KClass
actual object StartPluginSerializer : KSerializer<StartPlugin> {
private val registeredPlugins = mutableMapOf<String, StartPlugin>()
private val registeredPluginsByPlugin = mutableMapOf<StartPlugin, String>()
override val descriptor: SerialDescriptor = String.serializer().descriptor
override fun deserialize(decoder: Decoder): StartPlugin {
val name = decoder.decodeString()
return registeredPlugins[name] ?: error("Unable to find startup plugin for $name")
}
override fun serialize(encoder: Encoder, value: StartPlugin) {
val name = registeredPluginsByPlugin[value] ?: uuid4().toString().also {
registeredPlugins[it] = value
registeredPluginsByPlugin[value] = it
}
encoder.encodeString(name)
}
/**
* Register plugin inside of this [KSerializer]. Since plugin has been registered, you may use its [name] in any
* serialized [dev.inmo.micro_utils.startup.launcher.Config] to retrieve [plugin] you passed here
*/
fun registerPlugin(name: String, plugin: StartPlugin) {
registeredPlugins[name] = plugin
}
}

View File

@@ -1,36 +0,0 @@
package dev.inmo.micro_utils.startup.plugin
import com.benasher44.uuid.uuid4
import kotlinx.serialization.KSerializer
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlin.reflect.KClass
actual object StartPluginSerializer : KSerializer<StartPlugin> {
private val registeredPlugins = mutableMapOf<String, StartPlugin>()
private val registeredPluginsByPlugin = mutableMapOf<StartPlugin, String>()
override val descriptor: SerialDescriptor = String.serializer().descriptor
override fun deserialize(decoder: Decoder): StartPlugin {
val name = decoder.decodeString()
return registeredPlugins[name] ?: error("Unable to find startup plugin for $name")
}
override fun serialize(encoder: Encoder, value: StartPlugin) {
val name = registeredPluginsByPlugin[value] ?: uuid4().toString().also {
registeredPlugins[it] = value
registeredPluginsByPlugin[value] = it
}
encoder.encodeString(name)
}
/**
* Register plugin inside of this [KSerializer]. Since plugin has been registered, you may use its [name] in any
* serialized [dev.inmo.micro_utils.startup.launcher.Config] to retrieve [plugin] you passed here
*/
fun registerPlugin(name: String, plugin: StartPlugin) {
registeredPlugins[name] = plugin
}
}

View File

@@ -0,0 +1,13 @@
package dev.inmo.micro_utils.startup.plugin
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
internal actual fun alternativeDeserialize(decoder: Decoder): StartPlugin? {
return null
}
internal actual fun alternativeSerialize(
encoder: Encoder,
value: StartPlugin
): Boolean = false