From c0f884b81b2e3f196824d137cd7549e82860fbf6 Mon Sep 17 00:00:00 2001 From: Zahary Karadjov Date: Fri, 5 Jun 2020 17:05:22 +0300 Subject: [PATCH] Add shims/net for forced IP address initialization --- stew/shims/net.nim | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 stew/shims/net.nim diff --git a/stew/shims/net.nim b/stew/shims/net.nim new file mode 100644 index 0000000..9416620 --- /dev/null +++ b/stew/shims/net.nim @@ -0,0 +1,33 @@ +import std/net as stdNet +export stdNet + +type + ValidIpAddress* = distinct IpAddress + +{.push raises: [Defect].} + +proc ipv4*(address: array[4, byte]): ValidIpAddress = + ValidIpAddress IpAddress(family: IPv4, address_v4: address) + +template ipv4*(a, b, c, d: byte): ValidIpAddress = + ipv4([a, b, c, d]) + +proc ipv6*(address: array[16, byte]): ValidIpAddress = + ValidIpAddress IpAddress(family: IPv6, address_v6: address) + +template family*(a: ValidIpAddress): IpAddressFamily = + IpAddress(a).family + +template address_v4*(a: ValidIpAddress): array[4, byte] = + IpAddress(a).address_v4 + +template address_v6*(a: ValidIpAddress): array[16, byte] = + IpAddress(a).address_v6 + +template `$`*(a: ValidIpAddress): string = + $ IpAddress(a) + +func init*(T: type ValidIpAddress, str: string): T + {.raises: [ValueError].} = + ValidIpAddress stdNet.parseIpAddress(str) +