1 /* 2 * Copyright 2017 Google 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 * https://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 trebuchet.extras 18 19 import trebuchet.io.BufferProducer 20 import trebuchet.io.DataSlice 21 import java.io.File 22 import java.io.InputStream 23 24 typealias ProgressCallback = ((Long, Long) -> Unit) 25 26 class InputStreamAdapter(val inputStream: InputStream, 27 val totalSize: Long = 0, 28 val progressCallback: ProgressCallback? = null) : BufferProducer { 29 constructor(file: File, progressCallback: ProgressCallback? = null) 30 : this(file.inputStream(), file.length(), progressCallback) 31 32 var totalRead: Long = 0 33 var hitEof = false 34 nextnull35 override fun next(): DataSlice? { 36 if (hitEof) return null 37 val buffer = ByteArray(2 * 1024 * 1024) 38 val read = inputStream.read(buffer) 39 if (read == -1) { 40 hitEof = true 41 return null 42 } 43 totalRead += read 44 progressCallback?.let { it.invoke(totalRead, totalSize) } 45 return DataSlice(buffer, 0, read) 46 } 47 closenull48 override fun close() { 49 hitEof = true 50 inputStream.close() 51 } 52 }