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 java.io.InputStream 20 import java.io.OutputStream 21 22 /** 23 * The serializer determines the on-disk format and API for accessing it. 24 * 25 * The type [T] MUST be immutable. Mutable types will result in broken DataStore functionality. 26 * 27 * TODO(b/151635324): consider changing InputStream to File. 28 */ 29 public interface Serializer<T> { 30 31 /** Value to return if there is no data on disk. */ 32 public val defaultValue: T 33 34 /** 35 * Unmarshal object from stream. 36 * 37 * @param input the InputStream with the data to deserialize 38 * @throws androidx.datastore.core.CorruptionException if the data from [input] is corrupted 39 * and/or unparseable, e.g. [InvalidProtocolBufferException] when the type [T] is a protobuf 40 * message and it is corrupted. Other unrecoverable [IOException] from the file system should 41 * not be thrown as [CorruptionException]. 42 */ readFromnull43 public suspend fun readFrom(input: InputStream): T 44 45 /** 46 * Marshal object to a stream. Closing the provided OutputStream is a no-op. 47 * 48 * @param t the data to write to output 49 * @param output the OutputStream to serialize data to 50 */ 51 public suspend fun writeTo(t: T, output: OutputStream) 52 } 53