Joris PZ
12/06/2020, 12:20 PMsrc\commonMain\resources\day01.txt
and read its contents as text in my solutions. This isn't trivial in Kotlin multi-platform, as a.) there isn't a common file API, and b.) only the JVM provides standardized access to the resources directory.
To deal with this platform-dependent stuff, Kotlin MPP offers the `expect`/`actual` mechanism. In common code, I declare that each target platform (JVM, Node and native) should offer a readInput
function:
expect fun readInput(name: String): String
The, each platform can implement this in a platform-specific way:
JVM:
actual fun readInput(name: String) = {}::class.java.getResource(name).readText()
Since Node and native don't get access to the resources directory, I use an enviroment variable AOC_INPUT_DIR
to define the directory where they should look for the input files. Their implementations then become:
Node:
external fun require(name: String): dynamic
val fs = require("fs")
val path = require("path")
actual fun readInput(name: String): String {
val path = path.join(process.env.AOC_INPUT_DIR, name)
return fs.readFileSync(path, "utf8") as String
}
Native:
actual fun readInput(name: String): String {
val returnBuffer = StringBuilder()
val inputDir = getenv("AOC_INPUT_DIR")?.toKString() ?: ""
val file = fopen("""$inputDir\$name""", "r") ?: throw IllegalArgumentException("Cannot open input file $name")
try {
memScoped {
val readBufferLength = 64 * 1024
val buffer = allocArray<ByteVar>(readBufferLength)
var line = fgets(buffer, readBufferLength, file)?.toKString()
while (line != null) {
returnBuffer.append(line)
line = fgets(buffer, readBufferLength, file)?.toKString()
}
}
} finally {
fclose(file)
}
return returnBuffer.toString()
}
I'm not sure I'm actually going to use this, I don't really mind having the input in the source, but at least I know how to do it now 🙂ephemient
12/06/2020, 1:53 PMval generateInputSources by tasks.creating {
inputs.files("*.txt")
outputs.dir("build/generated/source/inputs")
doLast {
// read *.txt, write *.kt
}
}
sourceSets["main"].java.srcDir(generateSources.outputs.files)
todd.ginsberg
12/06/2020, 2:25 PMJoris PZ
12/06/2020, 2:40 PMtodd.ginsberg
12/06/2020, 2:44 PMJoris PZ
12/06/2020, 3:04 PMtodd.ginsberg
12/06/2020, 4:28 PMbjonnh
12/06/2020, 5:20 PM