A CBOR (RFC 7049 Concise Binary Object Representation) decoder and encoder in Swift. Encode directly from Swift types or use a wrapper object. Decode to a CBOR value type that can be accessed with native Swift subscripting and expressed with the equivalent literal notation.
A fully cross-platform Swift 5.x package!
Codable support!
Negative integers are decoded as NegativeInt(UInt), where the actual number is -1 - i (CBOR’s negative integers can be larger than 64-bit signed integers).
Tags are decoded, but not processed. Tagged values are encoded, but not type-checked. Do it yourself :-)
Literal convertibles are defined for the CBOR type!
And subscript too. So you can access CBOR maps and arrays like this: myDecodedObject["numbers"][1].
If you want to decode from a stream, implement the CBORInputStream protocol on your stream and create the decoder like this: CBORDecoder(stream: yourStream).
Half floats can be decoded to a Float, maybe even correctly. Encoding Float16s are not supported (they do not exist in Swift).
Memory efficiency of encoding needs tuning. (Encoding is not typically done in-place.)
Encoding indefinite-length data is supported but you need to explicitly add open and close information to your streaming data.
cbor.me is recommended for viewing your CBOR-encoded data.
Installation
There are many ways: Swift Package Manager, CocoaPods, git submodule…
Encoding a value returns an array of bytes, [UInt8]. You can encode with CBOR.encode(myValue) or myValue.encode(). Any type that conforms to the CBOREncodable protocol may be encoded. You can implement the CBOREncodable protocol for your types and then encode as usual.
CBOR.encode(100) // --> [0x18, 0x64] of type [UInt8]
Int(100).encode() // --> [0x18, 0x64]. Int conforms to the CBOREncodable protocol
"hello".encode() // --> [0x65, 0x68, 0x65, 0x6c, 0x6c, 0x6f]. So does String
CBOR.encode(["a", "b", "c"])
let byteString: [UInt8] = [0x01, 0x02]
CBOR.encode(byteString, asByteString: true)
Due to Swift’s incomplete generics system, you cannot call someArray.encode() or someDictionary.encode(), but you can simply use CBOR.encode(someArrayOrMap) so long as your array items or map key and value types conform to CBOREncodable.
In some cases it may be necessary to create a CBOR intermediate representation before encoding. For example, if you want to encode an array or dictionary containing heterogeneous types, as is common for JSON-like objects, you can’t use native Swift maps yet. You can implement CBOREncodable on your type that would build a CBOR value and encode that, or do the CBOR value thing without CBOREncodable.
The CBOR enum can be expressed with literals, but note that variables are not literals, so you might have to call the constructors manually.
public protocol CBOREncodable {
func encode(options: CBOROptions) -> [UInt8]
}
struct MyStruct: CBOREncodable {
var x: Int
var y: String
public func encode(options: CBOROptions = CBOROption()) -> [UInt8] {
let cborWrapper: CBOR = [
"x": CBOR(integerLiteral: self.x), // You can use the literal constructors
"y": CBOR.utf8String(self.y), // Or the enum variants
"z": 123 // Or literals
]
return cborWrapper.encode()
}
}
MyStruct(x: 42, y: "words").encode()
// --> bytes (as hex): a2 61 79 65 77 6f 72 64 73 61 78 18 2a
The encode function doesn’t have to look like that. If you want to do something custom, like preserving the order of map keys, you can build the [UInt8] manually. Look at the Encoder functions for inspiration.
Encoding API
The current general-purpose API is listed below. When you need fine grained control over the type you are encoding, use the following.
To encode indefinite length arrays, maps, strings, and byte strings, explicitly use the open- and close-stream CBOR values. In between these two values, use encoded array and map chunks with CBOR.encodeArrayChunk and CBOR.encodeMapChunk. Indefinite string and bytestrings can be encoded as normal (i.e. they don’t need their own ‘chunk’ function).
Finally, a technical note on encoding byte string when using the general purpose array encoder, CBOR.encode(..). If the function parameter asByteString is true, then arrays of ALL types EXCEPT UInt8 will be have the raw bytes of each item reversed (but not the order of the items together) if the computer is little endian (CBOR uses big endian or network byte order). Arrays of UInt8, are considered to be already in network byte order.
SwiftCBOR
A CBOR (RFC 7049 Concise Binary Object Representation) decoder and encoder in Swift. Encode directly from Swift types or use a wrapper object. Decode to a CBOR value type that can be accessed with native Swift subscripting and expressed with the equivalent literal notation.
Codable
support!NegativeInt(UInt)
, where the actual number is-1 - i
(CBOR’s negative integers can be larger than 64-bit signed integers).CBOR
type!subscript
too. So you can access CBOR maps and arrays like this:myDecodedObject["numbers"][1]
.CBORInputStream
protocol on your stream and create the decoder like this:CBORDecoder(stream: yourStream)
.Installation
There are many ways: Swift Package Manager, CocoaPods, git submodule…
The CocoaPod is submitted by contributors, updates can be delayed there.
Swift Package Manager is the recommended dependency manager.
Decoding
To unwrap the decoded
CBOR
values, use PATTERN MATCHING!!Encoding
Encoding a value returns an array of bytes,
[UInt8]
. You can encode withCBOR.encode(myValue)
ormyValue.encode()
. Any type that conforms to theCBOREncodable
protocol may be encoded. You can implement theCBOREncodable
protocol for your types and then encode as usual.Due to Swift’s incomplete generics system, you cannot call
someArray.encode()
orsomeDictionary.encode()
, but you can simply useCBOR.encode(someArrayOrMap)
so long as your array items or map key and value types conform toCBOREncodable
.In some cases it may be necessary to create a
CBOR
intermediate representation before encoding. For example, if you want to encode an array or dictionary containing heterogeneous types, as is common for JSON-like objects, you can’t use native Swift maps yet. You can implementCBOREncodable
on your type that would build aCBOR
value and encode that, or do theCBOR
value thing withoutCBOREncodable
.The
CBOR
enum can be expressed with literals, but note that variables are not literals, so you might have to call the constructors manually.The
encode
function doesn’t have to look like that. If you want to do something custom, like preserving the order of map keys, you can build the[UInt8]
manually. Look at the Encoder functions for inspiration.Encoding API
The current general-purpose API is listed below. When you need fine grained control over the type you are encoding, use the following.
Indefinite-length data
To encode indefinite length arrays, maps, strings, and byte strings, explicitly use the open- and close-stream CBOR values. In between these two values, use encoded array and map chunks with
CBOR.encodeArrayChunk
andCBOR.encodeMapChunk
. Indefinite string and bytestrings can be encoded as normal (i.e. they don’t need their own ‘chunk’ function).Note on endian reversal
Finally, a technical note on encoding byte string when using the general purpose array encoder,
CBOR.encode(..)
. If the function parameterasByteString
is true, then arrays of ALL types EXCEPT UInt8 will be have the raw bytes of each item reversed (but not the order of the items together) if the computer is little endian (CBOR uses big endian or network byte order). Arrays of UInt8, are considered to be already in network byte order.Contributing
By participating in this project you agree to follow the Contributor Code of Conduct.
The list of contributors is available on GitHub.
License
This is free and unencumbered software released into the public domain. For more information, please refer to the
UNLICENSE
file or unlicense.org.