Skip to content

Instantly share code, notes, and snippets.

@jeffypooo
Created May 20, 2018 03:52
Show Gist options
  • Save jeffypooo/69e30fe652c50662eb8660dd817b85c2 to your computer and use it in GitHub Desktop.
Save jeffypooo/69e30fe652c50662eb8660dd817b85c2 to your computer and use it in GitHub Desktop.
Generic serialization utility for Swift
//
// Binary.swift
//
// Created by Jefferson Jones on 2/14/17.
// Copyright © 2017 Jefferson Jones. All rights reserved.
//
import Foundation
class Binary {
public static func toBytes<T>(_ value: T) -> [UInt8] {
var mv: T = value
let size = MemoryLayout<T>.size
return withUnsafePointer(to: &mv, {
$0.withMemoryRebound(to: UInt8.self, capacity: size, {
Array(UnsafeBufferPointer(start: $0, count: size))
})
})
}
public static func toBytes<T>(_ values: [T]) -> [UInt8] {
var bytes = [UInt8]()
for value in values {
bytes.append(contentsOf: toBytes(value))
}
return bytes
}
public static func fromBytes<T>(_ value: [UInt8], _: T.Type) -> T {
return value.withUnsafeBufferPointer({
$0.baseAddress!.withMemoryRebound(to: T.self, capacity: 1, {
$0.pointee
})
})
}
public static func fromBytes<T>(_ bytes: [UInt8], arrayType type: T.Type) -> [T]? {
guard (bytes.count % MemoryLayout<T>.size) == 0 else {
return nil
}
let valueSize = MemoryLayout<T>.size
var values = [T]()
var i = 0
while (i < bytes.count) {
let slice = (i + valueSize) == bytes.count ? bytes.suffix(from: i) : bytes[i ... i + valueSize]
values.append(fromBytes(slice, type))
i += valueSize
}
return values
}
public static func fromBytes<T>(_ value: ArraySlice<UInt8>, _ type: T.Type) -> T {
return fromBytes([UInt8](value), type)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment