forked from vapor/postgres-nio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDecimal+PostgresCodable.swift
49 lines (45 loc) · 1.54 KB
/
Decimal+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
import NIOCore
import struct Foundation.Decimal
extension Decimal: PostgresEncodable {
public static var psqlType: PostgresDataType {
.numeric
}
public static var psqlFormat: PostgresFormat {
.binary
}
public func encode<JSONEncoder: PostgresJSONEncoder>(
into byteBuffer: inout ByteBuffer,
context: PostgresEncodingContext<JSONEncoder>
) {
let numeric = PostgresNumeric(decimal: self)
byteBuffer.writeInteger(numeric.ndigits)
byteBuffer.writeInteger(numeric.weight)
byteBuffer.writeInteger(numeric.sign)
byteBuffer.writeInteger(numeric.dscale)
var value = numeric.value
byteBuffer.writeBuffer(&value)
}
}
extension Decimal: PostgresDecodable {
public init<JSONDecoder: PostgresJSONDecoder>(
from buffer: inout ByteBuffer,
type: PostgresDataType,
format: PostgresFormat,
context: PostgresDecodingContext<JSONDecoder>
) throws {
switch (format, type) {
case (.binary, .numeric):
guard let numeric = PostgresNumeric(buffer: &buffer) else {
throw PostgresDecodingError.Code.failure
}
self = numeric.decimal
case (.text, .numeric):
guard let string = buffer.readString(length: buffer.readableBytes), let value = Decimal(string: string) else {
throw PostgresDecodingError.Code.failure
}
self = value
default:
throw PostgresDecodingError.Code.typeMismatch
}
}
}