1 /* 2 * Copyright (C) 2021 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 package okio 17 18 import java.io.RandomAccessFile 19 20 internal class JvmFileHandle( 21 readWrite: Boolean, 22 private val randomAccessFile: RandomAccessFile, 23 ) : FileHandle(readWrite) { 24 25 @Synchronized protectedResizenull26 override fun protectedResize(size: Long) { 27 val currentSize = size() 28 val delta = size - currentSize 29 if (delta > 0) { 30 protectedWrite(currentSize, ByteArray(delta.toInt()), 0, delta.toInt()) 31 } else { 32 randomAccessFile.setLength(size) 33 } 34 } 35 36 @Synchronized protectedSizenull37 override fun protectedSize(): Long { 38 return randomAccessFile.length() 39 } 40 41 @Synchronized protectedReadnull42 override fun protectedRead( 43 fileOffset: Long, 44 array: ByteArray, 45 arrayOffset: Int, 46 byteCount: Int, 47 ): Int { 48 randomAccessFile.seek(fileOffset) 49 var bytesRead = 0 50 while (bytesRead < byteCount) { 51 val readResult = randomAccessFile.read(array, arrayOffset, byteCount - bytesRead) 52 if (readResult == -1) { 53 if (bytesRead == 0) return -1 54 break 55 } 56 bytesRead += readResult 57 } 58 return bytesRead 59 } 60 61 @Synchronized protectedWritenull62 override fun protectedWrite( 63 fileOffset: Long, 64 array: ByteArray, 65 arrayOffset: Int, 66 byteCount: Int, 67 ) { 68 randomAccessFile.seek(fileOffset) 69 randomAccessFile.write(array, arrayOffset, byteCount) 70 } 71 72 @Synchronized protectedFlushnull73 override fun protectedFlush() { 74 randomAccessFile.fd.sync() 75 } 76 77 @Synchronized protectedClosenull78 override fun protectedClose() { 79 randomAccessFile.close() 80 } 81 } 82