Created
January 16, 2020 15:42
-
-
Save otmb/c70925c2b494af25e1f14f7b30d13ee2 to your computer and use it in GitHub Desktop.
Playground Swift5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
extension OutputStream { | |
func write(data: Data) -> Int { | |
return data.withUnsafeBytes { | |
write($0.bindMemory(to: UInt8.self).baseAddress!, maxLength: data.count) | |
} | |
} | |
var data: Data? { | |
guard let nsData = property(forKey: .dataWrittenToMemoryStreamKey) as? NSData else { | |
return nil | |
} | |
return Data(referencing: nsData) | |
} | |
} | |
extension InputStream { | |
func read(data: inout Data) -> Int { | |
let count = data.count | |
return data.withUnsafeMutableBytes { | |
read($0.bindMemory(to: UInt8.self).baseAddress!, maxLength: count) | |
} | |
} | |
} | |
func byteArray<T>(from value: T) -> [UInt8] where T: FixedWidthInteger { | |
return withUnsafeBytes(of: value.bigEndian) { Array($0) } | |
} | |
extension Data { | |
var uint32:UInt32 { | |
return UInt32(bigEndian: self.withUnsafeBytes { bytes in | |
bytes.load(as: UInt32.self) | |
}) | |
} | |
} | |
struct Bone : Codable { | |
var name: String | |
} | |
let stream = OutputStream(toMemory: ()) | |
stream.open() | |
let b = Bone(name: "hoge") | |
let data = try! JSONEncoder().encode(b) | |
let bytes = Data(byteArray(from: Int32(data.count))) | |
stream.write(data: bytes) | |
stream.write(data: data) | |
let b2 = Bone(name: "fugafuga") | |
let data2 = try! JSONEncoder().encode(b2) | |
let bytes2 = Data(byteArray(from: Int32(data2.count))) | |
stream.write(data: bytes2) | |
stream.write(data: data2) | |
stream.close() | |
let inputBytes : Data = stream.data! | |
let input = InputStream(data: inputBytes) | |
input.open() | |
while(input.hasBytesAvailable){ | |
var d = Data(count: 4) | |
input.read(data: &d) | |
let len = d.uint32 | |
d = Data(count: Int(len)) | |
input.read(data: &d) | |
let json = try! JSONDecoder().decode(Bone.self, from: d) | |
print(json) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment