1+ public struct PostgresINET {
2+ public let ipFamily : UInt8
3+ public let netmaskLength : UInt8
4+ public let isCIDR : Bool
5+ public let addressLength : UInt8
6+ public let ipAddress : [ UInt8 ]
7+ }
8+
9+ extension PostgresINET : PostgresDecodable {
10+ public init < JSONDecoder: PostgresJSONDecoder > ( from byteBuffer: inout ByteBuffer , type: PostgresDataType , format: PostgresFormat , context: PostgresDecodingContext < JSONDecoder > ) throws {
11+ // IP family
12+ guard let ipFamily: UInt8 = byteBuffer. readInteger ( as: UInt8 . self) else {
13+ throw PostgresDecodingError . Code. failure
14+ }
15+
16+ // netmask length in bits
17+ guard let netmaskLength: UInt8 = byteBuffer. readInteger ( as: UInt8 . self) else {
18+ throw PostgresDecodingError . Code. failure
19+ }
20+
21+ // whether it is a CIDR
22+ let isCIDR : Bool
23+ switch byteBuffer. readInteger ( as: UInt8 . self) {
24+ case . some( 0 ) :
25+ isCIDR = false
26+ case . some( 1 ) :
27+ isCIDR = true
28+ default :
29+ throw PostgresDecodingError . Code. failure
30+ }
31+
32+ // address length in bytes
33+ guard let addressLength: UInt8 = byteBuffer. readInteger ( as: UInt8 . self) ,
34+ addressLength * 8 == netmaskLength,
35+ let ipAddress: [ UInt8 ] = byteBuffer. readBytes ( length: Int ( addressLength) )
36+ else {
37+ throw PostgresDecodingError . Code. failure
38+ }
39+
40+ self . init (
41+ ipFamily: ipFamily,
42+ netmaskLength: netmaskLength,
43+ isCIDR: isCIDR,
44+ addressLength: addressLength,
45+ ipAddress: ipAddress
46+ )
47+ }
48+ }
49+
50+ extension PostgresINET : PostgresEncodable & PostgresNonThrowingEncodable {
51+ public static var psqlType : PostgresDataType { return . inet }
52+ public static var psqlFormat : PostgresFormat { . binary }
53+ public func encode< JSONEncoder: PostgresJSONEncoder > ( into byteBuffer: inout ByteBuffer , context: PostgresEncodingContext < JSONEncoder > ) {
54+ byteBuffer. writeInteger ( self . ipFamily, as: UInt8 . self)
55+ byteBuffer. writeInteger ( self . netmaskLength, as: UInt8 . self)
56+ byteBuffer. writeInteger ( self . isCIDR ? 1 : 0 , as: UInt8 . self)
57+ byteBuffer. writeInteger ( self . addressLength, as: UInt8 . self)
58+ byteBuffer. writeBytes ( self . ipAddress)
59+ }
60+ }
61+
62+ extension PostgresINET : PostgresArrayDecodable { }
63+
64+ extension PostgresINET : PostgresArrayEncodable {
65+ public static var psqlArrayType : PostgresDataType { return . inetArray }
66+ }
0 commit comments