From 527fd651952cf12280a9cc32a392fcc5b34cc8f2 Mon Sep 17 00:00:00 2001 From: HarelM Date: Wed, 31 Dec 2025 23:40:08 +0200 Subject: [PATCH 1/7] feat: Add readRange method --- .../helper/IONFILELocalFilesHelper.kt | 51 +++++++++ .../helper/IONFILELocalFilesHelperTest.kt | 102 ++++++++++++++++++ 2 files changed, 153 insertions(+) diff --git a/src/main/kotlin/io/ionic/libs/ionfilesystemlib/helper/IONFILELocalFilesHelper.kt b/src/main/kotlin/io/ionic/libs/ionfilesystemlib/helper/IONFILELocalFilesHelper.kt index 19968c0..e056fa5 100644 --- a/src/main/kotlin/io/ionic/libs/ionfilesystemlib/helper/IONFILELocalFilesHelper.kt +++ b/src/main/kotlin/io/ionic/libs/ionfilesystemlib/helper/IONFILELocalFilesHelper.kt @@ -53,6 +53,57 @@ internal class IONFILELocalFilesHelper { } } + /** + * Reads a specific range of bytes from a file + * + * @param fullPath full path of the file to read from + * @param offset the starting position in the file + * @param length the number of bytes to read + * @param options options for reading the file (encoding) + * @return success with file contents string if it was read successfully, error otherwise + */ + suspend fun readRange( + fullPath: String, + offset: Long, + length: Int, + options: IONFILEReadOptions + ): Result = withContext(Dispatchers.IO) { + runCatching { + val file = File(fullPath) + if (!file.exists()) { + throw IONFILEExceptions.DoesNotExist(fullPath) + } + if (offset < 0) { + throw IllegalArgumentException("Offset cannot be negative") + } + if (length < 0) { + throw IllegalArgumentException("Length cannot be negative") + } + + java.io.RandomAccessFile(file, "r").use { raf -> + raf.seek(offset) + val buffer = ByteArray(length) + val bytesRead = raf.read(buffer) + + if (bytesRead == -1) { + return@use "" + } + + val actualBuffer = if (bytesRead < length) { + buffer.copyOf(bytesRead) + } else { + buffer + } + + if (options.encoding is IONFILEEncoding.WithCharset) { + String(actualBuffer, options.encoding.charset) + } else { + Base64.encodeToString(actualBuffer, Base64.NO_WRAP) + } + } + } + } + /** * Reads the contents of a file in chunks * 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..634724c 100644 --- a/src/test/java/io/ionic/libs/ionfilesystemlib/helper/IONFILELocalFilesHelperTest.kt +++ b/src/test/java/io/ionic/libs/ionfilesystemlib/helper/IONFILELocalFilesHelperTest.kt @@ -830,4 +830,106 @@ class IONFILELocalFilesHelperTest : IONFILEBaseJUnitTest() { assertTrue(result.exceptionOrNull() is IONFILEExceptions.CopyRenameFailed.MixingFilesAndDirectories) } // endregion renameFile tests + // region readRange tests + @Test + fun `readRange should read specific bytes from file`() = 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.readRange( + fullPath = path, + offset = 7, + length = 5, + options = IONFILEReadOptions(encoding = IONFILEEncoding.WithCharset(Charsets.UTF_8)) + ) + + assertEquals("World", result.getOrNull()) + } + + @Test + fun `readRange should handle Base64 encoding`() = 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.readRange( + fullPath = path, + offset = 0, + length = 5, + options = IONFILEReadOptions(encoding = IONFILEEncoding.Base64) + ) + + // "Hello" in Base64 is "SGVsbG8=" + assertEquals("SGVsbG8=", result.getOrNull()) + } + + @Test + fun `readRange should handle EOF gracefully`() = 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.readRange( + fullPath = path, + offset = 3, + length = 10, // Try to read past EOF + options = IONFILEReadOptions(encoding = IONFILEEncoding.WithCharset(Charsets.UTF_8)) + ) + + assertEquals("45", result.getOrNull()) + } + + @Test + fun `readRange should return empty string if offset is at EOF`() = 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.readRange( + fullPath = path, + offset = 5, + length = 10, + options = IONFILEReadOptions(encoding = IONFILEEncoding.WithCharset(Charsets.UTF_8)) + ) + + assertEquals("", result.getOrNull()) + } + // endregion readRange tests } \ No newline at end of file From 13033a44f86ce459f7237d006d1a0abd4b16c407 Mon Sep 17 00:00:00 2001 From: HarelM Date: Wed, 31 Dec 2025 23:47:06 +0200 Subject: [PATCH 2/7] Update changelog --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d1a099..beef476 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### 2025-12-31 + +- Add `readRange` method. + ### 2025-06-26 - Migrate publishing from OSSRH to Central Portal. From 0d41a85705e5c49498968b3515b31813fddf63f4 Mon Sep 17 00:00:00 2001 From: OS-pedrogustavobilro Date: Wed, 14 Jan 2026 17:50:41 +0000 Subject: [PATCH 3/7] refactor: Use offset and length in existing file methods An alternative to creating a readRange method. This way it allows us to better use the functionality in consumers of the native library (e.g. capacitor plugin) --- .../helper/IONFILELocalFilesHelper.kt | 51 ---- .../helper/common/IONFILECommon.kt | 1 + .../common/IONFILEInputStreamExtensions.kt | 104 ++++++-- .../model/IONFILEReadInChunksOptions.kt | 9 + .../model/IONFILEReadOptions.kt | 11 +- .../helper/IONFILELocalFilesHelperTest.kt | 251 +++++++++++------- 6 files changed, 248 insertions(+), 179 deletions(-) diff --git a/src/main/kotlin/io/ionic/libs/ionfilesystemlib/helper/IONFILELocalFilesHelper.kt b/src/main/kotlin/io/ionic/libs/ionfilesystemlib/helper/IONFILELocalFilesHelper.kt index e056fa5..19968c0 100644 --- a/src/main/kotlin/io/ionic/libs/ionfilesystemlib/helper/IONFILELocalFilesHelper.kt +++ b/src/main/kotlin/io/ionic/libs/ionfilesystemlib/helper/IONFILELocalFilesHelper.kt @@ -53,57 +53,6 @@ internal class IONFILELocalFilesHelper { } } - /** - * Reads a specific range of bytes from a file - * - * @param fullPath full path of the file to read from - * @param offset the starting position in the file - * @param length the number of bytes to read - * @param options options for reading the file (encoding) - * @return success with file contents string if it was read successfully, error otherwise - */ - suspend fun readRange( - fullPath: String, - offset: Long, - length: Int, - options: IONFILEReadOptions - ): Result = withContext(Dispatchers.IO) { - runCatching { - val file = File(fullPath) - if (!file.exists()) { - throw IONFILEExceptions.DoesNotExist(fullPath) - } - if (offset < 0) { - throw IllegalArgumentException("Offset cannot be negative") - } - if (length < 0) { - throw IllegalArgumentException("Length cannot be negative") - } - - java.io.RandomAccessFile(file, "r").use { raf -> - raf.seek(offset) - val buffer = ByteArray(length) - val bytesRead = raf.read(buffer) - - if (bytesRead == -1) { - return@use "" - } - - val actualBuffer = if (bytesRead < length) { - buffer.copyOf(bytesRead) - } else { - buffer - } - - if (options.encoding is IONFILEEncoding.WithCharset) { - String(actualBuffer, options.encoding.charset) - } else { - Base64.encodeToString(actualBuffer, Base64.NO_WRAP) - } - } - } - } - /** * Reads the contents of a file in chunks * 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..b7401ac 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 @@ -20,6 +20,7 @@ private const val FILE_3GA_EXTENSION = "3ga" private const val FILE_3GA_MIME_TYPE = "audio/3gpp" private const val FILE_JAVASCRIPT_EXTENSION = "js" private const val FILE_JAVASCRIPT_MIME_TYPE = "text/javascript" +internal const val LENGTH_DEFAULT_VALUE = Int.MAX_VALUE /** * Create a directory or file 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..e825cb4 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 @@ -15,12 +15,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 +66,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 +101,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 +136,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/IONFILEReadInChunksOptions.kt b/src/main/kotlin/io/ionic/libs/ionfilesystemlib/model/IONFILEReadInChunksOptions.kt index ce8198d..396bd9e 100644 --- a/src/main/kotlin/io/ionic/libs/ionfilesystemlib/model/IONFILEReadInChunksOptions.kt +++ b/src/main/kotlin/io/ionic/libs/ionfilesystemlib/model/IONFILEReadInChunksOptions.kt @@ -1,5 +1,7 @@ package io.ionic.libs.ionfilesystemlib.model +import io.ionic.libs.ionfilesystemlib.helper.common.LENGTH_DEFAULT_VALUE + /** * Parameters for reading a file in chunks * @@ -14,8 +16,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 = LENGTH_DEFAULT_VALUE ) \ 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..67a9706 100644 --- a/src/main/kotlin/io/ionic/libs/ionfilesystemlib/model/IONFILEReadOptions.kt +++ b/src/main/kotlin/io/ionic/libs/ionfilesystemlib/model/IONFILEReadOptions.kt @@ -1,10 +1,19 @@ package io.ionic.libs.ionfilesystemlib.model +import io.ionic.libs.ionfilesystemlib.helper.common.LENGTH_DEFAULT_VALUE + /** * 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 = LENGTH_DEFAULT_VALUE ) \ 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 634724c..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`() = @@ -830,106 +979,4 @@ class IONFILELocalFilesHelperTest : IONFILEBaseJUnitTest() { assertTrue(result.exceptionOrNull() is IONFILEExceptions.CopyRenameFailed.MixingFilesAndDirectories) } // endregion renameFile tests - // region readRange tests - @Test - fun `readRange should read specific bytes from file`() = 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.readRange( - fullPath = path, - offset = 7, - length = 5, - options = IONFILEReadOptions(encoding = IONFILEEncoding.WithCharset(Charsets.UTF_8)) - ) - - assertEquals("World", result.getOrNull()) - } - - @Test - fun `readRange should handle Base64 encoding`() = 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.readRange( - fullPath = path, - offset = 0, - length = 5, - options = IONFILEReadOptions(encoding = IONFILEEncoding.Base64) - ) - - // "Hello" in Base64 is "SGVsbG8=" - assertEquals("SGVsbG8=", result.getOrNull()) - } - - @Test - fun `readRange should handle EOF gracefully`() = 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.readRange( - fullPath = path, - offset = 3, - length = 10, // Try to read past EOF - options = IONFILEReadOptions(encoding = IONFILEEncoding.WithCharset(Charsets.UTF_8)) - ) - - assertEquals("45", result.getOrNull()) - } - - @Test - fun `readRange should return empty string if offset is at EOF`() = 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.readRange( - fullPath = path, - offset = 5, - length = 10, - options = IONFILEReadOptions(encoding = IONFILEEncoding.WithCharset(Charsets.UTF_8)) - ) - - assertEquals("", result.getOrNull()) - } - // endregion readRange tests } \ No newline at end of file From 0998307150757fc9a4ff48a2fe1341f67d4b4c34 Mon Sep 17 00:00:00 2001 From: OS-pedrogustavobilro Date: Wed, 14 Jan 2026 18:04:12 +0000 Subject: [PATCH 4/7] refactor: Move checks of offset and length to controller --- .../ionfilesystemlib/IONFILEController.kt | 4 ++ .../helper/common/IONFILECommon.kt | 13 +++++- .../helper/IONFILEControllerTests.kt | 42 +++++++++++++++++++ 3 files changed, 58 insertions(+), 1 deletion(-) 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 b7401ac..a37204a 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 @@ -134,6 +134,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 * @@ -164,4 +174,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/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 From cb7cd0468185fc787ac702570876bdfff688fdbb Mon Sep 17 00:00:00 2001 From: OS-pedrogustavobilro Date: Wed, 14 Jan 2026 18:04:26 +0000 Subject: [PATCH 5/7] docs: Update README and CHANGELOG --- CHANGELOG.md | 2 +- README.md | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index beef476..3022eda 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### 2025-12-31 -- Add `readRange` method. +- 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`. From a229e642842768077232388258d94816b9deb7ec Mon Sep 17 00:00:00 2001 From: OS-pedrogustavobilro Date: Thu, 15 Jan 2026 16:12:06 +0000 Subject: [PATCH 6/7] refactor: Rename length default value --- .../libs/ionfilesystemlib/helper/common/IONFILECommon.kt | 1 - .../helper/common/IONFILEInputStreamExtensions.kt | 3 ++- .../io/ionic/libs/ionfilesystemlib/model/IONFILEConstants.kt | 5 +++++ .../ionfilesystemlib/model/IONFILEReadInChunksOptions.kt | 4 +--- .../ionic/libs/ionfilesystemlib/model/IONFILEReadOptions.kt | 4 +--- 5 files changed, 9 insertions(+), 8 deletions(-) create mode 100644 src/main/kotlin/io/ionic/libs/ionfilesystemlib/model/IONFILEConstants.kt 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 a37204a..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 @@ -20,7 +20,6 @@ private const val FILE_3GA_EXTENSION = "3ga" private const val FILE_3GA_MIME_TYPE = "audio/3gpp" private const val FILE_JAVASCRIPT_EXTENSION = "js" private const val FILE_JAVASCRIPT_MIME_TYPE = "text/javascript" -internal const val LENGTH_DEFAULT_VALUE = Int.MAX_VALUE /** * Create a directory or file 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 e825cb4..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 @@ -17,7 +18,7 @@ import java.io.InputStreamReader */ internal fun InputStream.readFull(options: IONFILEReadOptions): String { applyOffset(options.offset) - if (options.length in 1.. Date: Thu, 15 Jan 2026 17:52:44 +0000 Subject: [PATCH 7/7] chore(release): Prepare version 1.1.0 --- CHANGELOG.md | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3022eda..4d97620 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ 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 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