Scoop API

scoop:scoop.platform:0.1.0

src/net/socket_owner.scoop

Selected production source · src/net/socket_owner.scoop

1package scoop.platform.net
3import scoop.platform.system.*
5@CLayout
6internal struct NativeSocketHandle(val value: ULong)
8@CLayout
9internal struct NativeSocketOpened(val handle: NativeSocketHandle, val error: Int)
11@CLayout
12internal struct NativeSocketResult(val value: Long, val error: Int) {
13 fun checked(operation: String): Long {
14 checkSocketError(operation, error)
15 return value
16 }
19internal fun checkSocketError(operation: String, code: Int) {
20 if (code != 0) {
21 val domain =
22 if (operatingSystem == OperatingSystem.Windows)
23 NativeErrorDomain.Winsock
24 else
25 NativeErrorDomain.PosixErrno
26 val error = NativeError(domain, code)
27 throw PlatformException(operation, error.kind, Some(error))
28 }
31// Socket lifetime is independent of file handles and CRT descriptors.
32internal 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_VALUE
37 fun adopt(result: NativeSocketOpened, operation: String) {
38 checkSocketError(operation, result.error)
39 handle = result.handle
40 }
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 return
61 if (active.load(MemoryOrder.Relaxed) != 0L)
62 throw IllegalStateException(Some("socket operation is active"))
63 val owned = handle
64 handle = NativeSocketHandle(ULong.MAX_VALUE)
65 @Unsafe
66 {
67 nativeSocketClose(owned).checked("close socket")
68 }
69 }
71 release {
72 if (handle.value != ULong.MAX_VALUE) {
73 @Unsafe
74 {
75 nativeSocketClose(handle)
76 }
77 }
78 }
81@Extern(name = "scoop_platform_socket_close")
82private fun nativeSocketClose(handle: NativeSocketHandle): NativeSocketResult