Created
April 2, 2023 17:17
-
-
Save imuromtsev/833e2631a05591d8065e4ae7c8a623ae to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ru.spbsu.kotlin | |
import kotlinx.coroutines.ExperimentalCoroutinesApi | |
import kotlinx.coroutines.channels.ReceiveChannel | |
import kotlinx.coroutines.channels.produce | |
import kotlinx.coroutines.newSingleThreadContext | |
import kotlinx.coroutines.runBlocking | |
import kotlinx.coroutines.withContext | |
import java.io.File | |
import java.io.InputStream | |
import kotlin.coroutines.CoroutineContext | |
@OptIn(ExperimentalCoroutinesApi::class) | |
class DecodeStream(rootFolder: File) : InputStream() { | |
private val context: CoroutineContext = newSingleThreadContext("io") | |
private val channel: ReceiveChannel<Int> = runBlocking(context) { | |
produce { | |
for (file in rootFolder.scanFolders()) { | |
val currentXor = (file.lastModified() % 10).toInt() | |
file.inputStream().use { | |
while(true) { | |
val byte = it.read(); | |
if (byte == -1) { | |
break; | |
} | |
send(byte xor currentXor) | |
} | |
} | |
} | |
send(-1) | |
} | |
} | |
override fun read(): Int { | |
return runBlocking { | |
channel.receive() | |
} | |
} | |
} | |
fun File.scanFolders(): List<File> { | |
val listFiles = mutableListOf<File>() | |
scanFolders(this, listFiles) | |
return listFiles.toList() | |
} | |
private fun scanFolders(file: File, result: MutableList<File>) { | |
if (file.isFile) { | |
result += file | |
return | |
} | |
val directoryFiles = file.listFiles()!!.sortedBy { it.name } | |
for (currentFile in directoryFiles) { | |
scanFolders(currentFile, result) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment