1/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package androidx.room.solver.types
18
19import androidx.room.ext.L
20import androidx.room.solver.CodeGenScope
21import com.google.auto.common.MoreTypes
22import javax.annotation.processing.ProcessingEnvironment
23import javax.lang.model.type.TypeMirror
24
25/**
26 * Adapters for all boxed primitives that has direct cursor mappings.
27 */
28open class BoxedPrimitiveColumnTypeAdapter(
29        boxed: TypeMirror,
30        val primitiveAdapter: PrimitiveColumnTypeAdapter
31) : ColumnTypeAdapter(boxed, primitiveAdapter.typeAffinity) {
32    companion object {
33        fun createBoxedPrimitiveAdapters(
34                processingEnvironment: ProcessingEnvironment,
35                primitiveAdapters: List<PrimitiveColumnTypeAdapter>
36        ): List<ColumnTypeAdapter> {
37
38            return primitiveAdapters.map {
39                BoxedPrimitiveColumnTypeAdapter(
40                        processingEnvironment.typeUtils
41                                .boxedClass(MoreTypes.asPrimitiveType(it.out)).asType(),
42                        it
43                )
44            }
45        }
46    }
47
48    override fun bindToStmt(stmtName: String, indexVarName: String, valueVarName: String,
49                            scope: CodeGenScope) {
50        scope.builder().apply {
51            beginControlFlow("if ($L == null)", valueVarName).apply {
52                addStatement("$L.bindNull($L)", stmtName, indexVarName)
53            }
54            nextControlFlow("else").apply {
55                primitiveAdapter.bindToStmt(stmtName, indexVarName, valueVarName, scope)
56            }
57            endControlFlow()
58        }
59    }
60
61    override fun readFromCursor(outVarName: String, cursorVarName: String, indexVarName: String,
62                                scope: CodeGenScope) {
63        scope.builder().apply {
64            beginControlFlow("if ($L.isNull($L))", cursorVarName, indexVarName).apply {
65                addStatement("$L = null", outVarName)
66            }
67            nextControlFlow("else").apply {
68                primitiveAdapter.readFromCursor(outVarName, cursorVarName, indexVarName, scope)
69            }
70            endControlFlow()
71        }
72    }
73}
74