I wanted to try implementing message pack in pure swift. Everything worked well until I came to Array.
The approach I had was to implement a protocol called MsgPackMarshable
thats primitiv types extended :
//Protocol
protocol MsgPackMarshable{
func msgpack_marshal() -> Array<Byte>
}
//Implementation for some types
extension UInt8 : MsgPackMarshable{
func msgpack_marshal() -> Array<Byte>{
return [0xcc, self]
}
}
extension UInt16 : MsgPackMarshable{
func msgpack_marshal() -> Array<Byte>{
let bigEndian: UInt16 = self.bigEndian
return [0xcd, Byte((bigEndian & 0xFF00) >> 8), Byte(bigEndian & 0x00FF)]
}
}
extension UInt32 : MsgPackMarshable{
func msgpack_marshal() -> Array<Byte>{
let bigEndian: UInt32 = self.bigEndian
return [0xce, Byte((bigEndian & 0xFF000000) >> 24), Byte((bigEndian & 0xFF0000) >> 16), Byte((bigEndian & 0xFF00) >> 8), Byte(bigEndian & 0x00FF)]
}
}
I had some troubles extending Array
. I wanted to verify dynamically that the type of the array were implementing the MsgPackMarshable
protocol:
extension Array: MsgPackMarshable{
func msgpack_marshal() -> Array<Byte>{
for item in self{
//How to check type here?
}
return []
}
}
Due to the fact that Array
is a struct in swift, I wanted to avoid redefining a new type of Array<MsgPackMarshable>
that embeds an Array.