// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later

package space.rcmd.android.sizzle.ui.toolbox

import java.io.ByteArrayOutputStream
import java.io.InputStream

/** Upper bound on an imported instrument/sample file we read fully into memory.
 *  SF2 SoundFonts can be hundreds of MB; reading one wholesale would OOM the app,
 *  so anything larger is rejected with a friendly error instead of crashing. */
const val MAX_IMPORT_BYTES: Int = 64 * 1024 * 1024

/**
 * Read the whole stream, but give up (returning null) once more than [cap] bytes
 * have been read — so a pathologically large file can't exhaust memory. Returns
 * the bytes on success, or null if the stream is longer than [cap].
 */
fun readCapped(input: InputStream, cap: Int = MAX_IMPORT_BYTES): ByteArray? {
    val out = ByteArrayOutputStream(minOf(cap, 1 shl 20))
    val chunk = ByteArray(64 * 1024)
    var total = 0L
    while (true) {
        val n = input.read(chunk)
        if (n < 0) break
        total += n
        if (total > cap) return null
        out.write(chunk, 0, n)
    }
    return out.toByteArray()
}
