forked from vapor/postgres-nio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgresData+Double.swift
50 lines (45 loc) · 1.27 KB
/
PostgresData+Double.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
extension PostgresData {
public init(double: Double) {
var buffer = ByteBufferAllocator().buffer(capacity: 0)
buffer.writeDouble(double)
self.init(type: .float8, formatCode: .binary, value: buffer)
}
public var double: Double? {
guard var value = self.value else {
return nil
}
switch self.formatCode {
case .binary:
switch self.type {
case .float4:
return value.readFloat()
.flatMap { Double($0) }
case .float8:
return value.readDouble()
case .numeric:
return self.numeric?.double
default:
return nil
}
case .text:
guard let string = self.string else {
return nil
}
return Double(string)
}
}
}
extension Double: PostgresDataConvertible {
public static var postgresDataType: PostgresDataType {
return .float8
}
public init?(postgresData: PostgresData) {
guard let double = postgresData.double else {
return nil
}
self = double
}
public var postgresData: PostgresData? {
return .init(double: self)
}
}