diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d1a099..4d97620 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,11 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] +## [1.1.0] + +### 2025-12-31 + +- Feature: Add optional `length` and `offset` parameters to `readFile` and `readFileInChunks`. ### 2025-06-26 diff --git a/README.md b/README.md index 4697e29..3136637 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,7 @@ Clone the repository and run `./gradlew dokkaHtml` or `./gradlew dokkaGfm`. Docu 2. I obtained an `OutOfMemoryError` when reading my file. - Use `readFileInChunks` instead of `readFile` if you're trying to read large files that may not fit in memory (e.g. videos). - Make sure you don't use a very large value for `chunkSize` - stick to a few MB at most. + - Alternatively you can use the `offset` + `length` parameters in `readFile`. 3. The chunk received in `readFileInChunks` is not the same as specified in `IONFILEReadInChunksOptions#chunkSize` - The library may change the `chunkSize` internally to better improve the file reading. - The `chunkSize` specifies the total amount of bytes to be read at a time, however the number of bytes returned may vary according to the provided `encoding`. diff --git a/pom.xml b/pom.xml index e7baf48..a3d1f7e 100644 --- a/pom.xml +++ b/pom.xml @@ -6,5 +6,5 @@ 4.0.0 io.ionic.libs ionfilesystem-android - 1.0.0 + 1.1.0 \ No newline at end of file diff --git a/src/main/kotlin/io/ionic/libs/ionfilesystemlib/IONFILEController.kt b/src/main/kotlin/io/ionic/libs/ionfilesystemlib/IONFILEController.kt index 21695bd..0ab5c64 100644 --- a/src/main/kotlin/io/ionic/libs/ionfilesystemlib/IONFILEController.kt +++ b/src/main/kotlin/io/ionic/libs/ionfilesystemlib/IONFILEController.kt @@ -11,6 +11,7 @@ import io.ionic.libs.ionfilesystemlib.helper.common.useUriIfResolvedAsLocal import io.ionic.libs.ionfilesystemlib.helper.common.useUriIfResolvedAsLocalDirectory import io.ionic.libs.ionfilesystemlib.helper.common.useUriIfResolvedAsLocalFile import io.ionic.libs.ionfilesystemlib.helper.common.useUriIfResolvedAsNonDirectory +import io.ionic.libs.ionfilesystemlib.helper.common.validateOffsetAndLength import io.ionic.libs.ionfilesystemlib.model.IONFILECreateOptions import io.ionic.libs.ionfilesystemlib.model.IONFILEDeleteOptions import io.ionic.libs.ionfilesystemlib.model.IONFILEExceptions @@ -97,6 +98,8 @@ class IONFILEController internal constructor( uri: IONFILEUri, options: IONFILEReadOptions ): Result = uriHelper.useUriIfResolvedAsNonDirectory(uri) { resolvedUri -> + runCatching { validateOffsetAndLength(options.offset, options.length) } + .onFailure { return@useUriIfResolvedAsNonDirectory Result.failure(it) } if (resolvedUri is IONFILEUri.Resolved.Local) { localFilesHelper.readFile(resolvedUri.fullPath, options) } else { @@ -138,6 +141,7 @@ class IONFILEController internal constructor( uri: IONFILEUri, options: IONFILEReadInChunksOptions ): Flow = flow { + validateOffsetAndLength(offset = options.offset, length = options.length) val resolveResult = uriHelper.useUriIfResolvedAsNonDirectory(uri) { Result.success(it) } resolveResult.fold( onSuccess = { resolvedUri -> diff --git a/src/main/kotlin/io/ionic/libs/ionfilesystemlib/helper/common/IONFILECommon.kt b/src/main/kotlin/io/ionic/libs/ionfilesystemlib/helper/common/IONFILECommon.kt index 83ffe6e..539f67c 100644 --- a/src/main/kotlin/io/ionic/libs/ionfilesystemlib/helper/common/IONFILECommon.kt +++ b/src/main/kotlin/io/ionic/libs/ionfilesystemlib/helper/common/IONFILECommon.kt @@ -133,6 +133,16 @@ internal inline fun prepareForCopyOrRename( } } +/** + * Validates offset and length parameters for file reading operations. + * @param offset the number of bytes to skip before reading; must be >= 0 + * @param length the maximum number of bytes to read; must be > 0 + */ +internal fun validateOffsetAndLength(offset: Int, length: Int) { + require(offset >= 0) { "offset must be >= 0, but was $offset" } + require(length > 0) { "length must be > 0, but was $length" } +} + /** * Gets the mime type from a file object * @@ -163,4 +173,5 @@ private fun getMimeType(fileObject: File): String { */ private fun checkParentDirectory(file: File, create: Boolean): Boolean = file.parentFile?.let { it.exists() || (create && it.mkdirs()) -} ?: false \ No newline at end of file +} ?: false + diff --git a/src/main/kotlin/io/ionic/libs/ionfilesystemlib/helper/common/IONFILEInputStreamExtensions.kt b/src/main/kotlin/io/ionic/libs/ionfilesystemlib/helper/common/IONFILEInputStreamExtensions.kt index 15c3f7f..53714c2 100644 --- a/src/main/kotlin/io/ionic/libs/ionfilesystemlib/helper/common/IONFILEInputStreamExtensions.kt +++ b/src/main/kotlin/io/ionic/libs/ionfilesystemlib/helper/common/IONFILEInputStreamExtensions.kt @@ -1,6 +1,7 @@ package io.ionic.libs.ionfilesystemlib.helper.common import android.util.Base64 +import io.ionic.libs.ionfilesystemlib.model.IONFILEConstants import io.ionic.libs.ionfilesystemlib.model.IONFILEEncoding import io.ionic.libs.ionfilesystemlib.model.IONFILEReadInChunksOptions import io.ionic.libs.ionfilesystemlib.model.IONFILEReadOptions @@ -15,12 +16,37 @@ import java.io.InputStreamReader * @param options the options for configuring how to read from the stream * @return the full contents of the stream */ -internal fun InputStream.readFull(options: IONFILEReadOptions): String = - if (options.encoding is IONFILEEncoding.WithCharset) { - InputStreamReader(this, options.encoding.charset).use { it.readText() } +internal fun InputStream.readFull(options: IONFILEReadOptions): String { + applyOffset(options.offset) + if (options.length in 1.. 0 && totalBytesRead < options.length) + return readFile } else { - Base64.encodeToString(this.readBytes(), Base64.NO_WRAP) + // use default platform methods - can be slightly more efficient + return if (options.encoding is IONFILEEncoding.WithCharset) { + InputStreamReader(this, options.encoding.charset).use { + it.readText() + } + } else { + Base64.encodeToString(this.readBytes(), Base64.NO_WRAP) + } } +} /** * Reads the contents of an [InputStream] in chunks. @@ -41,20 +67,18 @@ internal suspend fun InputStream.readByChunks( onChunkRead: suspend (String) -> Unit, ) { val chunkSize = calculateChunkSizeToUse(options, bufferSize) - var bytesRead: Int + applyOffset(options.offset) + var chunkBytesRead: Int + var totalBytesRead = 0 do { - val byteArray = ByteArray(chunkSize) - bytesRead = readChunk(byteArray, bufferSize) - if (bytesRead > 0) { - val byteArrayToConvert = byteArray.take(bytesRead).toByteArray() - val readChunk = if (options.encoding is IONFILEEncoding.WithCharset) { - byteArrayToConvert.toString(options.encoding.charset) - } else { - Base64.encodeToString(byteArrayToConvert, Base64.NO_WRAP) - } - onChunkRead(readChunk) + val remainingBytesToRead = options.length - totalBytesRead + val byteArray = ByteArray(minOf(chunkSize, remainingBytesToRead)) + chunkBytesRead = readChunk(byteArray, bufferSize) + processReadChunk(byteArray, chunkBytesRead, options.encoding)?.let { + totalBytesRead += chunkBytesRead + onChunkRead(it) } - } while (bytesRead > 0) + } while (chunkBytesRead > 0 && totalBytesRead < options.length) } /** @@ -78,6 +102,29 @@ private fun InputStream.readChunk(byteArray: ByteArray, bufferSize: Int): Int { return totalBytesRead } +/** + * Converts a chunk of bytes to a String based on encoding and invokes a handler. + * + * @param byteArray the byte buffer containing data + * @param bytesRead the number of valid bytes in the buffer + * @param encoding the encoding to use for conversion + * @return the read chunk if anything was read, or null otherwise + */ +private fun processReadChunk( + byteArray: ByteArray, + bytesRead: Int, + encoding: IONFILEEncoding, +): String? { + if (bytesRead <= 0) return null + val byteArrayToConvert = byteArray.copyOf(bytesRead) + val readChunk = if (encoding is IONFILEEncoding.WithCharset) { + byteArrayToConvert.toString(encoding.charset) + } else { + Base64.encodeToString(byteArrayToConvert, Base64.NO_WRAP) + } + return readChunk +} + /** * Calculates chunk size based on specified parameters. * The chunk size here refers to a max amount of file bytes to place to read. @@ -90,14 +137,22 @@ private fun InputStream.readChunk(byteArray: ByteArray, bufferSize: Int): Int { private fun InputStream.calculateChunkSizeToUse( options: IONFILEReadInChunksOptions, bufferSize: Int, -): Int = minOf(options.chunkSize, available()) +): Int = minOf(options.chunkSize, minOf(available() - options.offset, options.length)) .coerceAtLeast(bufferSize) .let { - if (options.encoding == IONFILEEncoding.Base64) { - // make chunk size the nearest highest multiple of 3, to not add padding to the end - // this is so that multiple chunks can be concatenated and decoded correctly - it - (it % 3) + 3 - } else { - it - } - } \ No newline at end of file + options.encoding.convertChunkSize(it) + } + +private fun IONFILEEncoding.convertChunkSize(chunkSize: Int) = if (this == IONFILEEncoding.Base64) { + // make chunk size the nearest highest multiple of 3, to not add padding to the end + // this is so that multiple chunks can be concatenated and decoded correctly + chunkSize - (chunkSize % 3) + 3 +} else { + chunkSize +} + +private fun InputStream.applyOffset(offset: Int) { + if (offset > 0) { + skipNBytes(offset.toLong()) + } +} \ No newline at end of file diff --git a/src/main/kotlin/io/ionic/libs/ionfilesystemlib/model/IONFILEConstants.kt b/src/main/kotlin/io/ionic/libs/ionfilesystemlib/model/IONFILEConstants.kt new file mode 100644 index 0000000..9cc459b --- /dev/null +++ b/src/main/kotlin/io/ionic/libs/ionfilesystemlib/model/IONFILEConstants.kt @@ -0,0 +1,5 @@ +package io.ionic.libs.ionfilesystemlib.model + +object IONFILEConstants { + const val LENGTH_READ_TIL_EOF = Int.MAX_VALUE +} \ No newline at end of file diff --git a/src/main/kotlin/io/ionic/libs/ionfilesystemlib/model/IONFILEReadInChunksOptions.kt b/src/main/kotlin/io/ionic/libs/ionfilesystemlib/model/IONFILEReadInChunksOptions.kt index ce8198d..3df1930 100644 --- a/src/main/kotlin/io/ionic/libs/ionfilesystemlib/model/IONFILEReadInChunksOptions.kt +++ b/src/main/kotlin/io/ionic/libs/ionfilesystemlib/model/IONFILEReadInChunksOptions.kt @@ -14,8 +14,15 @@ package io.ionic.libs.ionfilesystemlib.model * This means multiple chunks can be concatenated and decoded together without losing data. * There is no check on a maximum value for chunkSize, meaning that if you provide a very large value, * an OutOfMemoryError may be thrown. Avoid using chunkSize larger than a few MB. + * @param offset An optional number of bytes to skip from the start of the file. + * Default is 0 (read from beginning of file). + * @param length The maximum number of bytes to read after the [offset]. + * If fewer bytes are available before the end of the file, only the available bytes are returned. + * By default, will read the entirety of contents after [offset]. */ data class IONFILEReadInChunksOptions( val encoding: IONFILEEncoding, val chunkSize: Int, + val offset: Int = 0, + val length: Int = IONFILEConstants.LENGTH_READ_TIL_EOF ) \ No newline at end of file diff --git a/src/main/kotlin/io/ionic/libs/ionfilesystemlib/model/IONFILEReadOptions.kt b/src/main/kotlin/io/ionic/libs/ionfilesystemlib/model/IONFILEReadOptions.kt index 2930400..3ec8ceb 100644 --- a/src/main/kotlin/io/ionic/libs/ionfilesystemlib/model/IONFILEReadOptions.kt +++ b/src/main/kotlin/io/ionic/libs/ionfilesystemlib/model/IONFILEReadOptions.kt @@ -4,7 +4,14 @@ package io.ionic.libs.ionfilesystemlib.model * Parameters for reading a file all at once * * @param encoding how the file data to return should be encoded; see [IONFILEEncoding] + * @param offset An optional number of bytes to skip from the start of the file. + * Default is 0 (read from beginning of file). + * @param length An optional maximum number of bytes to read after the [offset]. + * If fewer bytes are available before the end of the file, only the available bytes are returned. + * By default, will read the entirety of contents after [offset]. */ data class IONFILEReadOptions( - val encoding: IONFILEEncoding + val encoding: IONFILEEncoding, + val offset: Int = 0, + val length: Int = IONFILEConstants.LENGTH_READ_TIL_EOF ) \ No newline at end of file diff --git a/src/test/java/io/ionic/libs/ionfilesystemlib/helper/IONFILEControllerTests.kt b/src/test/java/io/ionic/libs/ionfilesystemlib/helper/IONFILEControllerTests.kt index b0d0ab4..4f17ca8 100644 --- a/src/test/java/io/ionic/libs/ionfilesystemlib/helper/IONFILEControllerTests.kt +++ b/src/test/java/io/ionic/libs/ionfilesystemlib/helper/IONFILEControllerTests.kt @@ -33,6 +33,7 @@ import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import java.io.File +import java.lang.IllegalArgumentException import java.util.Base64 import kotlin.math.ceil @@ -550,4 +551,45 @@ class IONFILEControllerTests { assertTrue(result.exceptionOrNull() is IONFILEExceptions.NotSupportedForContentScheme) } // endregion uri resolve errors + + // region read file input errors + @Test + fun `given negative offset, when calling readFile, IllegalArgumentException is returned`() = runTest { + val uriLocalFile = IONFILEUri.Unresolved( + parentFolder = IONFILEFolderType.INTERNAL_FILES, + "fileToCreate.txt" + ) + + val result = sut.readFile( + uriLocalFile, + IONFILEReadOptions( + encoding = IONFILEEncoding.Base64, + offset = -1 + ) + ) + + assertTrue(result.isFailure) + assertTrue(result.exceptionOrNull() is IllegalArgumentException) + } + + @Test + fun `given length=0, when calling readFile, IllegalArgumentException is returned`() = runTest { + val uriLocalFile = IONFILEUri.Unresolved( + parentFolder = IONFILEFolderType.INTERNAL_FILES, + "fileToCreate.txt" + ) + + sut.readFileInChunks( + uriLocalFile, + IONFILEReadInChunksOptions( + encoding = IONFILEEncoding.Base64, + chunkSize = 64, + length = 0 + ) + ).test { + val error = awaitError() + assertTrue(error is IllegalArgumentException) + } + } + // region read file input errors } \ No newline at end of file diff --git a/src/test/java/io/ionic/libs/ionfilesystemlib/helper/IONFILELocalFilesHelperTest.kt b/src/test/java/io/ionic/libs/ionfilesystemlib/helper/IONFILELocalFilesHelperTest.kt index d3bddc2..84d6a90 100644 --- a/src/test/java/io/ionic/libs/ionfilesystemlib/helper/IONFILELocalFilesHelperTest.kt +++ b/src/test/java/io/ionic/libs/ionfilesystemlib/helper/IONFILELocalFilesHelperTest.kt @@ -576,6 +576,155 @@ class IONFILELocalFilesHelperTest : IONFILEBaseJUnitTest() { } // endregion read by chunks tests + // region read with offset/length tests + @Test + fun `given offset and length, when readFileInChunks is called, the specific bytes from file are returned`() = runTest { + val file = fileInRootDir + val path = file.absolutePath + val content = "Hello, World!" + sut.saveFile( + path, + IONFILESaveOptions( + content, + IONFILEEncoding.WithCharset(Charsets.UTF_8), + IONFILESaveMode.WRITE, + createFileRecursive = false + ) + ) + + var i = 0 + sut.readFileInChunks( + fullPath = path, + options = IONFILEReadInChunksOptions( + encoding = IONFILEEncoding.WithCharset(Charsets.UTF_8), + chunkSize = 2, + offset = 7, + length = 5 + ), + bufferSize = 2 + ).test { + while (i <= 3) { + when (i) { + 0 -> assertEquals("Wo", awaitItem()) + 1 -> assertEquals("rl", awaitItem()) + 2 -> assertEquals("d", awaitItem()) + else -> awaitComplete() + } + i++ + } + } + } + + @Test + fun `given offset and length and base64 encoding, when readFile is called, the specific base64 portion of file is read`() = runTest { + val file = fileInRootDir + val path = file.absolutePath + val content = "Hello, World!" + sut.saveFile( + path, + IONFILESaveOptions( + content, + IONFILEEncoding.WithCharset(Charsets.UTF_8), + IONFILESaveMode.WRITE, + createFileRecursive = false + ) + ) + + val result = sut.readFile( + fullPath = path, + options = IONFILEReadOptions( + encoding = IONFILEEncoding.Base64, + offset = 0, + length = 5 + ) + ) + + // "Hello" in Base64 is "SGVsbG8=" + assertEquals("SGVsbG8=", result.getOrNull()) + } + + @Test + fun `given length is after EOF, when readFile is called, the file portion contents is returned correctly`() = runTest { + val file = fileInRootDir + val path = file.absolutePath + val content = "12345" + sut.saveFile( + path, + IONFILESaveOptions( + content, + IONFILEEncoding.WithCharset(Charsets.UTF_8), + IONFILESaveMode.WRITE, + createFileRecursive = false + ) + ) + + val result = sut.readFile( + fullPath = path, + options = IONFILEReadOptions( + encoding = IONFILEEncoding.WithCharset(Charsets.UTF_8), + offset = 3, + length = 10 // Try to read past EOF + ) + ) + + assertEquals("45", result.getOrNull()) + } + + @Test + fun `given offset is after EOF, when readFile is called, empty string is returned`() = runTest { + val file = fileInRootDir + val path = file.absolutePath + val content = "12345" + sut.saveFile( + path, + IONFILESaveOptions( + content, + IONFILEEncoding.WithCharset(Charsets.UTF_8), + IONFILESaveMode.WRITE, + createFileRecursive = false + ) + ) + + val result = sut.readFile( + fullPath = path, + options = IONFILEReadOptions( + encoding = IONFILEEncoding.WithCharset(Charsets.UTF_8), + offset = content.length + ) + ) + + assertEquals("", result.getOrNull()) + } + + @Test + fun `given offset is after EOF, when readFileInChunks is called, no items are emitted`() = runTest { + val file = fileInRootDir + val path = file.absolutePath + val content = "12345" + sut.saveFile( + path, + IONFILESaveOptions( + content, + IONFILEEncoding.WithCharset(Charsets.UTF_8), + IONFILESaveMode.WRITE, + createFileRecursive = false + ) + ) + + sut.readFileInChunks( + fullPath = path, + options = IONFILEReadInChunksOptions( + encoding = IONFILEEncoding.WithCharset(Charsets.UTF_8), + offset = content.length + 100, + chunkSize = 10 + ) + ).test { + // no emissions because returned file will be empty + awaitComplete() + } + } + // endregion read with offset/length tests + // region fileMetadata tests @Test fun `given empty file exists, when getting file metadata, the correct information is returned`() =