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.CorruptionException 20 import androidx.datastore.core.okio.OkioSerializer 21 import okio.BufferedSink 22 import okio.BufferedSource 23 import okio.EOFException 24 import okio.IOException 25 import okio.use 26 27 class TestingOkioSerializer(private val config: TestingSerializerConfig) : OkioSerializer<Byte> { 28 readFromnull29 override suspend fun readFrom(source: BufferedSource): Byte { 30 if (config.failReadWithCorruptionException) { 31 throw CorruptionException( 32 "CorruptionException", 33 IOException("I was asked to fail with corruption on reads") 34 ) 35 } 36 37 if (config.failingRead) { 38 throw IOException("I was asked to fail on reads") 39 } 40 41 val read = 42 try { 43 source.use { it.readInt() } 44 } catch (eof: EOFException) { 45 return 0 46 } 47 return read.toByte() 48 } 49 writeTonull50 override suspend fun writeTo(t: Byte, sink: BufferedSink) { 51 config.writeCount++ 52 if (config.failingWrite) { 53 throw IOException("I was asked to fail on writes") 54 } 55 sink.use { it.writeInt(t.toInt()) } 56 } 57 58 override val defaultValue: Byte 59 get() = config.defaultValue 60 } 61