xref: /aosp_15_r20/external/okio/okio/src/jvmMain/kotlin/okio/InflaterSource.kt (revision f9742813c14b702d71392179818a9e591da8620c)
1 /*
2  * Copyright (C) 2014 Square, Inc.
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 @file:JvmName("-InflaterSourceExtensions")
18 @file:Suppress("NOTHING_TO_INLINE") // Aliases to public API.
19 
20 package okio
21 
22 import java.io.IOException
23 import java.util.zip.DataFormatException
24 import java.util.zip.Inflater
25 
26 /**
27  * A source that uses [DEFLATE](http://tools.ietf.org/html/rfc1951) to decompress data read from
28  * another source.
29  */
30 class InflaterSource
31 /**
32  * This internal constructor shares a buffer with its trusted caller. In general we can't share a
33  * `BufferedSource` because the inflater holds input bytes until they are inflated.
34  */
35 internal constructor(private val source: BufferedSource, private val inflater: Inflater) : Source {
36 
37   /**
38    * When we call Inflater.setInput(), the inflater keeps our byte array until it needs input again.
39    * This tracks how many bytes the inflater is currently holding on to.
40    */
41   private var bufferBytesHeldByInflater = 0
42   private var closed = false
43 
44   constructor(source: Source, inflater: Inflater) : this(source.buffer(), inflater)
45 
46   @Throws(IOException::class)
readnull47   override fun read(sink: Buffer, byteCount: Long): Long {
48     while (true) {
49       val bytesInflated = readOrInflate(sink, byteCount)
50       if (bytesInflated > 0) return bytesInflated
51       if (inflater.finished() || inflater.needsDictionary()) return -1L
52       if (source.exhausted()) throw EOFException("source exhausted prematurely")
53     }
54   }
55 
56   /**
57    * Consume deflated bytes from the underlying source, and write any inflated bytes to [sink].
58    * Returns the number of inflated bytes written to [sink]. This may return 0L, though it will
59    * always consume 1 or more bytes from the underlying source if it is not exhausted.
60    *
61    * Use this instead of [read] when it is useful to consume the deflated stream even when doing so
62    * doesn't yield inflated bytes.
63    */
64   @Throws(IOException::class)
readOrInflatenull65   fun readOrInflate(sink: Buffer, byteCount: Long): Long {
66     require(byteCount >= 0L) { "byteCount < 0: $byteCount" }
67     check(!closed) { "closed" }
68     if (byteCount == 0L) return 0L
69 
70     try {
71       // Prepare the destination that we'll write into.
72       val tail = sink.writableSegment(1)
73       val toRead = minOf(byteCount, Segment.SIZE - tail.limit).toInt()
74 
75       // Prepare the source that we'll read from.
76       refill()
77 
78       // Decompress the inflater's compressed data into the sink.
79       val bytesInflated = inflater.inflate(tail.data, tail.limit, toRead)
80 
81       // Release consumed bytes from the source.
82       releaseBytesAfterInflate()
83 
84       // Track produced bytes in the destination.
85       if (bytesInflated > 0) {
86         tail.limit += bytesInflated
87         sink.size += bytesInflated
88         return bytesInflated.toLong()
89       }
90 
91       // We allocated a tail segment, but didn't end up needing it. Recycle!
92       if (tail.pos == tail.limit) {
93         sink.head = tail.pop()
94         SegmentPool.recycle(tail)
95       }
96 
97       return 0L
98     } catch (e: DataFormatException) {
99       throw IOException(e)
100     }
101   }
102 
103   /**
104    * Refills the inflater with compressed data if it needs input. (And only if it needs input).
105    * Returns true if the inflater required input but the source was exhausted.
106    */
107   @Throws(IOException::class)
refillnull108   fun refill(): Boolean {
109     if (!inflater.needsInput()) return false
110 
111     // If there are no further bytes in the source, we cannot refill.
112     if (source.exhausted()) return true
113 
114     // Assign buffer bytes to the inflater.
115     val head = source.buffer.head!!
116     bufferBytesHeldByInflater = head.limit - head.pos
117     inflater.setInput(head.data, head.pos, bufferBytesHeldByInflater)
118     return false
119   }
120 
121   /** When the inflater has processed compressed data, remove it from the buffer.  */
releaseBytesAfterInflatenull122   private fun releaseBytesAfterInflate() {
123     if (bufferBytesHeldByInflater == 0) return
124     val toRelease = bufferBytesHeldByInflater - inflater.remaining
125     bufferBytesHeldByInflater -= toRelease
126     source.skip(toRelease.toLong())
127   }
128 
timeoutnull129   override fun timeout(): Timeout = source.timeout()
130 
131   @Throws(IOException::class)
132   override fun close() {
133     if (closed) return
134     inflater.end()
135     closed = true
136     source.close()
137   }
138 }
139 
140 /**
141  * Returns an [InflaterSource] that DEFLATE-decompresses this [Source] while reading.
142  *
143  * @see InflaterSource
144  */
inflatenull145 inline fun Source.inflate(inflater: Inflater = Inflater()): InflaterSource =
146   InflaterSource(this, inflater)
147