forked from vapor/postgres-nio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgresData+Bool.swift
63 lines (57 loc) · 1.54 KB
/
PostgresData+Bool.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
extension PostgresData {
public init(bool: Bool) {
var buffer = ByteBufferAllocator().buffer(capacity: 1)
buffer.writeInteger(bool ? 1 : 0, as: UInt8.self)
self.init(type: .bool, formatCode: .binary, value: buffer)
}
public var bool: Bool? {
guard var value = self.value else {
return nil
}
guard value.readableBytes == 1 else {
return nil
}
guard let byte = value.readInteger(as: UInt8.self) else {
return nil
}
switch self.formatCode {
case .text:
switch byte {
case Character("t").asciiValue!:
return true
case Character("f").asciiValue!:
return false
default:
return nil
}
case .binary:
switch byte {
case 1:
return true
case 0:
return false
default:
return nil
}
}
}
}
extension PostgresData: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self.init(bool: value)
}
}
extension Bool: PostgresDataConvertible {
public static var postgresDataType: PostgresDataType {
return .bool
}
public var postgresData: PostgresData? {
return .init(bool: self)
}
public init?(postgresData: PostgresData) {
guard let bool = postgresData.bool else {
return nil
}
self = bool
}
}