scoop:scoop.platform:0.1.0
src/net/socket_owner.scoop
Selected production source · src/net/socket_owner.scoop
1
package scoop.platform.net3
import scoop.platform.system.*5
@CLayout6
internal struct NativeSocketHandle(val value: ULong)8
@CLayout9
internal struct NativeSocketOpened(val handle: NativeSocketHandle, val error: Int)11
@CLayout12
internal struct NativeSocketResult(val value: Long, val error: Int) {13
fun checked(operation: String): Long {14
checkSocketError(operation, error)15
return value16
}17
}19
internal fun checkSocketError(operation: String, code: Int) {20
if (code != 0) {21
val domain =22
if (operatingSystem == OperatingSystem.Windows)23
NativeErrorDomain.Winsock24
else25
NativeErrorDomain.PosixErrno26
val error = NativeError(domain, code)27
throw PlatformException(operation, error.kind, Some(error))28
}29
}31
// Socket lifetime is independent of file handles and CRT descriptors.32
internal class SocketOwner {33
private var handle: NativeSocketHandle = NativeSocketHandle(ULong.MAX_VALUE)34
private val active: AtomicLong = AtomicLong(0L)35
val isClosed: Boolean get() = handle.value == ULong.MAX_VALUE37
fun adopt(result: NativeSocketOpened, operation: String) {38
checkSocketError(operation, result.error)39
handle = result.handle40
}42
fun requireOpen() {43
if (isClosed)44
throw IllegalStateException(Some("socket is closed"))45
}47
fun <R> withHandle(block: (NativeSocketHandle) -> R): R {48
requireOpen()49
active.fetchAdd(1L, MemoryOrder.Relaxed)50
try {51
return block(handle)52
}53
finally {54
active.fetchSub(1L, MemoryOrder.Relaxed)55
}56
}58
fun close() {59
if (isClosed)60
return61
if (active.load(MemoryOrder.Relaxed) != 0L)62
throw IllegalStateException(Some("socket operation is active"))63
val owned = handle64
handle = NativeSocketHandle(ULong.MAX_VALUE)65
@Unsafe66
{67
nativeSocketClose(owned).checked("close socket")68
}69
}71
release {72
if (handle.value != ULong.MAX_VALUE) {73
@Unsafe74
{75
nativeSocketClose(handle)76
}77
}78
}79
}81
@Extern(name = "scoop_platform_socket_close")82
private fun nativeSocketClose(handle: NativeSocketHandle): NativeSocketResult