Scoop API

scoop:scoop.platform:0.1.0

src/net/socket_address.scoop

Selected production source · src/net/socket_address.scoop

1package scoop.platform.net
3import scoop.text.*
5/**
6 * An immutable numeric IP endpoint with a validated network port.
7 */
8public class SocketAddress public constructor(
9 /**
10 * The endpoint's numeric IP address.
11 */
12 public val address: IpAddress,
13 /**
14 * The endpoint port; zero can request an ephemeral local port when binding.
15 */
16 public val port: Int
17): Equals<SocketAddress>, Hash, ToString {
18 init {
19 requirePort(port)
20 }
21 /**
22 * Compares the complete normalized address identity, including its relevant family, scope,
23 * prefix, or port.
24 */
25 public override operator fun equals(other: SocketAddress): Boolean =
26 address == other.address && port == other.port
27 /**
28 * Hashes the same address identity used by equality.
29 */
30 public override fun hash(): Long = address.hash() * 31L + port.toLong()
31 /**
32 * Returns numeric address notation without performing name resolution.
33 */
34 public override fun toString(): String =
35 (
36 if (address.family == AddressFamily.Ipv6)
37 "[" + address.toString() + "]"
38 else
39 address.toString()
40 ) +
41 ":" +
42 port.toString()
44 /**
45 * Parses numeric endpoint text without DNS lookup.
46 */
47 public companion object {
48 /**
49 * Parses address and port, including bracketed IPv6 endpoint syntax.
50 */
51 public fun parse(text: String): SocketAddress {
52 val bracketed = text.startsWith("[")
53 val separator =
54 if (bracketed)
55 text.lastIndexOf("]:")
56 else
57 text.lastIndexOf(':')
58 if (separator < 1L)
59 throw IllegalArgumentException(Some("invalid socket address"))
60 val address =
61 IpAddress.parse(
62 text.slice(
63 if (bracketed)
64 1L
65 else
66 0L,
67 separator
68 )
69 )
70 if (bracketed != (address.family == AddressFamily.Ipv6))
71 throw IllegalArgumentException(Some("IPv6 endpoint requires brackets"))
72 val port =
73 decimal(
74 text.slice(
75 separator +
76 (
77 if (bracketed)
78 2L
79 else
80 1L
81 ),
82 text.charLength
83 )
84 )
85 if (port > 65535u)
86 throw IllegalArgumentException(Some("port is outside 0..65535"))
87 return SocketAddress(address, port.toInt())
88 }
89 }