ByteBackpacker is a small utility written in Swift to pack value types into a Byte
array and unpack them back. Additionally, there is a NSData
extension to convert NSData
objects into a Byte
array.
Byte
is a typealias
for UInt8
.
- Copy the
ByteBackpacker.swift
file (containing theByteBackpacker
class) to your project. - No second step, you are done.
Although it can be used in the same way in Objective-C, I had clearly Swift projects in mind. The easiest way for Objective-C users is to embed the ByteBackpacker.framework
. Of course, Swift users can also do this, but actually I do not see any advantages.
Important for a proper usage: ByteBackpacker does only support value types (e.g. numbers, structs, ...), but no reference types (e.g. classes)! For further information see Discussion.
let aDouble: Double = 1.0
let byteArray: [Byte] = ByteBackpacker.pack(aDouble)
// either without type inference
let doubleFromByteArray: Double = ByteBackpacker.unpack(byteArray)
/* or */ let doubleFromByteArray = ByteBackpacker.unpack(byteArray) as Double
// or with type inference, but explizit type parameter
let doubleFromByteArray = ByteBackpacker.unpack(byteArray, toType: Double.self)
var aDouble: Double = 1.0
let data = NSData(bytes: &aDouble, length: sizeof(Double.self))
let byteArray = data.toByteArray()
let doubleFromByteArray = ByteBackpacker.unpack(byteArray, toType: Double.self)
Byte
is a typealias
for UInt8
.
ByteOrder
is an enum
for Little Endian and Big Endian. Furthermore, there is the option for asking the platform you are using for the native byte order of the system: ByteOrder.nativeByteOrder
. By default .nativeByteOrder
is applied for packing and unpacking.
For packing value types into a [Byte]
, use
class func pack<T>(var value: T, byteOrder: ByteOrder = .nativeByteOrder) -> [Byte]
For unpacking a [Byte]
into a value type, use either
public class func unpack<T>(valueByteArray: [Byte], byteOrder: ByteOrder = .nativeByteOrder) -> T
or otherwise, if you want to use type inference
class func unpack<T>(valueByteArray: [Byte], toType type: T.Type, byteOrder: ByteOrder = .nativeByteOrder) -> T
Unfortunately, there is no suitable option for specifying value types in Swift's generics (see here the discussion on stackoverflow). It would be awesome to specify our methods like func (un)pack<T: Any where T: ~AnyClass>(...)
, but until today Swift does not provide us this opportunities. We will see what the future brings.
I would love to improve this project. Tell me your ideas, here in github, via mail or in codereview.stackexchange.com.
- Find a solution for making sure, that
T
is a value type, but not a reference type - Add documentation to the source code for a nice Xcode integration
- Add more test cases
- Add more examples and how-tos if requested
Thanks to Martin R for his suggestions in codereview.stackexchange.com.
ByteBackpacker is released under the MIT license. See LICENSE for more details.