forked from vapor/postgres-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgreSQLData+Data.swift
49 lines (40 loc) · 1.65 KB
/
PostgreSQLData+Data.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import Foundation
extension Data: PostgreSQLDataCustomConvertible {
/// See `PostgreSQLDataCustomConvertible.postgreSQLDataType`
public static var postgreSQLDataType: PostgreSQLDataType { return .bytea }
/// See `PostgreSQLDataCustomConvertible.postgreSQLDataArrayType`
public static var postgreSQLDataArrayType: PostgreSQLDataType { return ._bytea }
/// See `PostgreSQLDataCustomConvertible.convertFromPostgreSQLData(_:)`
public static func convertFromPostgreSQLData(_ data: PostgreSQLData) throws -> Data {
guard let value = data.data else {
throw PostgreSQLError(identifier: "data", reason: "Could not decode Data from `null` data.")
}
switch data.type {
case .bytea:
switch data.format {
case .text: return try Data(hexString: value[2...].makeString())
case .binary: return value
}
default: throw PostgreSQLError(identifier: "data", reason: "Could not decode Data from data type: \(data.type)")
}
}
/// See `PostgreSQLDataCustomConvertible.convertToPostgreSQLData()`
public func convertToPostgreSQLData() throws -> PostgreSQLData {
return PostgreSQLData(type: .bytea, format: .binary, data: self)
}
}
extension Data {
/// Initialize data from a hex string.
internal init(hexString: String) {
var data = Data()
var gen = hexString.makeIterator()
while let c1 = gen.next(), let c2 = gen.next() {
let s = String([c1, c2])
guard let d = UInt8(s, radix: 16) else {
break
}
data.append(d)
}
self.init(data)
}
}