1 /* 2 * Copyright 2020 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.core 18 19 import androidx.datastore.TestingSerializerConfig 20 import java.io.IOException 21 import java.io.InputStream 22 import java.io.OutputStream 23 24 class TestingSerializer( 25 private val config: TestingSerializerConfig = TestingSerializerConfig(), 26 ) : Serializer<Byte> { readFromnull27 override suspend fun readFrom(input: InputStream): Byte { 28 // hack to make failReadWithCorruptionException during runtime 29 var failReadWithCorruptionException = config.failReadWithCorruptionException 30 if (!config.listOfFailReadWithCorruptionException.isEmpty()) { 31 failReadWithCorruptionException = config.listOfFailReadWithCorruptionException.get(0) 32 config.listOfFailReadWithCorruptionException = 33 config.listOfFailReadWithCorruptionException.drop(1) 34 } 35 if (failReadWithCorruptionException) { 36 throw CorruptionException("CorruptionException", IOException()) 37 } 38 39 if (config.failingRead) { 40 throw IOException("I was asked to fail on reads") 41 } 42 43 val read = input.read() 44 if (read == -1) { 45 return 0 46 } 47 return read.toByte() 48 } 49 writeTonull50 override suspend fun writeTo(t: Byte, output: OutputStream) { 51 config.writeCount++ 52 if (config.failingWrite) { 53 throw IOException("I was asked to fail on writes") 54 } 55 output.write(t.toInt()) 56 } 57 58 override val defaultValue: Byte 59 get() = config.defaultValue 60 } 61