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 
17 package androidx.room.solver.query.result
18 
19 import androidx.room.ext.L
20 import androidx.room.ext.T
21 import androidx.room.ext.typeName
22 import androidx.room.solver.CodeGenScope
23 import com.squareup.javapoet.ArrayTypeName
24 import com.squareup.javapoet.TypeName
25 
26 class ArrayQueryResultAdapter(rowAdapter: RowAdapter) : QueryResultAdapter(rowAdapter) {
27     val type = rowAdapter.out
convertnull28     override fun convert(outVarName: String, cursorVarName: String, scope: CodeGenScope) {
29         scope.builder().apply {
30             rowAdapter?.onCursorReady(cursorVarName, scope)
31 
32             val arrayType = ArrayTypeName.of(type.typeName())
33             addStatement("final $T $L = new $T[$L.getCount()]",
34                     arrayType, outVarName, type.typeName(), cursorVarName)
35             val tmpVarName = scope.getTmpVar("_item")
36             val indexVar = scope.getTmpVar("_index")
37             addStatement("$T $L = 0", TypeName.INT, indexVar)
38             beginControlFlow("while($L.moveToNext())", cursorVarName).apply {
39                 addStatement("final $T $L", type.typeName(), tmpVarName)
40                 rowAdapter?.convert(tmpVarName, cursorVarName, scope)
41                 addStatement("$L[$L] = $L", outVarName, indexVar, tmpVarName)
42                 addStatement("$L ++", indexVar)
43             }
44             endControlFlow()
45             rowAdapter?.onCursorFinished()?.invoke(scope)
46         }
47     }
48 }
49