forked from vapor/postgres-nio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFloat+PSQLCodable.swift
74 lines (65 loc) · 2.97 KB
/
Float+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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import NIOCore
extension Float: PSQLCodable {
var psqlType: PSQLDataType {
.float4
}
var psqlFormat: PSQLFormat {
.binary
}
static func decode(from buffer: inout ByteBuffer, type: PSQLDataType, format: PSQLFormat, context: PSQLDecodingContext) throws -> Float {
switch (format, type) {
case (.binary, .float4):
guard buffer.readableBytes == 4, let float = buffer.psqlReadFloat() else {
throw PSQLCastingError.failure(targetType: Self.self, type: type, postgresData: buffer, context: context)
}
return float
case (.binary, .float8):
guard buffer.readableBytes == 8, let double = buffer.psqlReadDouble() else {
throw PSQLCastingError.failure(targetType: Self.self, type: type, postgresData: buffer, context: context)
}
return Float(double)
case (.text, .float4), (.text, .float8):
guard let string = buffer.readString(length: buffer.readableBytes), let value = Float(string) else {
throw PSQLCastingError.failure(targetType: Self.self, type: type, postgresData: buffer, context: context)
}
return value
default:
throw PSQLCastingError.failure(targetType: Self.self, type: type, postgresData: buffer, context: context)
}
}
func encode(into byteBuffer: inout ByteBuffer, context: PSQLEncodingContext) {
byteBuffer.psqlWriteFloat(self)
}
}
extension Double: PSQLCodable {
var psqlType: PSQLDataType {
.float8
}
var psqlFormat: PSQLFormat {
.binary
}
static func decode(from buffer: inout ByteBuffer, type: PSQLDataType, format: PSQLFormat, context: PSQLDecodingContext) throws -> Double {
switch (format, type) {
case (.binary, .float4):
guard buffer.readableBytes == 4, let float = buffer.psqlReadFloat() else {
throw PSQLCastingError.failure(targetType: Self.self, type: type, postgresData: buffer, context: context)
}
return Double(float)
case (.binary, .float8):
guard buffer.readableBytes == 8, let double = buffer.psqlReadDouble() else {
throw PSQLCastingError.failure(targetType: Self.self, type: type, postgresData: buffer, context: context)
}
return double
case (.text, .float4), (.text, .float8):
guard let string = buffer.readString(length: buffer.readableBytes), let value = Double(string) else {
throw PSQLCastingError.failure(targetType: Self.self, type: type, postgresData: buffer, context: context)
}
return value
default:
throw PSQLCastingError.failure(targetType: Self.self, type: type, postgresData: buffer, context: context)
}
}
func encode(into byteBuffer: inout ByteBuffer, context: PSQLEncodingContext) {
byteBuffer.psqlWriteDouble(self)
}
}