scoop:scoop.asyncio:0.1.0
src/file_control.scoop
Selected production source · src/file_control.scoop
1
package scoop.asyncio3
import scoop.platform.fs.FileMetadata5
internal suspend fun fileMetadata(owner: OwnedFile): FileMetadata {6
val job = owner.loop.requireJob()7
return fileControl<FileMetadata>(8
owner,9
job,10
"file metadata",11
{12
id -> @Unsafe13
{14
return@fileControl nativeFileMetadata(owner.pointer, id)15
}16
},17
{ result -> metadataResult(result) }18
)19
}21
internal suspend fun filePosition(owner: OwnedFile, offset: Long, current: Boolean): Long {22
val job = owner.loop.requireJob()23
if (offset < 0L)24
throw IllegalArgumentException(Some("negative file position"))25
return fileControl<Long>(26
owner,27
job,28
"file seek",29
{30
id -> @Unsafe31
{32
return@fileControl nativeFileSeek(owner.pointer, id, offset, current)33
}34
},35
{36
result -> when (result) {37
case Position(val value) -> value38
case _ -> throw IllegalStateException(Some("seek returned no position"))39
}40
}41
)42
}44
internal suspend fun truncateFile(owner: OwnedFile, size: Long) {45
val job = owner.loop.requireJob()46
if (size < 0L)47
throw IllegalArgumentException(Some("negative file size"))48
fileControl<Unit>(49
owner,50
job,51
"file truncate",52
{53
id -> @Unsafe54
{55
return@fileControl nativeFileTruncate(owner.pointer, id, size)56
}57
},58
{ result -> requireFileDone(result) }59
)60
}62
internal suspend fun syncFile(owner: OwnedFile, dataOnly: Boolean) {63
val job = owner.loop.requireJob()64
fileControl<Unit>(65
owner,66
job,67
"file sync",68
{69
id -> @Unsafe70
{71
return@fileControl nativeFileSync(owner.pointer, id, dataOnly)72
}73
},74
{ result -> requireFileDone(result) }75
)76
}78
private fun requireFileDone(result: IoResult) {79
when (result) {80
case Done -> {}81
case _ -> throw IllegalStateException(Some("file operation returned an invalid completion"))82
}83
}85
private suspend fun <R> fileControl(86
owner: OwnedFile,87
job: Job,88
operationName: String,89
start: (Long) -> Int,90
result: (IoResult) -> R91
): R {92
val reservation = owner.reserve()93
try {94
return suspendCoroutine<R> {95
continuation ->96
val operation =97
CallbackOperation(98
owner.loop,99
owner.loop.nextOperation(),100
{ _, id -> nativeStatus(id, start(id)) },101
{102
native,103
id -> @Unsafe104
{105
nativeWorkCancel(native, id)106
}107
},108
{109
event, selected ->110
val failure =111
completionFailure(112
operationName,113
event.result,114
selected,115
Some(owner.context)116
)117
when (failure) {118
case Some(val error) -> continuation.resumeWithException(error)119
case None -> {120
val value =121
try {122
result(event.result)123
}124
catch (error: Throwable) {125
continuation.resumeWithException(error);126
return@CallbackOperation127
}128
continuation.resume(value)129
}130
}131
}132
)133
operation.subscribe(job)134
owner.attach(operation)135
owner.loop.submit(operation)136
}137
} finally {138
reservation.dispose()139
}140
}