https://github.com/kennethnym/swiftmpack
SwiftMPack is a swift wrapper around mpack, a fast c message pack library. it also provides a swift implementation of msgpack rpc on top of mpack.
https://github.com/kennethnym/swiftmpack
Last synced: 2 months ago
JSON representation
SwiftMPack is a swift wrapper around mpack, a fast c message pack library. it also provides a swift implementation of msgpack rpc on top of mpack.
- Host: GitHub
- URL: https://github.com/kennethnym/swiftmpack
- Owner: kennethnym
- Created: 2024-08-02T22:40:24.000Z (10 months ago)
- Default Branch: main
- Last Pushed: 2024-08-05T16:31:41.000Z (10 months ago)
- Last Synced: 2025-01-20T06:45:39.648Z (4 months ago)
- Language: C
- Size: 491 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# SwiftMPack
SwiftMPack is a thin Swift wrapper around [`mpack`](https://github.com/ludocode/mpack), providing a more convenient Swift interface to mpack's API,
as well as a msgpack RPC implementation in Swift which mpack lacks.## Usage
### Quick example
```swift
import SwiftMPackstruct Device: Codable {
let name: String
let location: Location
}struct Location: Codable {
let x: Double
let y: Double
}let myDevice = Device(
name: "My iPhone",
location: Location(x: 123, y: 456)
)// myDevice serialized to msgpack bytes
let encodedData = try! MPEncoder.encode(myDevice)// get Device back from msgpack-encoded data
let decodedDevice = try! MPDecoder.decode(Device.self, from: encodedData)
```### Optional handling
By default, optional fields that have `nil` as their values are skipped by Swift and won't be encoded as msgpack nil values.
You can work around this by implementing your own encode method within your `Codable` structs/classes.
The example below is borroed from this [StackOverflow answer](https://stackoverflow.com/questions/47266862/encode-nil-value-as-null-with-jsonencoder/47268112).
Although the question was about JSON encoding, the same logic applies with SwiftMPack as they both work with the Codable protocol.```swift
struct Foo: Codable {
var string: String? = nil
var number: Int = 1func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(number, forKey: .number)
try container.encode(string, forKey: .string)
}
}
```