forked from vapor/postgres-nio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBool+PostgresCodable.swift
62 lines (55 loc) · 1.68 KB
/
Bool+PostgresCodable.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
import NIOCore
extension Bool: PostgresDecodable {
@inlinable
public init<JSONDecoder: PostgresJSONDecoder>(
from buffer: inout ByteBuffer,
type: PostgresDataType,
format: PostgresFormat,
context: PostgresDecodingContext<JSONDecoder>
) throws {
guard type == .bool else {
throw PostgresDecodingError.Code.typeMismatch
}
switch format {
case .binary:
guard buffer.readableBytes == 1 else {
throw PostgresDecodingError.Code.failure
}
switch buffer.readInteger(as: UInt8.self) {
case .some(0):
self = false
case .some(1):
self = true
default:
throw PostgresDecodingError.Code.failure
}
case .text:
guard buffer.readableBytes == 1 else {
throw PostgresDecodingError.Code.failure
}
switch buffer.readInteger(as: UInt8.self) {
case .some(UInt8(ascii: "f")):
self = false
case .some(UInt8(ascii: "t")):
self = true
default:
throw PostgresDecodingError.Code.failure
}
}
}
}
extension Bool: PostgresNonThrowingEncodable {
public static var psqlType: PostgresDataType {
.bool
}
public static var psqlFormat: PostgresFormat {
.binary
}
@inlinable
public func encode<JSONEncoder: PostgresJSONEncoder>(
into byteBuffer: inout ByteBuffer,
context: PostgresEncodingContext<JSONEncoder>
) {
byteBuffer.writeInteger(self ? 1 : 0, as: UInt8.self)
}
}