Scoop API

scoop:scoop.asyncio:0.1.0

src/resolve.scoop

Selected production source · src/resolve.scoop

1package scoop.asyncio
3import scoop.platform.net.*
4import scoop.platform.system.*
6internal suspend fun resolveOnLoop(
7 loop: LoopOwner,
8 host: OsString,
9 port: Int,
10 family: AddressFamily?
11): Array<SocketAddress> {
12 val job = loop.requireJob()
13 if (port < 0 || port > 65535)
14 throw IllegalArgumentException(Some("port is out of range"))
15 val selector =
16 when (family) {
17 case Some(AddressFamily.Ipv4) -> 4
18 case Some(AddressFamily.Ipv6) -> 6
19 case None -> 0
20 }
21 return suspendCoroutine<Array<SocketAddress>> {
22 continuation ->
23 val operation =
24 CallbackOperation(
25 loop,
26 loop.nextOperation(),
27 {
28 native,
29 id -> @Unsafe
30 {
31 return@CallbackOperation host.withIoString {
32 pointer -> @Unsafe
33 {
34 return@withIoString nativeStatus(
35 id,
36 nativeResolve(native, id, pointer, port, selector)
37 )
38 }
39 }
40 }
41 },
42 {
43 native,
44 id -> @Unsafe
45 {
46 nativeWorkCancel(native, id)
47 }
48 },
49 {
50 event, selected ->
51 val addresses =
52 try {
53 resolutionResult(host, event.result, selected)
54 }
55 catch (error: Throwable) {
56 continuation.resumeWithException(error);
57 return@CallbackOperation
58 }
59 continuation.resume(addresses)
60 }
61 )
62 operation.subscribe(job)
63 loop.submit(operation)
64 }
67private fun resolutionResult(host: OsString, result: IoResult, selected: Throwable?): Array<
68 SocketAddress
69> {
70 when (result) {
71 case Addresses(Some(val head)) -> {
72 try {
73 when (selected) {
74 case Some(val error) -> throw error;
75 case None -> {}
76 }
77 val values = ArrayList<SocketAddress>()
78 var current: Ptr<Unit>? = Some(head)
79 @Unsafe
80 {
81 while (current != None) {
82 val result = nativeResolveAddress(current!!)
83 if (result.status.code != 0) {
84 val error = nativeStatusError(result.status)
85 throw PlatformException(
86 "resolve address",
87 error.kind,
88 Some(error),
89 Some(host)
90 )
91 }
92 values.add(ioSocketAddress(result.address))
93 current = nativeResolveNext(current!!)
94 }
95 }
96 return values.toArray()
97 } finally {
98 @Unsafe
99 {
100 nativeResolveFree(head)
101 }
102 }
103 }
104 case Addresses(None) -> {
105 when (selected) {
106 case Some(val error) -> throw error;
107 case None -> {}
108 }
109 return []
110 }
111 case _ -> throw (
112 completionFailure("resolve", result, selected, Some(host)) ?:
113 IllegalStateException(Some("resolver returned no address list"))
114 )
115 }