1 /* 2 * Copyright 2022 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.datastore 18 19 import androidx.datastore.core.FileStorage 20 import androidx.datastore.core.InterProcessCoordinator 21 import androidx.datastore.core.Storage 22 import androidx.datastore.core.TestingSerializer 23 import java.io.File 24 import java.io.IOException 25 import kotlin.reflect.KClass 26 27 class FileTestIO : 28 TestIO<JavaIOFile, IOException>( <lambda>null29 getTmpDir = { File(System.getProperty("java.io.tmpdir")).toJavaFile() } 30 ) { getStoragenull31 override fun getStorage( 32 serializerConfig: TestingSerializerConfig, 33 coordinatorProducer: () -> InterProcessCoordinator, 34 futureFile: () -> JavaIOFile 35 ): Storage<Byte> { 36 return FileStorage(TestingSerializer(serializerConfig), { coordinatorProducer() }) { 37 futureFile().file 38 } 39 } 40 ioExceptionnull41 override fun ioException(message: String): IOException { 42 return IOException(message) 43 } 44 ioExceptionClassnull45 override fun ioExceptionClass(): KClass<IOException> = IOException::class 46 } 47 48 class JavaIOFile(val file: File) : TestFile<JavaIOFile>() { 49 override val name: String 50 get() = file.name 51 52 override fun path(): String { 53 return file.canonicalFile.absolutePath 54 } 55 56 override fun delete(): Boolean { 57 return file.delete() 58 } 59 60 override fun exists(): Boolean { 61 return file.exists() 62 } 63 64 override fun mkdirs(mustCreate: Boolean) { 65 if (file.exists()) { 66 check(!mustCreate) { "file $file already exists" } 67 } 68 file.mkdirs() 69 check(file.isDirectory) { "Failed to create directories for $file" } 70 } 71 72 override fun isRegularFile(): Boolean { 73 return file.isFile 74 } 75 76 override fun isDirectory(): Boolean { 77 return file.isDirectory 78 } 79 80 override fun protectedResolve(relative: String): JavaIOFile { 81 return file.resolve(relative).toJavaFile() 82 } 83 84 override fun parentFile(): JavaIOFile? { 85 return file.parentFile?.toJavaFile() 86 } 87 88 override fun protectedWrite(body: ByteArray) { 89 file.writeBytes(body) 90 } 91 92 override fun protectedReadBytes(): ByteArray { 93 return file.readBytes() 94 } 95 } 96 toJavaFilenull97fun File.toJavaFile(): JavaIOFile { 98 return JavaIOFile(this) 99 } 100