Scoop API

scoop:scoop.asyncio:0.1.0

src/directory.scoop

Selected production source · src/directory.scoop

1package scoop.asyncio
3import scoop.platform.fs.*
4import scoop.platform.system.OsString
6/**
7 * An owned asynchronous directory cursor. Close it even when iteration ends early.
8 */
9public interface AsyncDirectoryEntries: AsyncCloseable {
10 /**
11 * Returns the next directory entry, or None when the cursor is exhausted.
12 */
13 public suspend fun next(): DirectoryEntry?
16internal class WorkerDirectory(private val owner: OwnedDirectory): AsyncDirectoryEntries {
17 public override suspend fun next(): DirectoryEntry? {
18 val job = owner.loop.requireJob()
19 val name: OsString? =
20 when (owner.reserve()) {
21 case None -> None
22 case Some(val reservation) -> try {
23 nextDirectoryName(owner, job)
24 }
25 finally {
26 reservation.dispose()
27 }
28 }
29 return when (name) {
30 case Some(val value) -> Some(
31 DirectoryEntry(value, owner.path.resolve(Path.fromOsString(value)))
32 )
33 case None -> {
34 owner.close();
35 None
36 }
37 }
38 }
40 public override suspend fun close() {
41 owner.close()
42 }
45internal suspend fun openDirectoryOnLoop(loop: LoopOwner, path: Path): AsyncDirectoryEntries {
46 val job = loop.requireJob()
47 val context = path.toOsString()
48 return suspendCoroutine<AsyncDirectoryEntries> {
49 continuation ->
50 val operation =
51 CallbackOperation(
52 loop,
53 loop.nextOperation(),
54 {
55 native,
56 id -> @Unsafe
57 {
58 return@CallbackOperation path.withIoPath {
59 name -> @Unsafe
60 {
61 return@withIoPath nativeStatus(
62 id,
63 nativeDirectoryOpen(native, id, name)
64 )
65 }
66 }
67 }
68 },
69 {
70 native,
71 id -> @Unsafe
72 {
73 nativeWorkCancel(native, id)
74 }
75 },
76 {
77 event,
78 selected -> when (event.result) {
79 case Created(val pointer) -> {
80 val owner = OwnedDirectory(loop, pointer, path)
81 loop.retain(owner)
82 when (selected) {
83 case None -> continuation.resume(WorkerDirectory(owner))
84 case Some(val error) -> owner.closeOnLoop {
85 cleanup -> continuation.resumeWithException(
86 when (cleanup) {
87 case None -> error
88 case Some(val other) -> ResourceUseException(
89 error,
90 other
91 )
92 }
93 )
94 }
95 }
96 }
97 case _ -> continuation.resumeWithException(
98 completionFailure(
99 "open directory",
100 event.result,
101 selected,
102 Some(context)
103 ) ?:
104 IllegalStateException(Some("directory open returned no handle"))
105 )
106 }
107 }
108 )
109 operation.subscribe(job)
110 loop.submit(operation)
111 }
114@Extern(name = "scoop_io_directory_open")
115private fun nativeDirectoryOpen(loop: Ptr<Unit>, id: Long, path: Ptr<Byte>): Int