This repository has been archived by the owner on Mar 29, 2022. It is now read-only.
generated from arrow-kt/Arrow-MPP-Template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
example-readme-10.kt
56 lines (49 loc) · 1.68 KB
/
example-readme-10.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// This file was automatically generated from README.md by Knit tool. Do not edit.
package example.exampleReadme10
import arrow.*
import arrow.core.*
import arrow.fx.coroutines.*
import kotlinx.coroutines.*
import io.kotest.matchers.collections.*
import io.kotest.assertions.*
import io.kotest.matchers.*
import io.kotest.matchers.types.*
import kotlin.coroutines.cancellation.CancellationException
import io.kotest.property.*
import io.kotest.property.arbitrary.*
import arrow.core.test.generators.*
import java.io.*
@JvmInline
value class Content(val body: List<String>)
sealed interface FileError
@JvmInline value class SecurityError(val msg: String?) : FileError
@JvmInline value class FileNotFound(val path: String) : FileError
object EmptyPath : FileError {
override fun toString() = "EmptyPath"
}
fun readFile(path: String?): Cont<FileError, Content> = cont {
ensureNotNull(path) { EmptyPath }
ensure(path.isNotEmpty()) { EmptyPath }
try {
val lines = File(path).readLines()
Content(lines)
} catch (e: FileNotFoundException) {
shift(FileNotFound(path))
} catch (e: SecurityException) {
shift(SecurityError(e.message))
}
}
suspend fun <A> awaitExitCase(exit: CompletableDeferred<ExitCase>): A =
guaranteeCase(::awaitCancellation) { exitCase -> exit.complete(exitCase) }
suspend fun test() {
val exit = CompletableDeferred<ExitCase>()
cont<FileError, Int> {
withContext(Dispatchers.IO) {
val job = launch { awaitExitCase(exit) }
val content = readFile("failure").bind()
job.join()
content.body.size
}
}.fold({ e -> e shouldBe FileNotFound("failure") }, { fail("Int can never be the result") })
exit.await().shouldBeInstanceOf<ExitCase>()
}