Skip to content

Commit

Permalink
better readFloat/Double methods, #46
Browse files Browse the repository at this point in the history
  • Loading branch information
tanner0101 committed Aug 12, 2019
1 parent d0b93f9 commit 07b5ed0
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 31 deletions.
4 changes: 2 additions & 2 deletions Sources/PostgresNIO/Data/PostgresData+Double.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ extension PostgresData {
case .binary:
switch self.type {
case .float4:
return value.readFloat(as: Float.self)
return value.readFloat()
.flatMap { Double($0) }
case .float8:
return value.readFloat(as: Double.self)
return value.readDouble()
case .numeric:
return self.numeric?.double
default:
Expand Down
4 changes: 2 additions & 2 deletions Sources/PostgresNIO/Data/PostgresData+Float.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ extension PostgresData {
case .binary:
switch self.type {
case .float4:
return value.readFloat(as: Float.self)
return value.readFloat()
case .float8:
return value.readFloat(as: Double.self)
return value.readDouble()
.flatMap { Float($0) }
default:
return nil
Expand Down
41 changes: 14 additions & 27 deletions Sources/PostgresNIO/Utilities/NIOUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -65,35 +65,22 @@ internal extension ByteBuffer {
}
return array
}

mutating func readFloat<T: BinaryFloatingPoint>(as: T.Type = T.self) -> T? {
guard self.readableBytes >= MemoryLayout<T>.size else {
return nil
}

let value: T = self.getFloat(at: self.readerIndex)! /* must work as we have enough bytes */
// should be MoveReaderIndex
self.moveReaderIndex(forwardBy: MemoryLayout<T>.size)
return value

mutating func readFloat() -> Float? {
return self.readInteger(as: UInt32.self).map { Float(bitPattern: $0) }
}

func getFloat<T: BinaryFloatingPoint>(at index: Int, as: T.Type = T.self) -> T? {
precondition(index >= 0, "index must not be negative")
return self.withVeryUnsafeBytes { ptr in
guard index <= ptr.count - MemoryLayout<T>.size else {
return nil
}
var value: T = 0
withUnsafeMutableBytes(of: &value) { valuePtr in
valuePtr.copyBytes(
from: UnsafeRawBufferPointer(
start: ptr.baseAddress!.advanced(by: index),
count: MemoryLayout<T>.size
).reversed()
)
}
return value
}
mutating func readDouble() -> Double? {
return self.readInteger(as: UInt64.self).map { Double(bitPattern: $0) }
}


func getFloat(at index: Int) -> Float? {
return self.getInteger(at: index, as: UInt32.self).map { Float(bitPattern: $0) }
}

func getDouble(at index: Int) -> Double? {
return self.getInteger(at: index, as: UInt64.self).map { Double(bitPattern: $0) }
}

mutating func readUUID() -> UUID? {
Expand Down

0 comments on commit 07b5ed0

Please sign in to comment.