forked from vapor/postgres-nio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBool+PSQLCodable.swift
50 lines (43 loc) · 1.75 KB
/
Bool+PSQLCodable.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
import NIOCore
extension Bool: PSQLCodable {
var psqlType: PSQLDataType {
.bool
}
var psqlFormat: PSQLFormat {
.binary
}
static func decode(from buffer: inout ByteBuffer, type: PSQLDataType, format: PSQLFormat, context: PSQLDecodingContext) throws -> Bool {
guard type == .bool else {
throw PSQLCastingError.failure(targetType: Self.self, type: type, postgresData: buffer, context: context)
}
switch format {
case .binary:
guard buffer.readableBytes == 1 else {
throw PSQLCastingError.failure(targetType: Self.self, type: type, postgresData: buffer, context: context)
}
switch buffer.readInteger(as: UInt8.self) {
case .some(0):
return false
case .some(1):
return true
default:
throw PSQLCastingError.failure(targetType: Self.self, type: type, postgresData: buffer, context: context)
}
case .text:
guard buffer.readableBytes == 1 else {
throw PSQLCastingError.failure(targetType: Self.self, type: type, postgresData: buffer, context: context)
}
switch buffer.readInteger(as: UInt8.self) {
case .some(UInt8(ascii: "f")):
return false
case .some(UInt8(ascii: "t")):
return true
default:
throw PSQLCastingError.failure(targetType: Self.self, type: type, postgresData: buffer, context: context)
}
}
}
func encode(into byteBuffer: inout ByteBuffer, context: PSQLEncodingContext) {
byteBuffer.writeInteger(self ? 1 : 0, as: UInt8.self)
}
}