Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement kotlinx immutable adapters #586

Merged
merged 3 commits into from
May 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ spotless = { id = "com.diffplug.spotless", version = "6.25.0" }
[libraries]
agp = { module = "com.android.tools.build:gradle", version.ref = "agp" }

assertj = "org.assertj:assertj-core:3.25.3"

autoCommon = { module = "com.google.auto:auto-common", version = "1.2.2" }

autoService = { module = "com.google.auto.service:auto-service-annotations", version.ref = "autoService" }
Expand All @@ -58,6 +60,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
6 changes: 1 addition & 5 deletions moshi-adapters/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,13 @@
* 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") }
}
tasks.compileTestKotlin { compilerOptions { optIn.add("kotlin.ExperimentalStdlibApi") } }

dependencies {
implementation(libs.moshi)
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`
5 changes: 5 additions & 0 deletions moshi-immutable-adapters/api/moshi-immutable-adapters.api
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
public final class dev/zacsweers/moshix/adapters/immutable/ImmutableCollectionsJsonAdapterFactory : com/squareup/moshi/JsonAdapter$Factory {
public fun <init> ()V
public fun create (Ljava/lang/reflect/Type;Ljava/util/Set;Lcom/squareup/moshi/Moshi;)Lcom/squareup/moshi/JsonAdapter;
}

32 changes: 32 additions & 0 deletions moshi-immutable-adapters/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* 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.
*/

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

tasks.compileTestKotlin { compilerOptions { optIn.add("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>>,
)
}
8 changes: 2 additions & 6 deletions moshi-metadata-reflect/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,19 @@
* limitations under the License.
*/

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

plugins {
kotlin("jvm")
id("com.google.devtools.ksp")
id("com.vanniktech.maven.publish")
}

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

dependencies {
implementation(libs.kotlin.metadata)
implementation(libs.moshi)
kspTest(libs.moshi.codegen)
testImplementation("org.assertj:assertj-core:3.25.3")
testImplementation(libs.assertj)
testImplementation(libs.junit)
testImplementation(libs.truth)
}
Loading