1 package kotlinx.serialization.encoding
2 
3 import kotlinx.serialization.ExperimentalSerializationApi
4 
5 /**
6  * This interface indicates that decoder supports consuming large strings by chunks via consumeChunk method.
7  * Currently, only streaming json decoder implements this interface.
8  * Please note that this interface is only applicable to streaming decoders. That means that it is not possible to use
9  * some JsonTreeDecoder features like polymorphism with this interface.
10  */
11 @ExperimentalSerializationApi
12 public interface ChunkedDecoder {
13     /**
14      * Method allows decoding a string value by fixed-size chunks.
15      * Usable for handling very large strings that may not fit in memory.
16      * Chunk size is guaranteed to not exceed 16384 chars (but it may be smaller than that).
17      * Feeds string chunks to the provided consumer.
18      *
19      * @param consumeChunk - lambda function to handle string chunks
20      *
21      * Example usage:
22      * ```
23      * @Serializable(with = LargeStringSerializer::class)
24      * data class LargeStringData(val largeString: String)
25      *
26      * @Serializable
27      * data class ClassWithLargeStringDataField(val largeStringField: LargeStringData)
28      *
29      * object LargeStringSerializer : KSerializer<LargeStringData> {
30      *     override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("LargeStringContent", PrimitiveKind.STRING)
31      *
32      *     override fun deserialize(decoder: Decoder): LargeStringData {
33      *         require(decoder is ChunkedDecoder) { "Only chunked decoder supported" }
34      *
35      *         val tmpFile = createTempFile()
36      *         val writer = FileWriter(tmpFile.toFile()).use {
37      *             decoder.decodeStringChunked { chunk ->
38      *                 writer.append(chunk)
39      *             }
40      *         }
41      *         return LargeStringData("file://${tmpFile.absolutePathString()}")
42      *     }
43      * }
44      * ```
45      *
46      * In this sample, we need to be able to handle a huge string coming from json. Instead of storing it in memory,
47      * we offload it into a file and return the file name instead
48      */
49     @ExperimentalSerializationApi
decodeStringChunkednull50     public fun decodeStringChunked(consumeChunk: (chunk: String) -> Unit)
51 }