Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@
<modelVersion>4.0.0</modelVersion>
<groupId>io.ionic.libs</groupId>
<artifactId>ionfilesystem-android</artifactId>
<version>1.0.0</version>
<version>1.1.0</version>
</project>
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -97,6 +98,8 @@ class IONFILEController internal constructor(
uri: IONFILEUri,
options: IONFILEReadOptions
): Result<String> = 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 {
Expand Down Expand Up @@ -138,6 +141,7 @@ class IONFILEController internal constructor(
uri: IONFILEUri,
options: IONFILEReadInChunksOptions
): Flow<String> = flow {
validateOffsetAndLength(offset = options.offset, length = options.length)
val resolveResult = uriHelper.useUriIfResolvedAsNonDirectory(uri) { Result.success(it) }
resolveResult.fold(
onSuccess = { resolvedUri ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand Down Expand Up @@ -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
} ?: false

Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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..<IONFILEConstants.LENGTH_READ_TIL_EOF) {
var chunkBytesRead: Int
var readFile = ""
var totalBytesRead = 0
do {
val remainingBytesToRead = options.length - totalBytesRead
val bufferSize = minOf(
options.encoding.convertChunkSize(DEFAULT_BUFFER_SIZE),
remainingBytesToRead
)
val byteArray = ByteArray(bufferSize)
chunkBytesRead = readChunk(byteArray, bufferSize)
processReadChunk(byteArray, chunkBytesRead, options.encoding)?.let {
totalBytesRead += chunkBytesRead
readFile += it
}
} while (chunkBytesRead > 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.
Expand All @@ -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)
}

/**
Expand All @@ -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.
Expand All @@ -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
}
}
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())
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package io.ionic.libs.ionfilesystemlib.model

object IONFILEConstants {
const val LENGTH_READ_TIL_EOF = Int.MAX_VALUE
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
}
Loading