Skip to content

Commit

Permalink
Implement kotlinx immutable adapters
Browse files Browse the repository at this point in the history
  • Loading branch information
ZacSweers committed May 10, 2024
1 parent a0de833 commit e58044a
Show file tree
Hide file tree
Showing 7 changed files with 333 additions and 0 deletions.
1 change: 1 addition & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ kotlin-metadata = { module = "org.jetbrains.kotlinx:kotlinx-metadata-jvm", versi
kotlin-reflect = { module = "org.jetbrains.kotlin:kotlin-reflect", version.ref = "kotlin" }
kotlin-gradlePlugin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin" }
kotlin-gradlePlugin-api = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin-api", version.ref = "kotlin" }
kotlinx-immutable = "org.jetbrains.kotlinx:kotlinx-collections-immutable:0.3.7"

kotlinpoet = { module = "com.squareup:kotlinpoet", version.ref = "kotlinpoet" }
kotlinpoet-metadata = { module = "com.squareup:kotlinpoet-metadata", version.ref = "kotlinpoet" }
Expand Down
30 changes: 30 additions & 0 deletions moshi-immutable-adapters/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# moshi-adapters

A collection of Moshi adapters for [kotlinx.collections.immutable](https://github.com/Kotlin/kotlinx.collections.immutable).

## Usage

Gradle dependency

```kotlin
dependencies {
implementation("dev.zacsweers.moshix:moshi-immutable-adapters:<version>")
}
```

In code

```kotlin
val moshi = Moshi.Builder().add(ImmutableCollectionsJsonAdapterFactory()).build()
```

**Supported types**

- `ImmutableCollection`
- `ImmutableList`
- `ImmutableSet`
- `ImmutableMap`
- `PersistentCollection`
- `PersistentList`
- `PersistentSet`
- `PersistentMap`
36 changes: 36 additions & 0 deletions moshi-immutable-adapters/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Copyright (C) 2024 Zac Sweers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
alias(libs.plugins.kotlinJvm)
alias(libs.plugins.ksp)
alias(libs.plugins.mavenPublish)
}

tasks.named<KotlinCompile>("compileTestKotlin") {
compilerOptions { freeCompilerArgs.add("-opt-in=kotlin.ExperimentalStdlibApi") }
}

dependencies {
api(libs.kotlinx.immutable)
api(libs.moshi)
kspTest(libs.moshi.codegen)
testImplementation(libs.moshi.kotlin)
testImplementation(libs.junit)
testImplementation(libs.truth)
}
19 changes: 19 additions & 0 deletions moshi-immutable-adapters/gradle.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#
# Copyright (c) 2024 Zac Sweers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

POM_NAME=Moshi Immutable Adapters
POM_ARTIFACT_ID=moshi-immutable-adapters
POM_PACKAGING=jar
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
package dev.zacsweers.moshix.adapters.immutable

import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.JsonDataException
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import com.squareup.moshi.Moshi
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import kotlinx.collections.immutable.ImmutableCollection
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.ImmutableMap
import kotlinx.collections.immutable.ImmutableSet
import kotlinx.collections.immutable.PersistentCollection
import kotlinx.collections.immutable.PersistentList
import kotlinx.collections.immutable.PersistentMap
import kotlinx.collections.immutable.PersistentSet
import kotlinx.collections.immutable.mutate
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.persistentMapOf
import kotlinx.collections.immutable.persistentSetOf

/**
* A [JsonAdapter.Factory] that creates immutable collection adapters for the following supported
* types:
* - [ImmutableCollection]
* - [ImmutableList]
* - [ImmutableSet]
* - [ImmutableMap]
* - [PersistentCollection]
* - [PersistentList]
* - [PersistentSet]
* - [PersistentMap]
*/
public class ImmutableCollectionsJsonAdapterFactory : JsonAdapter.Factory {
override fun create(type: Type, annotations: Set<Annotation>, moshi: Moshi): JsonAdapter<*>? {
if (type !is ParameterizedType) return null
when (type.rawType) {
ImmutableList::class.java,
ImmutableCollection::class.java,
PersistentList::class.java,
PersistentCollection::class.java -> {
val elementType = type.actualTypeArguments[0]
val elementAdapter = moshi.adapter<Any>(elementType, annotations)
return ImmutableListAdapter(elementAdapter)
}
ImmutableSet::class.java,
PersistentSet::class.java -> {
val elementType = type.actualTypeArguments[0]
val elementAdapter = moshi.adapter<Any>(elementType, annotations)
return ImmutableSetAdapter(elementAdapter)
}
ImmutableMap::class.java,
PersistentMap::class.java -> {
val keyType = type.actualTypeArguments[0]
val valueType = type.actualTypeArguments[1]
val keyAdapter = moshi.adapter<Any>(keyType, annotations)
val valueAdapter = moshi.adapter<Any>(valueType, annotations)
return ImmutableMapAdapter(keyAdapter, valueAdapter)
}
else -> return null
}
}
}

private sealed class ImmutableCollectionAdapter<C : ImmutableCollection<E>, E>(
private val elementAdapter: JsonAdapter<E>
) : JsonAdapter<C>() {

abstract fun buildCollection(body: (MutableCollection<E>) -> Unit): C

override fun fromJson(reader: JsonReader): C? {
reader.beginArray()
val collection = buildCollection { builder ->
while (reader.hasNext()) {
builder += elementAdapter.fromJson(reader) ?: error("Null element at ${reader.path}")
}
}
reader.endArray()
return collection
}

override fun toJson(writer: JsonWriter, value: C?) {
if (value == null) {
writer.nullValue()
} else {
writer.beginArray()
for (element in value) {
elementAdapter.toJson(writer, element)
}
writer.endArray()
}
}
}

private class ImmutableListAdapter<E>(elementAdapter: JsonAdapter<E>) :
ImmutableCollectionAdapter<ImmutableList<E>, E>(elementAdapter) {
override fun buildCollection(body: (MutableCollection<E>) -> Unit) =
persistentListOf<E>().mutate(body)
}

private class ImmutableSetAdapter<E>(elementAdapter: JsonAdapter<E>) :
ImmutableCollectionAdapter<ImmutableSet<E>, E>(elementAdapter) {
override fun buildCollection(body: (MutableCollection<E>) -> Unit) =
persistentSetOf<E>().mutate(body)
}

private class ImmutableMapAdapter<K, V>(
private val keyAdapter: JsonAdapter<K>,
private val valueAdapter: JsonAdapter<V>,
) : JsonAdapter<ImmutableMap<K, V>>() {

override fun fromJson(reader: JsonReader): ImmutableMap<K, V> {
reader.beginObject()
return persistentMapOf<K, V>()
.mutate {
while (reader.hasNext()) {
reader.promoteNameToValue()
val key = keyAdapter.fromJson(reader) ?: error("Null key at ${reader.path}")
val value = valueAdapter.fromJson(reader) ?: error("Null value at ${reader.path}")
val replaced = it.put(key, value)
if (replaced != null) {
throw JsonDataException(
"Duplicate element '$key' with value '$replaced' at ${reader.path}"
)
}
}
}
.also { reader.endObject() }
}

override fun toJson(writer: JsonWriter, value: ImmutableMap<K, V>?) {
if (value == null) {
writer.nullValue()
} else {
writer.beginObject()
for ((k, v) in value) {
writer.promoteValueToName()
keyAdapter.toJson(writer, k)
valueAdapter.toJson(writer, v)
}
writer.endObject()
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
package dev.zacsweers.moshix.adapters.immutable

import com.squareup.moshi.Moshi
import com.squareup.moshi.adapter
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import kotlinx.collections.immutable.ImmutableCollection
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.ImmutableMap
import kotlinx.collections.immutable.ImmutableSet
import kotlinx.collections.immutable.PersistentCollection
import kotlinx.collections.immutable.PersistentList
import kotlinx.collections.immutable.PersistentMap
import kotlinx.collections.immutable.PersistentSet
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.persistentMapOf
import kotlinx.collections.immutable.persistentSetOf
import org.junit.Test

class ImmutableCollectionsJsonAdapterFactoryTest {
private val moshi =
Moshi.Builder()
.add(ImmutableCollectionsJsonAdapterFactory())
.addLast(KotlinJsonAdapterFactory())
.build()

// language=JSON
private val json =
"""
{
"list": [1, 2, 3],
"set": [1, 2, 3],
"collection": [1, 2, 3],
"map": {
"a": 1,
"b": 2,
"c": 3
},
"nested": {
"a": [1, 2, 3],
"b": [1, 2, 3],
"c": [1, 2, 3]
},
"persistentList": [1, 2, 3],
"persistentSet": [1, 2, 3],
"persistentCollection": [1, 2, 3],
"persistentMap": {
"a": 1,
"b": 2,
"c": 3
},
"persistentNested": {
"a": [1, 2, 3],
"b": [1, 2, 3],
"c": [1, 2, 3]
}
}
"""
.trimIndent()

@Test
fun smokeTest() {
val adapter = moshi.adapter<ClassWithImmutables>()
val instance = adapter.fromJson(json)!!
val expectedInstance =
ClassWithImmutables(
list = persistentListOf(1, 2, 3),
set = persistentSetOf(1, 2, 3),
collection = persistentListOf(1, 2, 3),
map = persistentMapOf("a" to 1, "b" to 2, "c" to 3),
nested =
persistentMapOf(
"a" to persistentListOf(1, 2, 3),
"b" to persistentListOf(1, 2, 3),
"c" to persistentListOf(1, 2, 3),
),
persistentList = persistentListOf(1, 2, 3),
persistentSet = persistentSetOf(1, 2, 3),
persistentCollection = persistentListOf(1, 2, 3),
persistentMap = persistentMapOf("a" to 1, "b" to 2, "c" to 3),
persistentNested =
persistentMapOf(
"a" to persistentListOf(1, 2, 3),
"b" to persistentListOf(1, 2, 3),
"c" to persistentListOf(1, 2, 3),
),
)
}

class ClassWithImmutables(
val list: ImmutableList<Int>,
val set: ImmutableSet<Int>,
val collection: ImmutableCollection<Int>,
val map: ImmutableMap<String, Int>,
val nested: ImmutableMap<String, ImmutableList<Int>>,
val persistentList: PersistentList<Int>,
val persistentSet: PersistentSet<Int>,
val persistentCollection: PersistentCollection<Int>,
val persistentMap: PersistentMap<String, Int>,
val persistentNested: PersistentMap<String, PersistentList<Int>>,
)
}
1 change: 1 addition & 0 deletions settings.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ rootProject.name = "moshix-root"

include(
":moshi-adapters",
":moshi-immutable-adapters",
":moshi-ir:moshi-compiler-plugin",
":moshi-ir:moshi-kotlin-tests",
":moshi-ir:moshi-kotlin-tests:extra-moshi-test-module",
Expand Down

0 comments on commit e58044a

Please sign in to comment.