mirror of
https://github.com/Dev1an/MsgPack.git
synced 2026-04-04 10:25:51 +00:00
Encode floats
This commit is contained in:
parent
afae5bb0bc
commit
112d35f359
3 changed files with 45 additions and 13 deletions
|
|
@ -94,11 +94,11 @@ extension MsgPack.Serialiser: SingleValueEncodingContainer {
|
|||
}
|
||||
|
||||
func encode(_ value: Float) throws {
|
||||
throw Error.notImplemented
|
||||
storage = .float32(value)
|
||||
}
|
||||
|
||||
func encode(_ value: Double) throws {
|
||||
throw Error.notImplemented
|
||||
storage = .float64(value)
|
||||
}
|
||||
|
||||
func encode(_ value: String) throws {
|
||||
|
|
|
|||
|
|
@ -29,6 +29,9 @@ enum Format {
|
|||
case int16(Int16)
|
||||
case int32(Int32)
|
||||
case int64(Int64)
|
||||
|
||||
case float32(Float)
|
||||
case float64(Double)
|
||||
|
||||
func appendTo(data: inout Data) {
|
||||
switch self {
|
||||
|
|
@ -128,6 +131,26 @@ enum Format {
|
|||
#else
|
||||
Format.int64(Int64(value)).appendTo(data: &data)
|
||||
#endif
|
||||
|
||||
// MARK: Floats
|
||||
case .float32(let value):
|
||||
var newData = Data(count: 5)
|
||||
newData.withUnsafeMutableBytes({ (byteContainer: UnsafeMutablePointer<UInt8>) -> Void in
|
||||
byteContainer.pointee = 0xCA
|
||||
byteContainer.advanced(by: 1).withMemoryRebound(to: UInt32.self, capacity: 1) {
|
||||
$0.pointee = value.bitPattern.bigEndian
|
||||
}
|
||||
})
|
||||
data.append(newData)
|
||||
case .float64(let value):
|
||||
var newData = Data(count: 9)
|
||||
newData.withUnsafeMutableBytes({ (byteContainer: UnsafeMutablePointer<UInt8>) -> Void in
|
||||
byteContainer.pointee = 0xCB
|
||||
byteContainer.advanced(by: 1).withMemoryRebound(to: UInt64.self, capacity: 1) {
|
||||
$0.pointee = value.bitPattern.bigEndian
|
||||
}
|
||||
})
|
||||
data.append(newData)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,17 +5,26 @@ import Foundation
|
|||
|
||||
let encoder = Encoder()
|
||||
|
||||
let data = try encoder.encode(0x0102030405060708)
|
||||
let integerData = try encoder.encode(0x0102030405060708)
|
||||
|
||||
String(data[0], radix: 16)
|
||||
String(integerData[0], radix: 16)
|
||||
|
||||
data[1]
|
||||
data[2]
|
||||
data[3]
|
||||
data[4]
|
||||
data[5]
|
||||
data[6]
|
||||
data[7]
|
||||
data[8]
|
||||
integerData[1]
|
||||
integerData[2]
|
||||
integerData[3]
|
||||
integerData[4]
|
||||
integerData[5]
|
||||
integerData[6]
|
||||
integerData[7]
|
||||
integerData[8]
|
||||
|
||||
try encoder.encode(Int8(6))[1]
|
||||
let doubleData = try encoder.encode(2.5)
|
||||
String(doubleData[0], radix: 16)
|
||||
doubleData[1]
|
||||
doubleData[2]
|
||||
doubleData[3]
|
||||
doubleData[4]
|
||||
doubleData[5]
|
||||
doubleData[6]
|
||||
doubleData[7]
|
||||
doubleData[8]
|
||||
|
|
|
|||
Loading…
Reference in a new issue