1 /*
2  * Copyright (C) 2024 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 com.android.adservices.shared.datastore
18 
19 import androidx.datastore.core.CorruptionException
20 import androidx.datastore.core.Serializer
21 import com.google.protobuf.ExtensionRegistryLite
22 import com.google.protobuf.InvalidProtocolBufferException
23 import com.google.protobuf.MessageLite
24 import java.io.InputStream
25 import java.io.OutputStream
26 
27 /** Serializer for using [androidx.datastore.core.DataStore] with protos. */
28 class ProtoSerializer<T : MessageLite>(
29     /** The default proto of this type, obtained via {@code T.getDefaultInstance()} */
30     override val defaultValue: T,
31     /**
32      * Sets the extensionRegistryLite to use when deserializing T. An extension registry is used to
33      * parse extension fields in the proto. If no extension registry is necessary, the default
34      * value is {@code ExtensionRegistryLite.getEmptyRegistry()}.
35      */
36     private val extensionRegistryLite: ExtensionRegistryLite =
37         ExtensionRegistryLite.getEmptyRegistry()
38 ) : Serializer<T> {
39 
40     @Suppress("UNCHECKED_CAST")
readFromnull41     override suspend fun readFrom(input: InputStream): T {
42         try {
43             return defaultValue.parserForType.parseFrom(input, extensionRegistryLite) as T
44         } catch (invalidProtocolBufferException: InvalidProtocolBufferException) {
45             throw CorruptionException("Cannot read proto.", invalidProtocolBufferException)
46         }
47     }
48 
writeTonull49     override suspend fun writeTo(t: T, output: OutputStream) {
50         t.writeTo(output)
51     }
52 }
53