xref: /aosp_15_r20/external/leakcanary2/shark-hprof/src/main/java/shark/RandomAccessSource.kt (revision d9e8da70d8c9df9a41d7848ae506fb3115cae6e6)
1 package shark
2 
3 import okio.Buffer
4 import okio.BufferedSource
5 import okio.Okio
6 import okio.Source
7 import okio.Timeout
8 import java.io.Closeable
9 import java.io.IOException
10 
11 interface RandomAccessSource : Closeable {
12   @Throws(IOException::class)
readnull13   fun read(
14     sink: Buffer,
15     position: Long,
16     byteCount: Long
17   ): Long
18 
19   fun asStreamingSource(): BufferedSource {
20     return Okio.buffer(object : Source {
21       var position = 0L
22 
23       override fun timeout() = Timeout.NONE
24 
25       override fun close() {
26         position = -1
27       }
28 
29       override fun read(
30         sink: Buffer,
31         byteCount: Long
32       ): Long {
33         if (position == -1L) {
34           throw IOException("Source closed")
35         }
36         val bytesRead = read(sink, position, byteCount)
37         if (bytesRead == 0L) {
38           return -1
39         }
40         position += bytesRead
41         return bytesRead
42       }
43     })
44   }
45 }
46